pax_global_header00006660000000000000000000000064131562267100014515gustar00rootroot0000000000000052 comment=5a32f9a3f9e10c882ec1b4f493d82093ffffd6c1 osr-common-osr-common-3.0.8/000077500000000000000000000000001315622671000157055ustar00rootroot00000000000000osr-common-osr-common-3.0.8/.gitignore000066400000000000000000000001061315622671000176720ustar00rootroot00000000000000**/.classpath **/.project **/.settings/ **/target/ **/.idea/ **/*.iml osr-common-osr-common-3.0.8/CHANGELOG.md000066400000000000000000000030111315622671000175110ustar00rootroot00000000000000# Change Log ## 3.0.7 - 2017-09-13 ### Changed - Running maven gpg plugin verify phase, not in package phase ## 3.0.7 - 2017-09-13 ### Changed - Added jenkins profile which generates coverage reports when build in Jenkins. ## 3.0.6 - 2017-06-14 ### Fixed - Added missing descriptions to pom.xml files. The release to oss.sonatype.org was failing with a validation error that complained about the missing descriptions. ## 3.0.5 - 2017-02-06 ### Fixed - Fixed issue #1: "Comparison method violates its general contract" in VisitorLogic.sweepCache by replacing Java sort with quick select. ## 3.0.4 - 2017-01-16 ### Changed - Disabled Java 8 doclint by default in tooling pom - bin/release script accepts -a option to specify alternative deployment repository - bin/release script "deploy-signed-release-locally" is now optional - bin/release script can work with master and develop branches that are called differently ## 3.0.3 - 2016-06-07 ### Added - BinaryPrefix can return value as double (getDoubleValue()) ### Fixed - NodeDeepComparer reported differences when ignored (xmlns) attributes were present - NodeDeepComparer failed when comparing elements with and without prefix ## 3.0.2 - 2016-05-03 ### Added - Helper classes for metrics collection - AccumulatingRingBufferDouble - AccumulatingRingBufferLong - SpeedMeter - StopWatch2 - Helper class GitRepositoryState for parsing repository state as produced by the maven-git-commit-id-plugin - NodeDeepComparer (subclass of DeepComparer) for org.w3c.dom.Node osr-common-osr-common-3.0.8/LICENSE000066400000000000000000000261361315622671000167220ustar00rootroot00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. osr-common-osr-common-3.0.8/parser-toolkit-parent/000077500000000000000000000000001315622671000221535ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/bin/000077500000000000000000000000001315622671000227235ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/bin/trace-indent.py000077500000000000000000000023401315622671000256540ustar00rootroot00000000000000#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright 2011 The Open Source Research Group, # University of Erlangen-Nürnberg # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import sys silent = -1 indent = 0 for line in sys.stdin.readlines(): if line.startswith('exit'): indent -= 1 if False: #hideRx.search(line) != None: if silent == -1: silent = indent elif silent == indent: silent = -1 if silent == -1 or silent == indent: if line.startswith('enter') or line.startswith('exit') or line.startswith('lookup') or indent < 1: print(' ' * (2 * indent) + line, end="") else: print('! ' + ' ' * (2 * (indent - 1)) + line, end="") if line.startswith('enter'): indent += 1 osr-common-osr-common-3.0.8/parser-toolkit-parent/doc/000077500000000000000000000000001315622671000227205ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/doc/kate-rats-syntax-highlighting.xml000066400000000000000000000322171315622671000313310ustar00rootroot00000000000000 public protected private transient memoized inline noinline constant stateful withLocation stateful resetting ignoringCase flatten variant withParseTree verbose nowarn parser factory visibility rawTypes main printer setOfString flag genericAsVoid dump explicit osr-common-osr-common-3.0.8/parser-toolkit-parent/pom.xml000066400000000000000000000123151315622671000234720ustar00rootroot00000000000000 4.0.0 de.fau.cs.osr tooling 3.0.8 ../tooling/ de.fau.cs.osr.ptk parser-toolkit-parent pom Parser Toolkit Parent POM 2009 The parser toolkit provides basic facilities for AST building, traversal, persistence and more. ptk-common ptk-json-tools ptk-xml-tools ptk-xpath ../tooling/ true 1.15.0 1.4.8 1.3.0.1 3.0.8 xtc rats-runtime ${rats-runtime.version} com.thoughtworks.xstream xstream ${xstream.version} de.fau.cs.osr.utils utils ${osr-common.version} de.fau.cs.osr.ptk ptk-common ${osr-common.version} de.fau.cs.osr.maven.plugins maven-rats-plugin ${maven-rats-plugin.version} rats-generate generate-sources generate jenkins env.BUILD_NUMBER org.codehaus.mojo cobertura-maven-plugin ${cobertura-maven-plugin.version} xml true true package cobertura osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/000077500000000000000000000000001315622671000242375ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/pom.xml000066400000000000000000000047631315622671000255660ustar00rootroot00000000000000 4.0.0 de.fau.cs.osr.ptk parser-toolkit-parent 3.0.8 ptk-common jar PTK - Common 2009 The parser toolkit common module provides the basic facilities for AST building, traversal, persistence and more. ../../tooling/ xtc rats-runtime de.fau.cs.osr.utils utils junit junit test osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/000077500000000000000000000000001315622671000250265ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/main/000077500000000000000000000000001315622671000257525ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/main/java/000077500000000000000000000000001315622671000266735ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/main/java/de/000077500000000000000000000000001315622671000272635ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/main/java/de/fau/000077500000000000000000000000001315622671000300365ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/main/java/de/fau/cs/000077500000000000000000000000001315622671000304435ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/main/java/de/fau/cs/osr/000077500000000000000000000000001315622671000312465ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/main/java/de/fau/cs/osr/ptk/000077500000000000000000000000001315622671000320445ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/main/java/de/fau/cs/osr/ptk/common/000077500000000000000000000000001315622671000333345ustar00rootroot00000000000000AstEntityMap.java000066400000000000000000000021171315622671000365030ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/main/java/de/fau/cs/osr/ptk/common/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import de.fau.cs.osr.ptk.common.ast.AstNode; public interface AstEntityMap> { public abstract int registerEntity(T entity); public abstract T getEntity(int id); public abstract Set> getEntities(); public abstract Map getMap(); public abstract boolean isEmpty(); } AstEntityMapImpl.java000066400000000000000000000047361315622671000373360ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/main/java/de/fau/cs/osr/ptk/common/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common; import java.io.Serializable; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import de.fau.cs.osr.ptk.common.ast.AstNode; public class AstEntityMapImpl> implements Serializable, AstEntityMap { private static final long serialVersionUID = 1L; private HashMap entityMap = new HashMap(); // ========================================================================= @Override public int registerEntity(T entity) { int id = entityMap.size(); entityMap.put(id, entity); return id; } @Override public T getEntity(int id) { return entityMap.get(id); } @Override public Set> getEntities() { return Collections.unmodifiableSet(entityMap.entrySet()); } @Override public Map getMap() { return Collections.unmodifiableMap(entityMap); } @Override public boolean isEmpty() { return this.entityMap.isEmpty(); } // ========================================================================= @Override public String toString() { return "EntityMap " + entityMap; } // ========================================================================= @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((entityMap == null) ? 0 : entityMap.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; AstEntityMapImpl other = (AstEntityMapImpl) obj; if (entityMap == null) { if (other.entityMap != null) return false; } else if (!entityMap.equals(other.entityMap)) return false; return true; } } AstPrinter.java000066400000000000000000000205361315622671000362210ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/main/java/de/fau/cs/osr/ptk/common/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common; import java.io.StringWriter; import java.io.Writer; import java.util.Collection; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.TreeMap; import de.fau.cs.osr.ptk.common.ast.AstLeafNode; import de.fau.cs.osr.ptk.common.ast.AstNode; import de.fau.cs.osr.ptk.common.ast.AstNodeList; import de.fau.cs.osr.ptk.common.ast.AstNodePropertyIterator; import de.fau.cs.osr.ptk.common.ast.AstStringNode; import de.fau.cs.osr.ptk.common.ast.AstText; import de.fau.cs.osr.utils.PrinterBase; import de.fau.cs.osr.utils.PrinterBase.Memoize; import de.fau.cs.osr.utils.PrinterBase.OutputBuffer; import de.fau.cs.osr.utils.StringTools; public class AstPrinter> extends AstVisitor { public void visit(AstNode n) { Memoize m = p.memoizeStart(n); if (m != null) { if (n.isEmpty() && !hasVisibleProperties(n)) { p.indent(n.getNodeName()); p.println("()"); } else { printNode(n); } p.memoizeStop(m); } } public void visit(AstLeafNode n) { if (n.isEmpty() && !hasVisibleProperties(n)) { p.indent(n.getNodeName()); p.println("()"); } else { printNode(n); } } public void visit(AstText n) { if (!hasVisibleProperties(n)) { p.indent('"'); p.print(StringTools.escJava(n.getContent())); p.println('"'); } else { printNode(n); } } public void visit(AstStringNode n) { if (!hasVisibleProperties(n)) { p.indent(n.getNodeName()); p.print("(\""); p.print(StringTools.escJava(n.getContent())); p.println("\")"); } else { printNode(n); } } public void visit(AstNodeList n) { Memoize m = p.memoizeStart(n); if (m != null) { String name = ""; if (n.getNodeType() != AstNode.NT_NODE_LIST) name = n.getNodeName(); if (hasVisibleProperties(n)) { printNode(n); } else if (n.isEmpty()) { p.indent(name); p.println("[]"); } else { boolean singleLine = false; if (isCompact() && n.size() <= 1) { OutputBuffer b = p.outputBufferStart(); printListOfNodes(n); b.stop(); String output = b.getBuffer().trim(); if (isSingleLine(output)) { p.indent(name); p.print("[ "); p.print(output); p.println(" ]"); singleLine = true; } } if (!singleLine) { p.indent(name); p.println('['); p.incIndent(); printListOfNodes(n); p.decIndent(); p.indentln(']'); } } p.memoizeStop(m); } } // ========================================================================= protected boolean hasVisibleProperties(AstNode n) { if (n.hasAttributes()) { return true; } else { // Shortcuts int count = n.getPropertyCount(); if (count > 2) return true; if (count == 0) return false; AstNodePropertyIterator i = n.propertyIterator(); while (i.next()) { if (i.getName().equals("rtd")) { if (i.getValue() != null) return true; } else if (!i.getName().equals("content") || !(n instanceof AstStringNode)) { return true; } } return false; } } protected void printNode(AstNode n) { p.indent(n.getNodeName()); p.println('('); p.incIndent(); printNodeContent(n); p.decIndent(); p.indentln(')'); } protected void printNodeContent(AstNode n) { if (hasVisibleProperties(n)) printProperties(n); printListOfNodes(n); } protected void printProperties(AstNode n) { Map props = new TreeMap(); for (Entry entry : n.getAttributes().entrySet()) props.put("{A} " + entry.getKey(), entry.getValue()); AstNodePropertyIterator i = n.propertyIterator(); while (i.next()) { if (i.getValue() != null || !i.getName().equals("rtd")) props.put("{P} " + i.getName(), i.getValue()); } for (Entry entry : props.entrySet()) { p.indent(entry.getKey()); p.print(" = "); p.eatNewlinesAndIndents(1); printPropertyValue(entry.getValue()); p.clearEatNewlinesAndIndents(); } } protected void printPropertyValue(Object value) { if (value == null) { p.indentln("null"); } else if (value instanceof String) { p.indent('"'); p.print(StringTools.escJava((String) value)); p.println('"'); } else if (value instanceof AstNode) { p.incIndent(); @SuppressWarnings("unchecked") T node = (T) value; dispatch(node); p.decIndent(); } else if (value instanceof AstEntityMap) { @SuppressWarnings("unchecked") AstEntityMap map = (AstEntityMap) value; printEntityMap(map); } else if (value instanceof Collection) { printCollection((Collection) value); } else { p.indentln(value.toString()); } } protected void printEntityMap(AstEntityMap entityMap) { if (entityMap.getMap().isEmpty()) { p.indentln("-"); } else { Map map = new TreeMap(entityMap.getMap()); p.indentln("{"); p.incIndent(); for (Iterator> k = map.entrySet().iterator(); k.hasNext();) { Entry entry = k.next(); p.indent('['); p.print(entry.getKey().toString()); p.print("] = "); p.eatNewlinesAndIndents(1); printPropertyValue(entry.getValue()); p.clearEatNewlinesAndIndents(); p.ignoreNewlines(); p.println(k.hasNext() ? "," : ""); } p.decIndent(); p.indentln('}'); } } protected void printCollection(Collection c) { if (c.isEmpty()) { p.indentln("C[]"); } else { boolean singleLine = false; if (isCompact() && c.size() == 1) { OutputBuffer b = p.outputBufferStart(); printPropertyValue(c.toArray()[0]); b.stop(); String output = b.getBuffer().trim(); if (isSingleLine(output)) { p.indent("C[ "); p.print(output); p.println(" ]"); singleLine = true; } } if (!singleLine) { p.indentln("C["); p.incIndent(); for (Iterator k = c.iterator(); k.hasNext();) { printPropertyValue(k.next()); p.ignoreNewlines(); p.println(k.hasNext() ? "," : ""); } p.decIndent(); p.indentln(']'); } } } protected void printListOfNodes(AstNode n) { int j = 0; String[] childNames = n.getChildNames(); for (Iterator i = n.iterator(); i.hasNext();) { if (!n.isList()) { p.indent(childNames[j++]); } else { p.indent('['); p.print(String.valueOf(j++)); p.print(']'); } p.print(" = "); p.eatNewlinesAndIndents(1); dispatch(i.next()); p.clearEatNewlinesAndIndents(); p.ignoreNewlines(); p.println(i.hasNext() ? "," : ""); } } // ========================================================================= protected boolean isSingleLine(String text) { return (text.indexOf('\n') == -1) && (text.indexOf('\r') == -1); } // ========================================================================= public static > String print(T node) { return print(new StringWriter(), node).toString(); } public static > Writer print(Writer writer, T node) { new AstPrinter(writer).go(node); return writer; } // ========================================================================= protected final PrinterBase p; public AstPrinter(Writer writer) { this.p = new PrinterBase(writer); this.p.setMemoize(true); this.setCompact(true); } @Override protected Object after(T node, Object result) { p.flush(); return result; } // ========================================================================= private boolean compact = true; public void setCompact(boolean compact) { this.compact = compact; } public boolean isCompact() { return compact; } } AstVisitor.java000066400000000000000000000063511315622671000362340ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/main/java/de/fau/cs/osr/ptk/common/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common; import java.util.ArrayList; import java.util.List; import java.util.ListIterator; import de.fau.cs.osr.ptk.common.ast.AstNode; import de.fau.cs.osr.utils.visitor.VisitorBase; import de.fau.cs.osr.utils.visitor.VisitorLogic; public class AstVisitor> extends VisitorBase { public static final Object REMOVE = new Object(); // ========================================================================= public AstVisitor() { } public AstVisitor(VisitorLogic logic) { super(logic); } // ========================================================================= /** * Dispatches to the appropriate visit() method and returns the result of * the visitation. If the given node is null this method * returns immediately with null as result. */ protected Object dispatch(T node) { if (node == null) throw new NullPointerException(); return resolveAndVisit(node); } // ========================================================================= protected void iterate(T node) { if (node == null) throw new NullPointerException(); for (T n : node) dispatch(n); } protected List map(T node) { if (node == null) throw new NullPointerException(); List result = new ArrayList(node.size()); for (T n : node) result.add(dispatch(n)); return result; } /** * Iterates over the children of an AST node and replaces each child node * with the result of the visitation of the respective child. If the given * AST node is a NodeList, the call will be passed to mapInPlace(NodeList) * which has special semantics. */ protected void mapInPlace(T node) { if (node == null) throw new NullPointerException(); if (node.isList()) { ListIterator i = node.listIterator(); while (i.hasNext()) { T current = i.next(); Object result = dispatch(current); if (result == null) { throw new NullPointerException(); } else if (result == REMOVE) { i.remove(); } else { if (result == current) continue; @SuppressWarnings("unchecked") T resultNode = (T) result; if (resultNode.getNodeType() == AstNode.NT_NODE_LIST) { i.remove(); i.add(resultNode); } else { i.set(resultNode); } } } } else { ListIterator i = node.listIterator(); while (i.hasNext()) { T current = i.next(); @SuppressWarnings("unchecked") T result = (T) dispatch(current); if (result != current) i.set(result); } } } } NodeTypeAstVisitor.java000066400000000000000000000104021315622671000376740ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/main/java/de/fau/cs/osr/ptk/common/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common; import java.util.ArrayList; import java.util.List; import java.util.ListIterator; import de.fau.cs.osr.ptk.common.ast.AstNode; import de.fau.cs.osr.ptk.common.ast.AstNodeList; import de.fau.cs.osr.ptk.common.ast.AstParserEntity; import de.fau.cs.osr.ptk.common.ast.AstText; import de.fau.cs.osr.utils.visitor.VisitingException; public class NodeTypeAstVisitor> { public static final Object REMOVE = new Object(); // ========================================================================= public Object go(T node) { return dispatch(node); } // ========================================================================= /** * Dispatches to the appropriate visit() method and returns the result of * the visitation. If the given node is null this method * returns immediately with null as result. */ protected final Object dispatch(T node) { if (node == null) throw new NullPointerException(); try { return resolveAndVisit(node, node.getNodeType()); } catch (VisitingException e) { throw e; } catch (Exception e) { throw new VisitingException(node, e); } } protected final void iterate(T node) { if (node == null) throw new NullPointerException(); for (T n : node) dispatch(n); } protected final List map(T node) { if (node == null) throw new NullPointerException(); List result = new ArrayList(node.size()); for (T n : node) result.add(dispatch(n)); return result; } /** * Iterates over the children of an AST node and replaces each child node * with the result of the visitation of the respective child. If the given * AST node is a WtNodeList, the call will be passed to * mapInPlace(WtNodeList) which has special semantics. */ protected final void mapInPlace(T node) { if (node == null) throw new NullPointerException(); if (node.isList()) { ListIterator i = node.listIterator(); while (i.hasNext()) { T current = i.next(); Object result = dispatch(current); if (result == null) { throw new NullPointerException(); } else if (result == REMOVE) { i.remove(); } else { if (result == current) continue; @SuppressWarnings("unchecked") T resultNode = (T) result; if (resultNode.getNodeType() == AstNode.NT_NODE_LIST) { i.remove(); i.add(resultNode); } else { i.set(resultNode); } } } } else { ListIterator i = node.listIterator(); while (i.hasNext()) { T current = i.next(); @SuppressWarnings("unchecked") T result = (T) dispatch(current); if (result != current) i.set(result); } } } // ========================================================================= protected Object resolveAndVisit(T node, int type) throws Exception { switch (type) { case T.NT_TEXT: return visit((AstText) node); case T.NT_NODE_LIST: return visit((AstNodeList) node); case T.NT_PARSER_ENTITY: return visit((AstParserEntity) node); default: return visitUnspecific(node); } } // ========================================================================= protected Object visitUnspecific(AstNode node) throws Exception { return node; } protected Object visit(AstText node) throws Exception { return visitUnspecific(node); } protected Object visit(AstNodeList node) throws Exception { return visitUnspecific(node); } protected Object visit(AstParserEntity node) throws Exception { return visitUnspecific(node); } } ParserCommon.java000066400000000000000000000032011315622671000365210ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/main/java/de/fau/cs/osr/ptk/common/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common; import java.util.Collection; import java.util.LinkedList; import java.util.List; import de.fau.cs.osr.ptk.common.ast.AstNode; public abstract class ParserCommon> implements ParserInterface { private final List> visitors = new LinkedList>(); // ========================================================================= @Override public List> getVisitors() { return visitors; } @Override public ParserInterface addVisitor(AstVisitor v) { visitors.add(v); return this; } @Override public ParserInterface addVisitors(Collection> v) { visitors.addAll(v); return this; } public abstract Object getConfig(); @SuppressWarnings("unchecked") protected T process(T n) { T result = n; for (AstVisitor v : getVisitors()) { Object o = v.go(result); if (o instanceof AstNode) result = (T) o; } return result; } } ParserContext.java000066400000000000000000000024201315622671000367170ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/main/java/de/fau/cs/osr/ptk/common/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common; public abstract class ParserContext { /** * Initializes the root parser context. An implementation of this method has * to initialize all fields of the context and must not rely on * default initializations since context class instances are reused. */ public abstract void clear(); /** * Initializes any non-root parser context. An implementation of this method * has to initialize all fields of the context and must not rely on * default initializations since context class instances are reused. */ public void init(ParserContext parent) { clear(); } } ParserInterface.java000066400000000000000000000022521315622671000371760ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/main/java/de/fau/cs/osr/ptk/common/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common; import java.io.IOException; import java.util.Collection; import java.util.List; import de.fau.cs.osr.ptk.common.ast.AstNode; import xtc.parser.ParseException; public interface ParserInterface> { public Object parseArticle(String src, String title) throws IOException, ParseException; public List> getVisitors(); public ParserInterface addVisitor(AstVisitor v); public ParserInterface addVisitors(Collection> v); } ParserState.java000066400000000000000000000041651315622671000363630ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/main/java/de/fau/cs/osr/ptk/common/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common; import de.fau.cs.osr.utils.ArrayStack; import de.fau.cs.osr.utils.Utils; import xtc.util.State; public class ParserState implements State { private final Class contextClass; private final ArrayStack stack = new ArrayStack(16, 16); private final ArrayStack pool; // ========================================================================= public ParserState() { this.contextClass = null; this.pool = null; start(); } public ParserState(Class contextClass) { this.contextClass = contextClass; this.pool = new ArrayStack(16, 16); start(); } // ========================================================================= public final C getTop() { return stack.peek(); } public final void reset(String file) { stack.clear(); } public final void start() { if (stack.isEmpty()) { push(); stack.peek().clear(); } else { C last = stack.peek(); push(); stack.peek().init(last); } } public final void commit() { pop(); } public final void abort() { pop(); } // ========================================================================= protected C instantiateContext() { return pool.isEmpty() ? Utils.getInstance(contextClass) : pool.pop(); } private final void push() { stack.push(instantiateContext()); } private final void pop() { if (pool != null) { pool.push(stack.pop()); } else { stack.pop(); } } } PrinterInterface.java000066400000000000000000000021721315622671000373660ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/main/java/de/fau/cs/osr/ptk/common/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common; import java.io.IOException; import java.io.Writer; public interface PrinterInterface { public void print(Object ast, Writer out) throws IOException; /** * Return a name describing the type of text which the printer produces. For * a pretty printer this could be "wikitext", while for a printer which * dumps an AST this could be "ast". The extension should be suitable as * file extension! */ public String getPrintoutType(); } Warning.java000066400000000000000000000064101315622671000355260ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/main/java/de/fau/cs/osr/ptk/common/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common; import java.io.Serializable; import de.fau.cs.osr.ptk.common.ast.Span; public abstract class Warning implements Serializable { private static final long serialVersionUID = 1L; private final Span span; private final String origin; private final String message; // ========================================================================= public Warning() { this(new Span(), "Unknown origin", "Unknown warning."); } public Warning(Span span, String origin, String message) { this.span = span; this.origin = origin; this.message = message; } public Warning(Span span, Class origin, String message) { this(span, origin.getSimpleName(), message); } // ========================================================================= public Span getSpan() { return span; } public String getOrigin() { return origin; } public String getMessage() { return message; } // ========================================================================= @Override public String toString() { String span = spanToString(); String message = messageToString(); return "Warning: " + span + " : " + message; } protected String spanToString() { String span = ""; if (this.span != null) span = this.span.toString(); return span; } protected String messageToString() { String message = this.message; if (message == null || message.isEmpty()) message = ""; switch (message.charAt(message.length() - 1)) { case '.': case '?': case '!': break; default: message += "."; } return message; } // ========================================================================= @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((message == null) ? 0 : message.hashCode()); result = prime * result + ((origin == null) ? 0 : origin.hashCode()); result = prime * result + ((span == null) ? 0 : span.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Warning other = (Warning) obj; if (message == null) { if (other.message != null) return false; } else if (!message.equals(other.message)) return false; if (origin == null) { if (other.origin != null) return false; } else if (!origin.equals(other.origin)) return false; if (span == null) { if (other.span != null) return false; } else if (!span.equals(other.span)) return false; return true; } } ast/000077500000000000000000000000001315622671000340445ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/main/java/de/fau/cs/osr/ptk/commonAstAbstractInnerNode.java000066400000000000000000000167541315622671000407410ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/main/java/de/fau/cs/osr/ptk/common/ast/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common.ast; import java.io.IOException; import xtc.tree.Location; public abstract class AstAbstractInnerNode> extends AstNodeImpl implements AstInnerNode { private static final long serialVersionUID = 3931233748530723300L; protected AstAbstractInnerNode() { } protected AstAbstractInnerNode(Location arg0) { super(arg0); } @Override public S get(int index, Class clazz) { @SuppressWarnings("unchecked") S value = (S) get(index); return value; } // ========================================================================= public abstract String[] getChildNames(); // ========================================================================= @Override public void toString(Appendable out) throws IOException { out.append(getClass().getSimpleName()); out.append('('); for (int i = 0; i < size(); ++i) { if (i != 0) out.append(", "); out.append('['); out.append(String.valueOf(i)); out.append("] = "); T child = get(i); if (child == null) out.append("null"); else child.toString(out); } out.append(')'); } // ========================================================================= public static abstract class AstInnerNode1> extends AstAbstractInnerNode { private static final long serialVersionUID = -8841086798545623538L; private T n0; protected AstInnerNode1(Uninitialized u) { } protected AstInnerNode1(Location arg0) { super(arg0); } protected AstInnerNode1(T n0) { super(); set(0, n0); } protected AstInnerNode1(Location arg0, T n0) { super(arg0); set(0, n0); } @Override public final int size() { return 1; } @Override public T get(int index) { switch (index) { case 0: return n0; default: throw new IndexOutOfBoundsException( "Size: " + size() + ", Index: " + index); } } @Override public T set(int index, T n) { if (n == null) throw new NullPointerException("node may not be null"); T o; switch (index) { case 0: o = n0; n0 = n; break; default: throw new IndexOutOfBoundsException( "Size: " + size() + ", Index: " + index); } return o; } @Override public T remove(int index) { return set(index, null); } } // ========================================================================= public static abstract class AstInnerNode2> extends AstAbstractInnerNode { private static final long serialVersionUID = 6501151075140985136L; private T n0; private T n1; protected AstInnerNode2(Uninitialized u) { } protected AstInnerNode2(Location arg0) { super(arg0); } protected AstInnerNode2(T n0, T n1) { super(); set(0, n0); set(1, n1); } protected AstInnerNode2( Location arg0, T n0, T n1) { super(arg0); set(0, n0); set(1, n1); } @Override public final int size() { return 2; } @Override public T get(int index) { switch (index) { case 0: return n0; case 1: return n1; default: throw new IndexOutOfBoundsException( "Size: " + size() + ", Index: " + index); } } @Override public T set(int index, T n) { if (n == null) throw new NullPointerException("node may not be null"); T o; switch (index) { case 0: o = n0; n0 = n; break; case 1: o = n1; n1 = n; break; default: throw new IndexOutOfBoundsException( "Size: " + size() + ", Index: " + index); } return o; } @Override public T remove(int index) { return set(index, null); } } // ========================================================================= public static abstract class AstInnerNode3> extends AstAbstractInnerNode { private static final long serialVersionUID = 7450920544821225168L; private T n0; private T n1; private T n2; protected AstInnerNode3(Uninitialized u) { } protected AstInnerNode3(Location arg0) { super(arg0); } protected AstInnerNode3( T n0, T n1, T n2) { super(); set(0, n0); set(1, n1); set(2, n2); } protected AstInnerNode3( Location arg0, T n0, T n1, T n2) { super(arg0); set(0, n0); set(1, n1); set(2, n2); } @Override public final int size() { return 3; } @Override public T get(int index) { switch (index) { case 0: return n0; case 1: return n1; case 2: return n2; default: throw new IndexOutOfBoundsException( "Size: " + size() + ", Index: " + index); } } @Override public T set(int index, T n) { if (n == null) throw new NullPointerException("node may not be null"); T o; switch (index) { case 0: o = n0; n0 = n; break; case 1: o = n1; n1 = n; break; case 2: o = n2; n2 = n; break; default: throw new IndexOutOfBoundsException( "Size: " + size() + ", Index: " + index); } return o; } @Override public T remove(int index) { return set(index, null); } } // ========================================================================= public static abstract class AstInnerNode4> extends AstAbstractInnerNode { private static final long serialVersionUID = -6518009272746861741L; private T n0; private T n1; private T n2; private T n3; protected AstInnerNode4(Uninitialized u) { } protected AstInnerNode4(Location arg0) { super(arg0); } protected AstInnerNode4( T n0, T n1, T n2, T n3) { super(); set(0, n0); set(1, n1); set(2, n2); set(3, n3); } protected AstInnerNode4( Location arg0, T n0, T n1, T n2, T n3) { super(arg0); set(0, n0); set(1, n1); set(2, n2); set(3, n3); } @Override public final int size() { return 4; } @Override public T get(int index) { switch (index) { case 0: return n0; case 1: return n1; case 2: return n2; case 3: return n3; default: throw new IndexOutOfBoundsException( "Size: " + size() + ", Index: " + index); } } @Override public T set(int index, T n) { if (n == null) throw new NullPointerException("node may not be null"); T o; switch (index) { case 0: o = n0; n0 = n; break; case 1: o = n1; n1 = n; break; case 2: o = n2; n2 = n; break; case 3: o = n3; n3 = n; break; default: throw new IndexOutOfBoundsException( "Size: " + size() + ", Index: " + index); } return o; } @Override public T remove(int index) { return set(index, null); } } } AstChildIterator.java000066400000000000000000000021361315622671000401160ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/main/java/de/fau/cs/osr/ptk/common/ast/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common.ast; import java.util.ListIterator; interface AstChildIterator> extends ListIterator { /** * Returns the child last returned by a call to previous() or next(). This * method can only be called after previous() or next() have been called and * must not be called after a call to remove() or add(). */ public T get(); /** * Resets the iterator. */ public void reset(); } AstInnerNode.java000066400000000000000000000014231315622671000372400ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/main/java/de/fau/cs/osr/ptk/common/ast/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common.ast; public interface AstInnerNode> extends AstNode { } AstLeafNode.java000066400000000000000000000014221315622671000370330ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/main/java/de/fau/cs/osr/ptk/common/ast/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common.ast; public interface AstLeafNode> extends AstNode { } AstLeafNodeImpl.java000066400000000000000000000030171315622671000376570ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/main/java/de/fau/cs/osr/ptk/common/ast/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common.ast; import java.io.IOException; import xtc.tree.Location; public abstract class AstLeafNodeImpl> extends AstNodeImpl implements AstLeafNode { private static final long serialVersionUID = 3078845253977311630L; // ========================================================================= protected AstLeafNodeImpl() { } protected AstLeafNodeImpl(Location arg0) { super(arg0); } @Override public int size() { return 0; } // ========================================================================= public final String[] getChildNames() { return EMPTY_CHILD_NAMES; } // ========================================================================= @Override public void toString(Appendable out) throws IOException { out.append(getClass().getSimpleName()); out.append("()"); } } AstLocation.java000066400000000000000000000072341315622671000371350ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/main/java/de/fau/cs/osr/ptk/common/ast/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common.ast; import java.io.Serializable; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.net.URLEncoder; import de.fau.cs.osr.utils.WrappedException; public class AstLocation implements Serializable { private static final long serialVersionUID = 1L; private final String file; private final int line; private final int column; // ========================================================================= public AstLocation() { this.file = ""; this.line = -1; this.column = -1; } public AstLocation(String file, int line, int column) { this.file = file; this.line = line; this.column = column; } public AstLocation(AstLocation location) { this.file = location.file; this.line = location.line; this.column = location.column; } public AstLocation(xtc.tree.Location location) { this.file = location.file; this.line = location.line; this.column = location.column; } // ========================================================================= @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + column; result = prime * result + ((file == null) ? 0 : file.hashCode()); result = prime * result + line; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; AstLocation other = (AstLocation) obj; if (column != other.column) return false; if (file == null) { if (other.file != null) return false; } else if (!file.equals(other.file)) return false; if (line != other.line) return false; return true; } @Override public String toString() { String file = getFile(); if (file == null) return getLine() + ":" + getColumn(); try { return URLEncoder.encode(file, "UTF-8") + ":" + getLine() + ":" + getColumn(); } catch (UnsupportedEncodingException e) { throw new WrappedException(e); } } public static AstLocation valueOf(String s) { int line; int column; String file = null; int i = s.indexOf(':'); if (i == -1) return null; int j = s.indexOf(':', i + 1); if (j == -1) { line = Integer.parseInt(s.substring(0, i)); column = Integer.parseInt(s.substring(i + 1)); } else { try { file = URLDecoder.decode(s.substring(0, i), "UTF-8"); } catch (UnsupportedEncodingException e) { throw new WrappedException(e); } line = Integer.parseInt(s.substring(i + 1, j)); column = Integer.parseInt(s.substring(j + 1)); } return new AstLocation(file, line, column); } // ========================================================================= public boolean isValid() { return line != -1; } public String getFile() { return file; } public int getLine() { return line; } public int getColumn() { return column; } public xtc.tree.Location toXtcLocation() { return new xtc.tree.Location(file, line, column); } } AstNode.java000066400000000000000000000074101315622671000362460ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/main/java/de/fau/cs/osr/ptk/common/ast/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common.ast; import java.io.IOException; import java.io.Serializable; import java.util.List; import xtc.tree.Locatable; import xtc.util.Pair; public interface AstNode> extends AstNodeAttributeInterface, AstNodePropertyInterface, Locatable, Cloneable, Serializable, List { public static final int NT_CUSTOM_BIT = 0x10000; public static final int NT_UNTYPED = -1; public static final int NT_NODE_LIST = 0x002; public static final int NT_PARSER_ENTITY = 0x005; public static final int NT_TUPLE_1 = 0x101; public static final int NT_TUPLE_2 = 0x102; public static final int NT_TUPLE_3 = 0x103; public static final int NT_TUPLE_4 = 0x104; public static final int NT_TUPLE_5 = 0x105; public static final int NT_TEXT = 0x1001; // ========================================================================= public static final String[] EMPTY_CHILD_NAMES = new String[0]; // ========================================================================= /** * Returns an integer value that identifies the node type. It's the * programmers responsibility to make sure these values are unique. */ public int getNodeType(); /** * Returns true if the given node type equals the node type * returned by getNodeType(). */ public boolean isNodeType(int testType); /** * Returns the fully qualified name of this node's class. */ public String getNodeTypeName(); /** * Returns the name of this node. The name is the simple name of the node's * class. */ public String getNodeName(); // ========================================================================= // native location public AstLocation getNativeLocation(); public void setNativeLocation(AstLocation location); // ========================================================================= /** * Appends all items from the given list to list of children. * * @return Returns true if the list of children has changed. */ public boolean addAll(Pair p); /** * Same as get(index) but casts the node to the specified type. */ public S get(int index, Class clazz); /** * Determine whether this node can have a variable number of children and * implements the {@link List} interface (or parts of it). */ public boolean isList(); /** * Returns the names of the children. This method may only be called for * nodes with a fixed number of children (isList() returns false). */ public String[] getChildNames(); // ========================================================================= // Object public void toString(Appendable out) throws IOException; public boolean equals(Object obj); // ========================================================================= public Object clone() throws CloneNotSupportedException; public AstNode cloneWrapException(); /** * Only children and children's children are cloned by this method. Property * and attribute values are just copied. */ public AstNode deepClone() throws CloneNotSupportedException; public AstNode deepCloneWrapException(); } AstNodeAttributeInterface.java000066400000000000000000000123131315622671000417510ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/main/java/de/fau/cs/osr/ptk/common/ast/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common.ast; import java.util.Map; public interface AstNodeAttributeInterface { /** * Tell whether this node has any attributes attached. * * @return True if this node has any attributes attached, * otherwise false. */ public abstract boolean hasAttributes(); /** * Retrieve the attributes as an unmodifiable map. * * @return The map of attributes attached to this node. */ public abstract Map getAttributes(); /** * Set the attributes for this node. * * @param attrs * The attributes to attach to this node. */ public void setAttributes(Map attrs); /** * Removes all attributes from this node. */ public void clearAttributes(); // ========================================================================= /** * Check whether a certain attribute is attached to this node. * * @param name * The name of the attribute to test. * * @return True if an attribute with the respective name is * attached to this node, false otherwise. */ public abstract boolean hasAttribute(String name); /** * Retrieve the value of an attribute. * * @param name * The name of the attribute to retrieve. * * @return The value of the respective attribute or null if the * attribute does not exist. */ public abstract Object getAttribute(String name); /** * Assign an attribute to this node. Attaches a name associated with an * object to this node. * * @param name * The name of the attribute. * @param value * The value associated with the attribute. * * @return Returns the value previously associated with the attribute or * null if the attribute does not exist yet. */ public abstract Object setAttribute(String name, Object value); /** * Remove an attribute from this node. * * @param name * The name of the attribute to remove. * * @return The value of the removed attribute. */ public abstract Object removeAttribute(String name); // ========================================================================= /** * Retrieve the value of an integer attribute. * * @param name * The name of the integer attribute to retrieve. * * @return The integer value of the respective attribute or 0 * if the attribute does not exist. */ public abstract int getIntAttribute(String name); /** * Assign an integer attribute to this node. Attaches a name associated with * an integer object to this node. * * @param name * The name of the attribute. * @param value * The integer value associated with the attribute. * * @return Returns the value previously associated with the attribute or * null if the attribute does not exist yet. */ public abstract Integer setIntAttribute(String name, Integer value); /** * Retrieve the value of a boolean attribute. * * @param name * The name of the boolean attribute to retrieve. * * @return The boolean value of the respective attribute or * false if the attribute does not exist. */ public abstract boolean getBooleanAttribute(String name); /** * Assign a boolean attribute to this node. Attaches a name associated with * a boolean object to this node. * * @param name * The name of the attribute. * @param value * The boolean value associated with the attribute. * * @return Returns the value previously associated with the attribute or * null if the attribute does not exist yet. */ public abstract boolean setBooleanAttribute(String name, boolean value); /** * Retrieve the value of a string attribute. * * @param name * The name of the string attribute to retrieve. * * @return The string value of the respective attribute or null * if the attribute does not exist. */ public abstract String getStringAttribute(String name); /** * Assign an string attribute to this node. Attaches a name associated with * an String object to this node. * * @param name * The name of the attribute. * @param value * The String value associated with the attribute. * * @return Returns the value previously associated with the attribute or * null if the attribute does not exist yet. */ public abstract String setStringAttribute(String name, String value); } AstNodeImpl.java000066400000000000000000000315701315622671000370740ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/main/java/de/fau/cs/osr/ptk/common/ast/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common.ast; import java.io.IOException; import java.util.AbstractList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import de.fau.cs.osr.utils.WrappedException; import xtc.tree.Locatable; import xtc.tree.Location; import xtc.util.Pair; /** * The parent node of all AST (abstract/attributed syntax tree) nodes. * * FIXME: Get rid of Locatable interface somehow ... */ public abstract class AstNodeImpl> extends AbstractList implements AstNode { private static final long serialVersionUID = 3333532331617925714L; // ========================================================================= private HashMap attributes; private AstLocation location; // ========================================================================= protected AstNodeImpl() { } protected AstNodeImpl(AstLocation location) { setNativeLocation(location); } protected AstNodeImpl(Location location) { setLocation(location); } // ========================================================================= /** * Returns an integer value that identifies the node type. It's the * programmers responsibility to make sure these values are unique. */ @Override public int getNodeType() { return NT_UNTYPED; } /** * Returns true if the given node type equals the node type * returned by getNodeType(). */ @Override public boolean isNodeType(int testType) { return getNodeType() == testType; } /** * Returns the fully qualified name of this node's class. */ @Override public final String getNodeTypeName() { return getClass().getName(); } /** * Returns the name of this node. The name is the simple name of the node's * class. */ @Override public String getNodeName() { return getClass().getSimpleName(); } // ========================================================================= // Implementation of AstNodeAttributeInterface @Override public final boolean hasAttributes() { return attributes != null && !attributes.isEmpty(); } @Override public final Map getAttributes() { if (attributes == null) return Collections.emptyMap(); return Collections.unmodifiableMap(attributes); } @Override public void setAttributes(Map attrs) { this.attributes = new HashMap(attrs); } @Override public void clearAttributes() { this.attributes = null; } @Override public final boolean hasAttribute(String name) { if (attributes == null) return false; return attributes.containsKey(name); } @Override public final Object getAttribute(String name) { if (attributes == null) return null; return attributes.get(name); } @Override public Object setAttribute(String name, Object value) { if (attributes == null) attributes = new HashMap(); return attributes.put(name, value); } @Override public Object removeAttribute(String name) { if (attributes == null) return null; Object value = attributes.remove(name); if (attributes.isEmpty()) attributes = null; return value; } @Override public final int getIntAttribute(String name) { if (attributes == null) return 0; return (Integer) attributes.get(name); } @Override public Integer setIntAttribute(String name, Integer value) { if (attributes == null) attributes = new HashMap(); return (Integer) attributes.put(name, value); } @Override public final boolean getBooleanAttribute(String name) { if (attributes == null) return false; Object o = attributes.get(name); if (null == o) return false; return (Boolean) o; } @Override public boolean setBooleanAttribute(String name, boolean value) { if (attributes == null) attributes = new HashMap(); Boolean o = (Boolean) attributes.put(name, value); if (o == null) return false; return (Boolean) o; } @Override public final String getStringAttribute(String name) { if (attributes == null) return null; return (String) attributes.get(name); } @Override public String setStringAttribute(String name, String value) { if (attributes == null) attributes = new HashMap(); return (String) attributes.put(name, value); } // ========================================================================= // Implementation of AstNodePropertyInterface @Override public final boolean hasProperties() { return getPropertyCount() > 0; } @Override public int getPropertyCount() { return 0; } @Override public Object getProperty(String name) { AstNodePropertyIterator i = propertyIterator(); while (i.next()) { if (i.getName().equals(name)) return i.getValue(); } throw new NoSuchPropertyException(); } @Override public Object getProperty(String name, Object default_) { AstNodePropertyIterator i = propertyIterator(); while (i.next()) { if (i.getName().equals(name)) return i.getValue(); } return default_; } @Override public boolean hasProperty(String name) { AstNodePropertyIterator i = propertyIterator(); while (i.next()) { if (i.getName().equals(name)) return true; } return false; } @Override public Object setProperty(String name, Object value) { AstNodePropertyIterator i = propertyIterator(); while (i.next()) { if (i.getName().equals(name)) { Object old = i.getValue(); i.setValue(value); return old; } } throw new NoSuchPropertyException(); } @Override public AstNodePropertyIterator propertyIterator() { return new AstNodePropertyIterator() { @Override protected String getName(int index) { throw new IndexOutOfBoundsException(); } @Override protected Object getValue(int index) { throw new IndexOutOfBoundsException(); } @Override protected Object setValue(int index, Object value) { throw new IndexOutOfBoundsException(); } @Override protected int getPropertyCount() { return 0; } }; } // ========================================================================= // Implementation of Locatable interface @Override public final boolean hasLocation() { return location != null; } @Override public final Location getLocation() { if (location == null) return null; return location.toXtcLocation(); } @Override public void setLocation(Location location) { setNativeLocation(new AstLocation(location)); } @Override public void setLocation(Locatable locatable) { if (locatable.hasLocation()) setLocation(locatable.getLocation()); } // ========================================================================= @Override public final AstLocation getNativeLocation() { return location; } @Override public void setNativeLocation(AstLocation location) { this.location = location; } // ========================================================================= // Implementation of the AbstractList interface @Override public int size() { return 0; } @Override public T get(int index) { throw new UnsupportedOperationException(); } @Override public S get(int index, Class clazz) { throw new UnsupportedOperationException(); } // ========================================================================= // Extension of the List interface for Pair /** * Appends all items from the given list to list of children. * * @return Returns true if the list of children has changed. */ @Override public boolean addAll(Pair p) { throw new UnsupportedOperationException(); } // ========================================================================= // Introspection /** * Determine whether this node can have a variable number of children and * implements the {@link List} interface (or parts of it). */ @Override public boolean isList() { return false; } /** * Returns the names of the children. This method may only be called for * nodes with a fixed number of children (isList() returns false). */ @Override public String[] getChildNames() { return EMPTY_CHILD_NAMES; } // ========================================================================= @Override public void toString(Appendable out) throws IOException { out.append(getClass().getSimpleName()); out.append('('); boolean first = true; for (T node : this) { if (first) { first = false; } else { out.append(", "); } node.toString(out); } out.append(')'); } @Override public String toString() { StringBuilder buf = new StringBuilder(); try { toString(buf); } catch (IOException x) { assert false; } return buf.toString(); } // ========================================================================= @Override public Object clone() throws CloneNotSupportedException { @SuppressWarnings("unchecked") AstNodeImpl n = (AstNodeImpl) super.clone(); // we don't clone the location since a location is immutable if (n.attributes != null) n.attributes = new HashMap(n.attributes); // we don't copy the properties, we assume that properties are stored // as attributes of classes and are therefore already copied. // we don't copy/clone children, we're doing a shallow clone. return n; } @SuppressWarnings("unchecked") public AstNodeImpl cloneWrapException() { try { return (AstNodeImpl) this.clone(); } catch (CloneNotSupportedException e) { throw new WrappedException(e); } } /** * Unlike clone() deepClone() calls deepClone() on children and thus * recursively create a deep copy of a sub-tree. It does, however, not clone * properties or attributes, those are just copied by reference. */ @Override @SuppressWarnings("unchecked") public AstNodeImpl deepClone() throws CloneNotSupportedException { AstNodeImpl n = (AstNodeImpl) clone(); if (isList()) { // First remove cloned references n.clear(); Iterator i = iterator(); while (i.hasNext()) n.add((T) i.next().deepClone()); } else { for (int i = 0; i < size(); ++i) n.set(i, (T) get(i).deepClone()); } return n; } public AstNodeImpl deepCloneWrapException() { try { return this.deepClone(); } catch (CloneNotSupportedException e) { throw new WrappedException(e); } } // ========================================================================= /* hashCode is omitted intentionally. It's hard to implement a meaningful * hashCode method that does NOT recurse into the subtree. But recursing the * whole subtree defeats the purpose of a hash function, which should be * fast to allow quick look-ups. */ @Override public boolean equals(Object obj) { // Type checking if (this == obj) return true; if (obj == null || getClass() != obj.getClass()) return false; @SuppressWarnings("unchecked") AstNodeImpl other = (AstNodeImpl) obj; return equalsNoTypeCheck(this, other); } public static > boolean equalsNoTypeCheck( AstNode a, AstNode b) { // Check location if (a.getNativeLocation() == null) { if (b.getNativeLocation() != null) return false; } else if (!a.getNativeLocation().equals(b.getNativeLocation())) return false; // Check attributes if (a.getAttributes() == null) { if (b.getAttributes() != null) return false; } else if (!a.getAttributes().equals(b.getAttributes())) return false; // Check properties AstNodePropertyIterator p1 = a.propertyIterator(); AstNodePropertyIterator p2 = b.propertyIterator(); while (p1.next() & p2.next()) // Don't short-circuit! { Object v1 = p1.getValue(); Object v2 = p2.getValue(); if (v1 == null) { if (v2 != null) return false; } else if (!v1.equals(v2)) return false; } // Nodes of the same type have the same set of properties // Check children Iterator i1 = a.iterator(); Iterator i2 = b.iterator(); while (i1.hasNext() && i2.hasNext()) { S n1 = i1.next(); S n2 = i2.next(); if (n1 == null) { if (n2 != null) return false; } else if (!n1.equals(n2)) return false; } if (i1.hasNext() != i2.hasNext()) return false; return true; } } AstNodeList.java000066400000000000000000000015151315622671000371020ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/main/java/de/fau/cs/osr/ptk/common/ast/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common.ast; public interface AstNodeList> extends AstInnerNode { public abstract void exchange(AstNodeList other); } AstNodeListImpl.java000066400000000000000000000321151315622671000377240ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/main/java/de/fau/cs/osr/ptk/common/ast/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common.ast; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import xtc.util.Pair; /** * List of nodes using a Pair as underlying data structure. * * Invariants:
*
    *
  • This list never contains {@code null} as node.
  • *
  • This list never contains another {@link AstNodeListImpl} as node.
  • *
* * In order to assure these invariants, all functions adding nodes to this list * will discard null references and will recursively flatten any * {@link AstNodeListImpl}. */ public class AstNodeListImpl> extends AstAbstractInnerNode implements AstNodeList { private static final long serialVersionUID = -3855416846550776026L; // ========================================================================= private ArrayList children = new ArrayList(); // ========================================================================= public AstNodeListImpl() { } public AstNodeListImpl(T child) { add(child); } public AstNodeListImpl(T car, Pair cdr) { add(car); addAll(cdr); } public AstNodeListImpl(T a, T b) { add(a); add(b); } public AstNodeListImpl(T a, T b, T c) { add(a); add(b); add(c); } public AstNodeListImpl(T a, T b, T c, T d) { add(a); add(b); add(c); add(d); } public AstNodeListImpl(Pair list) { addAll(list); } public AstNodeListImpl(Collection list) { addAll(list); } public AstNodeListImpl(T... children) { for (T x : children) add(x); } // ========================================================================= public int getNodeType() { return NT_NODE_LIST; } // ========================================================================= // Implementation of the List interface @Override public int size() { return children.size(); } @Override public boolean isEmpty() { return children.isEmpty(); } @Override public boolean contains(Object o) { return children.contains(o); } @Override public Iterator iterator() { return children.iterator(); } @Override public Object[] toArray() { return children.toArray(); } @Override public S[] toArray(S[] a) { return children.toArray(a); } // Modification Operations @Override public boolean add(T e) { return addIntern(children, e); } @Override public boolean remove(Object o) { return children.remove(o); } // Bulk Modification Operations @Override public boolean containsAll(Collection c) { return children.containsAll(c); } @Override public boolean addAll(Collection c) { return addAllIntern(children, c); } @Override public boolean addAll(int index, Collection c) { return addAllIntern(children, index, c); } @Override public boolean removeAll(Collection c) { return children.removeAll(c); } @Override public boolean retainAll(Collection c) { return children.retainAll(c); } @Override public void clear() { children.clear(); } // Positional Access Operations @Override public T get(int index) { return children.get(index); } @Override public T set(int index, T value) { if (value == null) { throw new NullPointerException( "A NodeList must not contain a null element!"); } else { switch (value.getNodeType()) { case AstNode.NT_NODE_LIST: throw new IllegalArgumentException( "Must not set a single element to a NodeList"); case AstNode.NT_TEXT: return setTextIntern(children, index, (AstStringNode) value); default: return children.set(index, value); } } } @SuppressWarnings("unchecked") private static > S setTextIntern( ArrayList list, int index, AstStringNode text) { if (text.getContent().isEmpty()) { return list.remove(index); } else { if (index > 0 && !text.hasAttributes()) { S prev = list.get(index - 1); if (prev.getNodeType() == AstNode.NT_TEXT && !prev.hasAttributes()) { try { list.set(index - 1, (S) mergeTextNodes((AstStringNode) prev, text)); return list.remove(index); } catch (CloneNotSupportedException e) { // Just set, don't merge } } } return list.set(index, (S) text); } } @Override public void add(int index, T element) { addIntern(children, index, element); } private static > boolean addIntern( ArrayList list, S element) { return addIntern(list, list.size(), element); } private static > boolean addIntern( ArrayList list, int index, S element) { if (element == null) { return false; } else { switch (element.getNodeType()) { case AstNode.NT_NODE_LIST: return addAllIntern(list, index, element); case AstNode.NT_TEXT: return addTextIntern(list, index, (AstStringNode) element); default: list.add(index, element); return true; } } } @SuppressWarnings({ "rawtypes", "unchecked" }) private static boolean addTextIntern( ArrayList list, int index, AstStringNode text) { if (text.getContent().isEmpty()) { return false; } else { if (index > 0 && !text.hasAttributes()) { AstNode prev = (AstNode) list.get(index - 1); if (prev.getNodeType() == AstNode.NT_TEXT && !prev.hasAttributes()) { try { list.set(index - 1, mergeTextNodes((AstStringNode) prev, text)); return true; } catch (CloneNotSupportedException e) { // Just add, don't merge } } } list.add(index, text); return true; } } private static > AstStringNode mergeTextNodes( AstStringNode prev, AstStringNode text) throws CloneNotSupportedException { @SuppressWarnings("unchecked") AstStringNode merged = (AstStringNode) prev.clone(); merged.setContent(merged.getContent() + text.getContent()); return merged; } private static > boolean addAllIntern( ArrayList list, Collection c) { boolean changed = false; for (S n : c) changed |= addIntern(list, n); return changed; } private static > boolean addAllIntern( ArrayList list, int index, Collection c) { boolean changed = false; for (S n : c) { int oldSize = list.size(); changed |= addIntern(list, index, n); index += list.size() - oldSize; } return changed; } @Override public T remove(int index) { return children.remove(index); } // Search Operations @Override public int indexOf(Object o) { return children.indexOf(o); } @Override public int lastIndexOf(Object o) { return children.lastIndexOf(o); } // List Iterators @Override public ListIterator listIterator() { return new ChildListIterator(); } @Override public ListIterator listIterator(int index) { return new ChildListIterator(index); } // View @Override public List subList(int fromIndex, int toIndex) { return children.subList(fromIndex, toIndex); } // ========================================================================= // Extension of the List interface for Pair @Override public boolean addAll(Pair p) { boolean changed = false; while (!p.isEmpty()) { changed |= add(p.head()); p = p.tail(); } return changed; } // ========================================================================= // Introspection @Override public boolean isList() { return true; } @Override public String[] getChildNames() { return EMPTY_CHILD_NAMES; } // ========================================================================= @Override public void toString(Appendable out) throws IOException { out.append('['); boolean first = true; for (T node : this) { if (first) { first = false; } else { out.append(", "); } node.toString(out); } out.append(']'); } // ========================================================================= @Override public void exchange(AstNodeList other) { if (other instanceof AstNodeListImpl) { AstNodeListImpl other2 = (AstNodeListImpl) other; ArrayList tmp = this.children; this.children = other2.children; other2.children = tmp; } else { AstNodeListImpl tmp = new AstNodeListImpl(other); this.exchange(tmp); } } // ========================================================================= @Override @SuppressWarnings({ "rawtypes", "unchecked" }) public Object clone() throws CloneNotSupportedException { AstNodeListImpl clone = (AstNodeListImpl) super.clone(); clone.children = new ArrayList(children); return clone; } // ========================================================================= private final class ChildListIterator implements AstChildIterator { private ListIterator i; private T current = null; private final int start; public ChildListIterator() { start = 0; reset(); } public ChildListIterator(int index) { start = index; reset(); } @Override public boolean hasNext() { return i.hasNext(); } @Override public T next() { current = i.next(); return current; } @Override public boolean hasPrevious() { return i.hasPrevious(); } @Override public T previous() { current = i.previous(); return current; } @Override public int nextIndex() { return i.nextIndex(); } @Override public int previousIndex() { return i.previousIndex(); } @Override public void remove() { i.remove(); current = null; } @Override public void set(T e) { if (e == null) { throw new NullPointerException( "A NodeList must not contain a null element!"); } else { switch (e.getNodeType()) { case AstNode.NT_NODE_LIST: throw new IllegalArgumentException( "Must not set a single element to a NodeList"); case AstNode.NT_TEXT: setTextIntern((AstStringNode) e); break; default: i.set(e); current = e; break; } } } /** * This whole method breaks the set() interface established by the * ListIterator class! */ @SuppressWarnings("unchecked") private void setTextIntern(AstStringNode text) { if (current == null) throw new IllegalStateException(); if (text.getContent().isEmpty()) { i.remove(); current = null; } else { if (i.hasPrevious() && !text.hasAttributes()) { i.previous(); if (i.hasPrevious()) { T prev = i.previous(); if (prev.getNodeType() == AstNode.NT_TEXT && !prev.hasAttributes()) { try { i.set((T) mergeTextNodes((AstStringNode) prev, text)); // set() protocol requires that the iterator doesn't // move. When deleting something that's not // possible. So we move to the merged text element. i.next(); i.next(); i.remove(); i.previous(); // use own method to set current! next(); return; } catch (CloneNotSupportedException e) { // Just set, don't merge } } i.next(); } i.next(); } i.set((T) text); } } @Override public void add(T e) { if (e != null) { current = null; switch (e.getNodeType()) { case AstNode.NT_NODE_LIST: for (T n : (AstNodeList) e) i.add(n); break; case AstNode.NT_TEXT: addTextIntern((AstStringNode) e); break; default: i.add(e); break; } } } @SuppressWarnings("unchecked") private void addTextIntern(AstStringNode text) { if (!text.getContent().isEmpty()) { if (i.hasPrevious() && !text.hasAttributes()) { T prev = i.previous(); if (prev.getNodeType() == AstNode.NT_TEXT && !prev.hasAttributes()) { try { i.set((T) mergeTextNodes((AstStringNode) prev, text)); i.next(); return; } catch (CloneNotSupportedException e) { // Just add, don't merge } } } i.add((T) text); } } @Override public T get() { if (current == null) throw new IllegalStateException(); return current; } @Override public void reset() { i = AstNodeListImpl.this.children.listIterator(start); } } } AstNodePropertyInterface.java000066400000000000000000000025321315622671000416340ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/main/java/de/fau/cs/osr/ptk/common/ast/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common.ast; public interface AstNodePropertyInterface { public boolean hasProperties(); public int getPropertyCount(); public Object getProperty(String name); public Object getProperty(String name, Object default_); public boolean hasProperty(String name); public Object setProperty(String name, Object value); /** * Return an iterator which iterates over this node's properties. Though * order is not important for properties, this method must always * iterate through the properties in the exact same order. * * @return An iterator which iterates over this node's properties. */ public AstNodePropertyIterator propertyIterator(); } AstNodePropertyIterator.java000066400000000000000000000036221315622671000415260ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/main/java/de/fau/cs/osr/ptk/common/ast/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common.ast; /** * An iterator for AstNode properties. This class does not offer a * hasNext() method, like the {@link java.util.Iterator}. Instead * it only offers a next() method, which returns true * if the iterator points to a valid property after the call to * next(). * *

* Example loop: * *

 * AstNodePropertyIterator i = iterateProperties();
 * while (i.next())
 * {
 * 	// Call getName(), getValue() or setValue()
 * 	// (these do NOT move the iterator)
 * }
 * 
*/ public abstract class AstNodePropertyIterator { private int i = -1; // ========================================================================= public boolean next() { return ++i < getPropertyCount(); } public String getName() { return getName(i); } public Object getValue() { return getValue(i); } public Object setValue(Object value) { return setValue(i, value); } // ========================================================================= protected abstract int getPropertyCount(); protected abstract String getName(int index); protected abstract Object getValue(int index); protected abstract Object setValue(int index, Object value); } AstParserEntity.java000066400000000000000000000047071315622671000400200ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/main/java/de/fau/cs/osr/ptk/common/ast/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common.ast; import java.io.IOException; public class AstParserEntity> extends AstLeafNodeImpl { private static final long serialVersionUID = 3182955812498375838L; protected AstParserEntity(Uninitialized u) { } public AstParserEntity(int id) { setId(id); } // ========================================================================= private int id; public int getId() { return id; } public int setId(int id) { int old = this.id; this.id = id; return old; } @Override public int getPropertyCount() { return 1; } @Override public AstNodePropertyIterator propertyIterator() { return new AstNodePropertyIterator() { @Override protected int getPropertyCount() { return 1; } @Override protected String getName(int index) { switch (index) { case 0: return "id"; default: throw new IndexOutOfBoundsException(); } } @Override protected Object getValue(int index) { switch (index) { case 0: return AstParserEntity.this.getId(); default: throw new IndexOutOfBoundsException(); } } @Override protected Object setValue(int index, Object value) { switch (index) { case 0: return AstParserEntity.this.setId((Integer) value); default: throw new IndexOutOfBoundsException(); } } }; } // ========================================================================= @Override public int getNodeType() { return NT_PARSER_ENTITY; } // ========================================================================= @Override public void toString(Appendable out) throws IOException { out.append("GenericParserEntity("); out.append(String.valueOf(getId())); out.append(')'); } } AstStringNode.java000066400000000000000000000015611315622671000374360ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/main/java/de/fau/cs/osr/ptk/common/ast/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common.ast; public interface AstStringNode> extends AstLeafNode { public abstract String getContent(); public abstract void setContent(String content); } AstStringNodeImpl.java000066400000000000000000000052751315622671000402660ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/main/java/de/fau/cs/osr/ptk/common/ast/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common.ast; import java.io.IOException; import de.fau.cs.osr.utils.StringTools; public abstract class AstStringNodeImpl> extends AstLeafNodeImpl implements AstStringNode { private static final long serialVersionUID = -3995972757553601033L; protected AstStringNodeImpl(Uninitialized u) { } protected AstStringNodeImpl(String content) { setContent(content); } // ========================================================================= private String content; @Override public String getContent() { return content; } @Override public void setContent(String content) { if (content == null) throw new NullPointerException(); this.content = content; } @Override public int getPropertyCount() { return 1; } @Override public AstNodePropertyIterator propertyIterator() { return new StringContentNodePropertyIterator(); } protected class StringContentNodePropertyIterator extends AstNodePropertyIterator { @Override protected int getPropertyCount() { return 1; } @Override protected String getName(int index) { switch (index) { case 0: return "content"; default: throw new IndexOutOfBoundsException(); } } @Override protected Object getValue(int index) { switch (index) { case 0: return AstStringNodeImpl.this.getContent(); default: throw new IndexOutOfBoundsException(); } } @Override protected Object setValue(int index, Object value) { switch (index) { case 0: { String old = AstStringNodeImpl.this.getContent(); AstStringNodeImpl.this.setContent((String) value); return old; } default: throw new IndexOutOfBoundsException(); } } } // ========================================================================= @Override public void toString(Appendable out) throws IOException { out.append(getClass().getSimpleName()); out.append("(\""); out.append(StringTools.escJava(getContent())); out.append("\")"); } } AstText.java000066400000000000000000000021251315622671000363030ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/main/java/de/fau/cs/osr/ptk/common/ast/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common.ast; public class AstText> extends AstStringNodeImpl { private static final long serialVersionUID = 7614892787867816308L; protected AstText(Uninitialized u) { super(u); } public AstText(String content) { super(content); } // ========================================================================= @Override public int getNodeType() { return NT_TEXT; } } NoSuchPropertyException.java000066400000000000000000000021421315622671000415310ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/main/java/de/fau/cs/osr/ptk/common/ast/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common.ast; public class NoSuchPropertyException extends RuntimeException { private static final long serialVersionUID = 1L; public NoSuchPropertyException() { super(); } public NoSuchPropertyException(String message, Throwable cause) { super(message, cause); } public NoSuchPropertyException(String message) { super(message); } public NoSuchPropertyException(Throwable cause) { super(cause); } } RtData.java000066400000000000000000000272441315622671000360770ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/main/java/de/fau/cs/osr/ptk/common/ast/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common.ast; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import de.fau.cs.osr.utils.StringTools; import de.fau.cs.osr.utils.WrappedException; public class RtData implements Serializable, Cloneable { public static final String SEP = new String(); public static final RtData SUPPRESS = new RtDataSuppressSingleton(); // ========================================================================= private static final long serialVersionUID = 1L; private static final Object[] EMPTY_FIELD = {}; private final Object[][] fields; // ========================================================================= /** * Constructor for SUPPRESS singleton. */ protected RtData() { this.fields = new Object[0][]; } /** * Instantiates an RtData object and initializes its size to match that of * the given AstNodeInterface. * * An AstNodeInterface with two children will need an RtData object with * size three. */ public RtData(AstNode node) { this(node.size() + 1); } /** * Instantiates an empty RtData object with the given size. */ public RtData(int size) { if (size <= 0) throw new IllegalArgumentException("RtData must have a size of at least 1"); this.fields = new Object[size][]; Arrays.fill(this.fields, EMPTY_FIELD); } /** * Instantiates an RtData object, initializes its size to match that of the * given AstNodeInterface and immediately fills it with glue information. * * To move on to the next glue field insert a SEP object. */ public RtData(AstNode node, Object... glue) { this(node); set(glue); } /** * Instantiates an RtData object with the given size and immediately fills * it with glue information. * * To move on to the next glue field insert a SEP object. */ public RtData(int size, Object... glue) { this(size); set(glue); } /** * Instantiates an RtData object, initializes its size to match that of the * given AstNodeInterface and immediately fills it with glue information. * * To move on to the next glue field insert a SEP object. */ public RtData(AstNode node, String... glue) { this(node); set(glue); } /** * Instantiates an RtData object with the given size and immediately fills * it with glue information. * * To move on to the next glue field insert a SEP object. */ public RtData(int size, String... glue) { this(size); set(glue); } protected RtData(RtData rtData) { Object[][] other = rtData.fields; this.fields = new Object[other.length][]; for (int i = 0; i < fields.length; ++i) { this.fields[i] = (other[i] == EMPTY_FIELD) ? EMPTY_FIELD : other[i].clone(); } } // ========================================================================= public void set(Object... glue) { int seps = 0; int from = 0; int to = 0; for (int field = 0; field < fields.length; ++field) { while (to < glue.length) { if (glue[to] == SEP) { ++seps; break; } ++to; } setFieldFromArraySection(field, glue, from, to); if (to < glue.length) ++to; from = to; } if (seps >= fields.length) throw new IndexOutOfBoundsException("The glue array has too many fields!"); } public void set(String... glue) { int seps = 0; int from = 0; int to = 0; for (int field = 0; field < fields.length; ++field) { while (to < glue.length) { if (glue[to] == SEP) { ++seps; break; } ++to; } setFieldFromArraySection(field, glue, from, to); if (to < glue.length) ++to; from = to; } if (seps >= fields.length) throw new IndexOutOfBoundsException("The glue array has too many fields!"); } // ========================================================================= public void setField(int field, Object... glue) { setFieldFromArraySection(field, glue, 0, glue.length); } public void setField(int field, String... glue) { setFieldFromArraySection(field, glue, 0, glue.length); } public void setField(int field, String glue) { if (glue == null || glue.isEmpty()) { this.fields[field] = EMPTY_FIELD; } else { this.fields[field] = new Object[] { glue }; } } // ========================================================================= private void setFieldFromArraySection( int field, Object[] glue, int from, int to) { if (from < 0 || to > glue.length) throw new IndexOutOfBoundsException(); if (to <= from) return; ArrayList result = new ArrayList(glue.length); for (int i = from; i < to; ++i) { Object o = glue[i]; if (o == null) { } else if (o instanceof Object[]) { for (Object o2 : (Object[]) o) addObject(result, o2); } else { addObject(result, o); } } if (result.isEmpty()) { this.fields[field] = EMPTY_FIELD; } else { this.fields[field] = result.toArray(); } } protected void addObject(ArrayList result, Object o) { if (o instanceof Character) { rtAddString(result, String.valueOf((Character) o)); } else if (o instanceof String) { rtAddString(result, o.toString()); } else { addNodeOrObject(result, o); } } protected void addNodeOrObject(ArrayList result, Object o) { if (o instanceof AstNode) { AstNode node = (AstNode) o; if (node.getNodeType() == AstNode.NT_NODE_LIST) { for (AstNode c : (AstNodeList) o) addNodeOrObject(result, c); } else if (node.getNodeType() == AstNode.NT_TEXT) { rtAddString(result, ((AstText) o).getContent()); } else { result.add(o); } } else { result.add(o); } } protected static void rtAddString(ArrayList result, String text) { if (text.isEmpty()) return; int i = result.size() - 1; if (i >= 0) { Object last = result.get(i); if (last instanceof String) { result.set(i, (String) last + text); return; } } result.add(text); } private void setFieldFromArraySection( int field, String[] glue, int from, int to) { if (from < 0 || to > glue.length) throw new IndexOutOfBoundsException(); if (to <= from) return; StringBuilder sb = new StringBuilder(); for (int i1 = from; i1 < to; ++i1) { String g = glue[i1]; if (g == null) continue; sb.append(g); } setField(field, sb.toString()); } // ========================================================================= public boolean isSuppress() { return this == SUPPRESS; } public int size() { return this.fields.length; } public Object[][] getFields() { return fields; } /** * Returns the glue field that can be found between two child nodes or in * front of the first or after the last child node. */ public Object[] getField(int index) { return fields[index]; } /** * Converts a glue field to a string. */ public String toString(int index) { Object[] field = fields[index]; if (field.length == 0) { return ""; } else if (field.length == 1 && field[0] instanceof String) { return (String) field[0]; } else { StringBuilder sb = new StringBuilder(); toString(index, sb); return sb.toString(); } } public boolean isStringOnly(int index) { Object[] field = fields[index]; return (field.length == 0) || (field.length == 1 && field[0] instanceof String); } protected void toString(int index, StringBuilder sb) { Object[] field = fields[index]; for (int i = 0; i < field.length; ++i) { if (i != 0) sb.append(" + "); Object o = field[i]; if (o instanceof String) { stringRep(sb, (String) o); } else { stringRep(sb, o); } } } protected void stringRep(StringBuilder sb, Object o) { sb.append(o.toString()); } protected void stringRep(StringBuilder sb, String str) { sb.append('"'); sb.append(StringTools.escJava(str)); sb.append('"'); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("RTD[ "); for (int i = 0; i < fields.length; ++i) { if (i > 0) sb.append(" "); if (getField(i).length == 0) { sb.append("\"\""); } else { toString(i, sb); } } sb.append(" ]"); return sb.toString(); } // ========================================================================= public void prepend(Object... glue) { if (glue.length == 0) return; setField(0, glue, getField(0)); } public void append(Object... glue) { if (glue.length == 0) return; int last = size() - 1; setField(last, getField(last), glue); } public void prepend(String text) { if (text == null || text.isEmpty()) return; Object[] firstField = fields[0]; if (firstField.length == 0) { setField(0, text); } else { Object firstGlue = firstField[0]; if (firstGlue instanceof String) { firstField[0] = text + firstGlue; } else { Object[] newField = new Object[firstField.length + 1]; System.arraycopy(firstField, 0, newField, 1, firstField.length); newField[0] = text; fields[0] = newField; } } } // ========================================================================= @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + Arrays.hashCode(fields); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; RtData other = (RtData) obj; if (!Arrays.deepEquals(fields, other.fields)) return false; return true; } // ========================================================================= @Override public Object clone() throws CloneNotSupportedException { return new RtData(this); } public RtData cloneWrapException() { try { return (RtData) this.clone(); } catch (CloneNotSupportedException e) { throw new WrappedException(e); } } // ========================================================================= protected static class RtDataSuppressSingleton extends RtData { private static final long serialVersionUID = 1L; @Override public void set(Object... glue) { notSupported(); } @Override public void set(String... glue) { notSupported(); } @Override public void setField(int field, Object... glue) { notSupported(); } @Override public void setField(int field, String glue) { notSupported(); } @Override public void setField(int field, String... glue) { notSupported(); } @Override public void prepend(String text) { notSupported(); } @Override public void append(Object... glue) { notSupported(); } @Override public void prepend(Object... glue) { notSupported(); } private void notSupported() { throw new UnsupportedOperationException(); } @Override public boolean equals(Object obj) { if (this == obj) return true; return false; } @Override public Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException(); } } } Span.java000066400000000000000000000071521315622671000356150ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/main/java/de/fau/cs/osr/ptk/common/ast/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common.ast; import java.io.Serializable; import de.fau.cs.osr.utils.StringTools; import xtc.tree.Location; public final class Span implements Serializable { private static final long serialVersionUID = 1L; private final String content; private final AstLocation from; private final AstLocation to; // ========================================================================= public Span() { content = null; from = new AstLocation("Unknown file", -1, -1); to = from; } public Span(AstLocation from, AstLocation to, String content) { this.content = content; this.from = from; this.to = to; } public Span(AstLocation from, String content) { this.content = content; this.from = from; this.to = from; } public Span(Location from, Location to, String content) { this.content = content; this.from = new AstLocation(from); this.to = new AstLocation(to); } public Span(Location from, String content) { this.content = content; this.from = new AstLocation(from); this.to = this.from; } // ========================================================================= public String getContent() { return content; } public AstLocation getFrom() { return from; } public AstLocation getTo() { return to; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((content == null) ? 0 : content.hashCode()); result = prime * result + ((from == null) ? 0 : from.hashCode()); result = prime * result + ((to == null) ? 0 : to.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Span other = (Span) obj; if (content == null) { if (other.content != null) return false; } else if (!content.equals(other.content)) return false; if (from == null) { if (other.from != null) return false; } else if (!from.equals(other.from)) return false; if (to == null) { if (other.to != null) return false; } else if (!to.equals(other.to)) return false; return true; } @Override public String toString() { StringBuilder buf = new StringBuilder(); if (from == null) { buf.append(""); } else { String file = from.getFile(); if (file == null || file.isEmpty()) file = ""; buf.append(file); buf.append(':'); buf.append(from.getLine()); buf.append(':'); buf.append(from.getColumn()); if (to != null && !to.equals(from)) { buf.append(" - "); if (from.getLine() != to.getLine()) { buf.append(to.getLine()); buf.append(':'); } buf.append(to.getColumn()); } } if (content != null) { buf.append(": \""); buf.append(StringTools.escJava(StringTools.crop(content, 32))); buf.append('"'); } else { buf.append(": "); } return buf.toString(); } } Uninitialized.java000066400000000000000000000013441315622671000375210ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/main/java/de/fau/cs/osr/ptk/common/ast/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common.ast; public enum Uninitialized { X } comparer/000077500000000000000000000000001315622671000350655ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/main/java/de/fau/cs/osr/ptk/commonAstComparer.java000066400000000000000000000043331315622671000401530ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/main/java/de/fau/cs/osr/ptk/common/comparer/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common.comparer; import de.fau.cs.osr.ptk.common.ast.AstNode; import de.fau.cs.osr.utils.ComparisonException; import de.fau.cs.osr.utils.DeepComparer; import de.fau.cs.osr.utils.DeepComparerDelegate; public class AstComparer { /** * Compare two AST subtrees for equality. * * Property and attribute values are compared using the equals * method. * * @param rootA * First subtree. * @param rootB * Second subtree. * @param compareAttributes * Whether to include the node attributes in the comparison. */ public static void compareAndThrow( AstNode rootA, AstNode rootB, boolean compareAttributes, boolean compareLocation) throws ComparisonException { makeComparer(compareAttributes, compareLocation).compare(rootA, rootB); } public static boolean compareNoThrow( AstNode rootA, AstNode rootB, boolean compareAttributes, boolean compareLocation) { try { compareAndThrow(rootA, rootB, compareAttributes, compareLocation); return true; } catch (ComparisonException e) { return false; } } public static DeepComparer makeComparer( boolean compareAttributes, boolean compareLocation) { DeepComparerDelegate entityMapDelegate = new AstEntityMapComparerDelegate(); DeepComparerDelegate nodeDelegate = new AstNodeComparerDelegate( compareAttributes, compareLocation); DeepComparer comparer = new DeepComparer(); comparer.addComparer(entityMapDelegate); comparer.addComparer(nodeDelegate); return comparer; } } AstComparisonException.java000066400000000000000000000056141315622671000423770ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/main/java/de/fau/cs/osr/ptk/common/comparer/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common.comparer; import java.io.IOException; import java.io.StringWriter; import java.io.Writer; import de.fau.cs.osr.ptk.common.ast.AstNode; import de.fau.cs.osr.utils.ComparisonException; public class AstComparisonException extends ComparisonException { private static final long serialVersionUID = 1L; private final AstDifference reason; public AstComparisonException() { this(null, null, AstDifference.DEEP_COMPARISON_FAILED); } public AstComparisonException(AstComparisonException e) { this(e, null, null, AstDifference.DEEP_COMPARISON_FAILED); } public AstComparisonException( AstNode a, AstNode b, AstDifference reason) { super(a, b); this.reason = reason; } protected AstComparisonException( AstComparisonException e, AstNode a, AstNode b) { this(e, a, b, AstDifference.CHILDREN_DIFFER); } protected AstComparisonException( AstComparisonException e, AstNode a, AstNode b, AstDifference reason) { super(e, a, b); this.reason = reason; } public AstNode getA() { return (AstNode) super.getA(); } public AstNode getB() { return (AstNode) super.getB(); } public AstDifference getReason() { return reason; } protected Writer toString(Writer w) throws IOException { if ((getA() != null) != (getB() != null)) { if (getA() != null) { w.append(String.format( "Node A of type %s is not null while node B is null: %s\n", getA().getNodeName(), reason.getReason())); } else { w.append(String.format( "Node B of type %s is not null while node A is null: %s\n", getB().getNodeName(), reason.getReason())); } } else if (getA().getClass() != getB().getClass()) { w.append(String.format( "Two nodes differ in type %s vs. %s: %s\n", getA().getClass().getName(), getB().getClass().getName(), reason.getReason())); } else { w.append(String.format( "Two nodes of type %s differ: %s\n", getA().getNodeName(), reason.getReason())); } return w; } @Override public String toString() { try { return toString(new StringWriter()).toString(); } catch (IOException e) { e.printStackTrace(); return null; } } } AstDifference.java000066400000000000000000000037111315622671000404340ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/main/java/de/fau/cs/osr/ptk/common/comparer/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common.comparer; public enum AstDifference { NULL_VS_NON_NULL { @Override public String getReason() { return "One node is null the other is non-null"; } }, NODE_TYPES_DIFFER { @Override public String getReason() { return "The two nodes have different type"; } }, LOCATION_DIFFERS { @Override public String getReason() { return "The two nodes have different locations"; } }, NUMBER_OF_CHILDREN_DIFFERS { @Override public String getReason() { return "The two nodes' number of children differs"; } }, PROPERTY_VALUE_DIFFERS { @Override public String getReason() { return "The value of a property differs between the two nodes"; } }, CHILDREN_DIFFER { @Override public String getReason() { return "One of the child nodes differs between the two nodes"; } }, NUMBER_OF_ATTRIBUTES_DIFFERS { @Override public String getReason() { return "The two nodes' number of attributes differs"; } }, ATTRIBUTE_VALUE_DIFFERS { @Override public String getReason() { return "The value of an attribute differs between the two nodes"; } }, DEEP_COMPARISON_FAILED { @Override public String getReason() { return "Deep comparison of two values failed"; } }; public abstract String getReason(); } AstEntityMapComparerDelegate.java000066400000000000000000000025401315622671000434370ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/main/java/de/fau/cs/osr/ptk/common/comparer/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common.comparer; import de.fau.cs.osr.ptk.common.AstEntityMap; import de.fau.cs.osr.utils.ComparisonException; import de.fau.cs.osr.utils.DeepComparer; import de.fau.cs.osr.utils.DeepComparerDelegate; public class AstEntityMapComparerDelegate implements DeepComparerDelegate { @Override public boolean compare(Object _a, Object _b, DeepComparer comparer) throws ComparisonException { if (!(_a instanceof AstEntityMap)) return false; if (!(_b instanceof AstEntityMap)) throw new ComparisonException(_a, _b); AstEntityMap a = (AstEntityMap) _a; AstEntityMap b = (AstEntityMap) _b; comparer.compare(a.getMap(), b.getMap()); return true; } } AstNodeComparerDelegate.java000066400000000000000000000126651315622671000424230ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/main/java/de/fau/cs/osr/ptk/common/comparer/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common.comparer; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import de.fau.cs.osr.ptk.common.ast.AstNode; import de.fau.cs.osr.ptk.common.ast.AstNodePropertyIterator; import de.fau.cs.osr.utils.ComparisonException; import de.fau.cs.osr.utils.DeepComparer; import de.fau.cs.osr.utils.DeepComparerDelegate; public class AstNodeComparerDelegate implements DeepComparerDelegate { private final boolean compareAttributes; private final boolean compareLocation; // ========================================================================= public AstNodeComparerDelegate( boolean compareAttributes, boolean compareLocation) { this.compareAttributes = compareAttributes; this.compareLocation = compareLocation; } // ========================================================================= @Override public boolean compare(Object a, Object b, DeepComparer comparer) throws ComparisonException { if (!(a instanceof AstNode && b instanceof AstNode)) return false; compare((AstNode) a, (AstNode) b, comparer); return true; } // ========================================================================= public void compare(AstNode a, AstNode b, DeepComparer comparer) throws ComparisonException { if (a == b) return; if ((a == null) != (b == null)) throw new AstComparisonException(a, b, AstDifference.NULL_VS_NON_NULL); if (a == null) return; if (a.getClass() != b.getClass()) throw new AstComparisonException(a, b, AstDifference.NODE_TYPES_DIFFER); if (compareLocation) { if (a.getNativeLocation() == null) { if (b.getNativeLocation() != null) throw new AstComparisonException(a, b, AstDifference.LOCATION_DIFFERS); } else if (!a.getNativeLocation().equals(b.getNativeLocation())) throw new AstComparisonException(a, b, AstDifference.LOCATION_DIFFERS); } // Compare attributes if (compareAttributes) { compareAttributes(a, b, comparer); } // Compare properties { AstNodePropertyIterator i = a.propertyIterator(); AstNodePropertyIterator j = b.propertyIterator(); while (i.next()) { // Should not be necessary, but it's here for safety if (!j.next()) throw new InternalError(); // Should not be necessary, but it's here for safety if (!i.getName().equals(j.getName())) throw new InternalError(); try { comparer.compare(i.getValue(), j.getValue()); } catch (AstComparisonException e) { throw new PropertyComparisonException(e, a, b, i.getName(), i.getValue(), j.getValue()); } } // Should not be necessary, but it's here for safety if (j.next()) throw new InternalError(); } // Compare children if (a.isList()) { if (a.size() != b.size()) throw new AstComparisonException(a, b, AstDifference.NUMBER_OF_CHILDREN_DIFFERS); @SuppressWarnings({ "rawtypes", "unchecked" }) Iterator i = (Iterator) a.iterator(); @SuppressWarnings({ "rawtypes", "unchecked" }) Iterator j = (Iterator) b.iterator(); int k = 0; while (i.hasNext() & j.hasNext()) { try { comparer.compare(i.next(), j.next()); ++k; } catch (AstComparisonException e) { throw new ComparisonOfChildrenFailedException(a, b, k, e); } } } else { String[] acn = a.getChildNames(); String[] bcn = b.getChildNames(); // Should not be necessary, but it's here for safety if (acn.length != bcn.length) throw new InternalError(); for (int i = 0; i < acn.length; ++i) { // Should not be necessary, but it's here for safety if (!acn[i].equals(bcn[i])) throw new InternalError(); try { comparer.compare(a.get(i), b.get(i)); } catch (AstComparisonException e) { throw new ComparisonOfChildrenFailedException(a, b, i, acn[i], e); } } } // Subtree is equal } private void compareAttributes( AstNode na, AstNode nb, DeepComparer comparer) throws ComparisonException { Map a = na.getAttributes(); Map b = nb.getAttributes(); if (b == a) return; if (b.size() != a.size()) throw new AstComparisonException(na, nb, AstDifference.NUMBER_OF_ATTRIBUTES_DIFFERS); Iterator> i = a.entrySet().iterator(); while (i.hasNext()) { Entry e = i.next(); String key = e.getKey(); Object value = e.getValue(); if (value == null) { if (!(b.get(key) == null && b.containsKey(key))) throw new AttributeComparisonException(na, nb, key, null, b.get(key)); } else { try { comparer.compare(value, b.get(key)); } catch (AstComparisonException ce) { throw new AttributeComparisonException(ce, na, nb, key, value, b.get(key)); } } } } } AttributeComparisonException.java000066400000000000000000000050111315622671000436020ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/main/java/de/fau/cs/osr/ptk/common/comparer/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common.comparer; import java.io.IOException; import java.io.Writer; import de.fau.cs.osr.ptk.common.ast.AstNode; import de.fau.cs.osr.utils.StringTools; public class AttributeComparisonException extends AstComparisonException { private static final long serialVersionUID = 1L; private final String attributeName; private final Object aAttributeValue; private final Object bAttributeValue; public AttributeComparisonException( AstNode a, AstNode b, String attributeName, Object aAttributeValue, Object bAttributeValue) { this(null, a, b, attributeName, aAttributeValue, bAttributeValue); } public AttributeComparisonException( AstComparisonException e, AstNode a, AstNode b, String attributeName, Object aAttributeValue, Object bAttributeValue) { super(e, a, b, AstDifference.ATTRIBUTE_VALUE_DIFFERS); this.attributeName = attributeName; this.aAttributeValue = aAttributeValue; this.bAttributeValue = bAttributeValue; } public String getAttributeName() { return attributeName; } public Object getAttributeAValue() { return aAttributeValue; } public Object getAttributeBValue() { return bAttributeValue; } public Writer toString(Writer w) throws IOException { if (getCause() != null) ((AstComparisonException) getCause()).toString(w); w.append(String.format( "Value of attribute `%s' differs between nodes of type %s:\n", attributeName, getA().getNodeName())); printValue("a", aAttributeValue, w); printValue("b", bAttributeValue, w); return w; } private void printValue(String which, Object value, Writer w) throws IOException { w.append("\t"); w.append(which); w.append(": "); if (value == null) w.append("null\n"); else { w.append("\"\"\""); w.append(StringTools.escJava(value.toString())); w.append("\"\"\"\n"); } } } ComparisonOfChildrenFailedException.java000066400000000000000000000040021315622671000447600ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/main/java/de/fau/cs/osr/ptk/common/comparer/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common.comparer; import java.io.IOException; import java.io.Writer; import de.fau.cs.osr.ptk.common.ast.AstNode; public class ComparisonOfChildrenFailedException extends AstComparisonException { private static final long serialVersionUID = 1L; private final int childIndex; private final String childName; public ComparisonOfChildrenFailedException( AstNode a, AstNode b, int childIndex, AstComparisonException e) { super(e, a, b); this.childIndex = childIndex; this.childName = null; } public ComparisonOfChildrenFailedException( AstNode a, AstNode b, int childIndex, String childName, AstComparisonException e) { super(e, a, b); this.childIndex = childIndex; this.childName = childName; } public int getChildIndex() { return childIndex; } public String getChildName() { return childName; } public Writer toString(Writer w) throws IOException { ((AstComparisonException) getCause()).toString(w); if (childName == null) { w.append(String.format( "The %dth child nodes of two list nodes of type %s differ.\n", childIndex, getA().getNodeName())); } else { w.append(String.format( "The %dth child nodes (`%s') of two list nodes of type %s differ.\n", childIndex, childName, getA().getNodeName())); } return w; } } DeepComparisonException.java000066400000000000000000000037731315622671000425310ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/main/java/de/fau/cs/osr/ptk/common/comparer/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common.comparer; import java.io.IOException; import java.io.Writer; import de.fau.cs.osr.ptk.common.ast.AstNode; import de.fau.cs.osr.utils.StringTools; public class DeepComparisonException extends AstComparisonException { private static final long serialVersionUID = 1L; private final Object a; private final Object b; public DeepComparisonException(Object a, Object b) { this.a = a; this.b = b; } public DeepComparisonException( AstComparisonException e, AstNode a, AstNode b) { super(e); this.a = a; this.b = b; } public Object getObjectA() { return a; } public Object getObjectB() { return b; } public Writer toString(Writer w) throws IOException { if (getCause() != null) ((AstComparisonException) getCause()).toString(w); w.append(String.format( "Values during deep comparison differed (%s vs. %s):\n", (a == null ? "-" : a.getClass().getName()), (b == null ? "-" : b.getClass().getName()))); printValue("a", a, w); printValue("b", b, w); return w; } private void printValue(String which, Object value, Writer w) throws IOException { w.append("\t"); w.append(which); w.append(": "); if (value == null) w.append("null\n"); else { w.append("\"\"\""); w.append(StringTools.escJava(value.toString())); w.append("\"\"\"\n"); } } } PropertyComparisonException.java000066400000000000000000000044151315622671000434720ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/main/java/de/fau/cs/osr/ptk/common/comparer/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common.comparer; import java.io.IOException; import java.io.Writer; import de.fau.cs.osr.ptk.common.ast.AstNode; import de.fau.cs.osr.utils.StringTools; public class PropertyComparisonException extends AstComparisonException { private static final long serialVersionUID = 1L; private final String propertyName; private final Object aPropertyValue; private final Object bPropertyValue; public PropertyComparisonException( AstComparisonException e, AstNode a, AstNode b, String propertyName, Object aPropertyValue, Object bPropertyValue) { super(e, a, b, AstDifference.PROPERTY_VALUE_DIFFERS); this.propertyName = propertyName; this.aPropertyValue = aPropertyValue; this.bPropertyValue = bPropertyValue; } public String getPropertyName() { return propertyName; } public Object getPropertyAValue() { return aPropertyValue; } public Object getPropertyBValue() { return bPropertyValue; } public Writer toString(Writer w) throws IOException { if (getCause() != null) ((AstComparisonException) getCause()).toString(w); w.append(String.format( "Value of property `%s' differs between nodes of type %s:\n", propertyName, getA().getNodeName())); printValue("a", aPropertyValue, w); printValue("b", bPropertyValue, w); return w; } private void printValue(String which, Object value, Writer w) throws IOException { w.append("\t"); w.append(which); w.append(": "); if (value == null) w.append("null\n"); else { w.append("\"\"\""); w.append(StringTools.escJava(value.toString())); w.append("\"\"\"\n"); } } } serialization/000077500000000000000000000000001315622671000361325ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/main/java/de/fau/cs/osr/ptk/commonAstConverterBase.java000066400000000000000000000030621315622671000422100ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/main/java/de/fau/cs/osr/ptk/common/serialization/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common.serialization; public class AstConverterBase { private TypeNameMapper typeNameMapper = new SimpleTypeNameMapper(); // ========================================================================= public void setTypeNameMapper(TypeNameMapper typeNameMapper) { this.typeNameMapper = typeNameMapper; } // ========================================================================= protected String getTypeAlias(Class n) { String typeAlias = typeNameMapper.nameForType(n); if (typeAlias == null) throw new MissingTypeInformationException( "Cannot determine type alias for class '" + n.getName() + "'"); return typeAlias; } protected Class getClassForAlias(String typeAlias) { Class type = typeNameMapper.typeForName(typeAlias); if (type == null) throw new UnknownTypeException("Cannot find type for name '" + typeAlias + "'"); return type; } } AstNodeConverterBase.java000066400000000000000000000244601315622671000430230ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/main/java/de/fau/cs/osr/ptk/common/serialization/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common.serialization; import java.beans.IntrospectionException; import java.beans.PropertyDescriptor; import java.lang.reflect.Method; import java.util.Arrays; import java.util.Enumeration; import java.util.HashSet; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import de.fau.cs.osr.ptk.common.ast.AstNode; import de.fau.cs.osr.ptk.common.ast.AstNodePropertyIterator; import de.fau.cs.osr.ptk.common.ast.AstStringNode; import de.fau.cs.osr.ptk.common.serialization.NodeFactory.NamedMemberId; import de.fau.cs.osr.utils.ReflectionUtils; public class AstNodeConverterBase> extends AstConverterBase { private static final int LOWER_CAPACITY = 256; private static final int UPPER_CAPACITY = 384; private static final float LOAD_FACTOR = .6f; private static final ConcurrentHashMap CACHE = new ConcurrentHashMap(LOWER_CAPACITY, LOAD_FACTOR); // ========================================================================= private final Class nodeType; private NodeFactory nodeFactory = new SimpleNodeFactory(); private boolean alwaysStoreType = false; private Set> suppressTypeInfo = null; private boolean storeLocation = true; private boolean storeAttributes = true; private Set suppressAttributes = null; private boolean suppressEmptyStringProperties = false; private Set suppressProperties = null; private Set> suppressNodes = null; private Class> stringNodeType; private boolean suppressEmptyStringNodes = false; // ========================================================================= public AstNodeConverterBase(Class nodeType) { this.nodeType = nodeType; } // ========================================================================= public void setNodeFactory(NodeFactory nodeFactory) { this.nodeFactory = nodeFactory; } public NodeFactory getNodeFactory() { return nodeFactory; } public void setAlwaysStoreType(boolean alwaysStoreType) { this.alwaysStoreType = alwaysStoreType; } public void suppressTypeInfo(Class type) { if (this.suppressTypeInfo == null) this.suppressTypeInfo = new HashSet>(); this.suppressTypeInfo.add(type); } public void setStoreLocation(boolean storeLocation) { this.storeLocation = storeLocation; } public void setStoreAttributes(boolean storeAttributes) { this.storeAttributes = storeAttributes; } public void suppressAttribute(String name) { if (this.suppressAttributes == null) this.suppressAttributes = new HashSet(); this.suppressAttributes.add(name); } public void setSuppressEmptyStringProperties( boolean suppressEmptyStringProperties) { this.suppressEmptyStringProperties = suppressEmptyStringProperties; } public void suppressProperty(String name) { if (this.suppressProperties == null) this.suppressProperties = new HashSet(); this.suppressProperties.add(name); } public void suppressNode(Class nodeType) { if (this.suppressNodes == null) this.suppressNodes = new HashSet>(); this.suppressNodes.add(nodeType); } public void setStringNodeType( Class> stringNodeType) { this.stringNodeType = stringNodeType; } public void setSuppressEmptyStringNodes(boolean suppressEmptyStringNodes) { this.suppressEmptyStringNodes = suppressEmptyStringNodes; } // ========================================================================= protected Class getNodeType() { return nodeType; } public boolean isAlwaysStoreType() { return alwaysStoreType; } protected boolean isTypeInfoSuppressed(Class type) { return !alwaysStoreType && ((suppressTypeInfo != null) && suppressTypeInfo.contains(type)); } protected boolean isLocationSuppressed() { return !storeLocation; } protected boolean isAttributesSuppressed() { return !storeAttributes; } protected boolean isAttributeSuppressed(String name) { return isAttributesSuppressed() || ((suppressAttributes != null) && suppressAttributes.contains(name)); } protected boolean isPropertySuppressed(String name) { return ((suppressProperties != null) && suppressProperties.contains(name)); } protected boolean isSuppressed(Object n) { Class objType = n.getClass(); if (suppressNodes != null && suppressNodes.contains(objType)) { return true; } else if (suppressEmptyStringNodes && isStringNode(objType)) { @SuppressWarnings("unchecked") String content = ((AstStringNode) n).getContent(); if (content.isEmpty()) return true; } else if (suppressEmptyStringProperties && String.class == objType) { String content = (String) n; if (content.isEmpty()) return true; } return false; } protected boolean isStringNode(Class clazz) { return stringNodeType == clazz; } public Class> getStringNodeType() { return stringNodeType; } // ========================================================================= protected T instantiateNode(Class clazz) { return nodeFactory.instantiateNode(clazz); } protected T instantiateDefaultChild(T n, String name, Class child) { return nodeFactory.instantiateDefaultChild( new NamedMemberId(n.getClass(), name), child); } protected void setDefaultChild(T n, int childIndex, String childName) { Class type = getGetterType(n, childName); T value = instantiateDefaultChild(n, childName, type); n.set(childIndex, value); } private Object instantiateDefaultProperty(T n, String name, Class type) { return nodeFactory.instantiateDefaultProperty( new NamedMemberId(n.getClass(), name), type); } protected void setDefaultProperty(T n, AstNodePropertyIterator i) { String name = i.getName(); Class type = getGetterType(n, name); Object value = instantiateDefaultProperty(n, name, type); i.setValue(value); } // ========================================================================= protected String getTypeAlias(AstNode n) { return getTypeAlias(n.getClass()); } protected boolean serializedTypeIsExpectedType( Class expectedType, Class childType) { if (childType == expectedType) return true; // Maybe we have a (Integer != int) problem? if (expectedType.isPrimitive()) return ReflectionUtils.mapPrimitiveToUcType(expectedType) == childType; return false; } protected boolean serializedTypeIsExpectedType( AstNode parent, String name, Class valueType) { return serializedTypeIsExpectedType(getGetterType(parent, name), valueType); } protected boolean isTypeInfoRequired( AstNode parentNode, String name, Class valueType) { return alwaysStoreType || (!serializedTypeIsExpectedType(parentNode, name, valueType) && !isTypeInfoSuppressed(valueType)); } protected Class getGetterType(AstNode n, String name) { Class nodeType = n.getClass(); Getter getter = new Getter(nodeType, name); Getter cached = CACHE.get(getter); if (cached != null) return cached.getGetterType(); return analyzeGetter(name, nodeType); } private Class analyzeGetter(String name, Class nodeType) { Method getterMethod; try { getterMethod = new PropertyDescriptor(name, nodeType).getReadMethod(); } catch (IntrospectionException e) { throw new IncompatibleAstNodeClassException("Class '" + nodeType.getName() + "' is malformed", e); } Class getterType = getterMethod.getReturnType(); rememberGetter(name, nodeType, getterType); return getterType; } private void rememberGetter( String name, Class nodeType, Class getterType) { Getter getter = new Getter(nodeType, name, getterType); Getter cached = CACHE.putIfAbsent(getter, getter); if (cached == null) { // Make sure the target is not swept from the cache ... getter.touch(); if (CACHE.size() > UPPER_CAPACITY) sweepCache(); } } private static synchronized void sweepCache() { if (CACHE.size() <= UPPER_CAPACITY) return; Getter keys[] = new Getter[CACHE.size()]; Enumeration keysEnum = CACHE.keys(); int i = 0; while (i < keys.length && keysEnum.hasMoreElements()) keys[i++] = keysEnum.nextElement(); int length = i; Arrays.sort(keys, 0, length); int to = length - LOWER_CAPACITY; for (int j = 0; j < to; ++j) CACHE.remove(keys[j]); } // ========================================================================= protected static final class Getter implements Comparable { private static long useCounter = 0; private long lastUse = -1; private Class nodeType; private String fieldName; private Class getterType; public Getter(Class nodeType, String fieldName) { this.nodeType = nodeType; this.fieldName = fieldName; this.getterType = null; } public Getter(Class nodeType, String fieldName, Class getterType) { this.nodeType = nodeType; this.fieldName = fieldName; this.getterType = getterType; } public Class getNodeType() { return nodeType; } public String getFieldName() { return fieldName; } public Class getGetterType() { return getterType; } @Override public int hashCode() { return fieldName.hashCode() + 31 * nodeType.hashCode(); } @Override public boolean equals(Object obj) { Getter other = (Getter) obj; if (!fieldName.equals(other.fieldName)) return false; if (nodeType != other.nodeType) return false; return true; } public void touch() { lastUse = ++useCounter; } @Override public int compareTo(Getter o) { // Equality is not possible! return (lastUse < o.lastUse) ? -1 : +1; } } } IncompatibleAstNodeClassException.java000066400000000000000000000022361315622671000455310ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/main/java/de/fau/cs/osr/ptk/common/serialization/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common.serialization; public class IncompatibleAstNodeClassException extends RuntimeException { private static final long serialVersionUID = 1L; public IncompatibleAstNodeClassException() { super(); } public IncompatibleAstNodeClassException(String message, Throwable cause) { super(message, cause); } public IncompatibleAstNodeClassException(String message) { super(message); } public IncompatibleAstNodeClassException(Throwable cause) { super(cause); } } MissingTypeInformationException.java000066400000000000000000000022111315622671000453310ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/main/java/de/fau/cs/osr/ptk/common/serialization/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common.serialization; public class MissingTypeInformationException extends RuntimeException { private static final long serialVersionUID = 1L; public MissingTypeInformationException() { } public MissingTypeInformationException(String message, Throwable cause) { super(message, cause); } public MissingTypeInformationException(String message) { super(message); } public MissingTypeInformationException(Throwable cause) { super(cause); } } NoDefaultValueException.java000066400000000000000000000021411315622671000435300ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/main/java/de/fau/cs/osr/ptk/common/serialization/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common.serialization; public class NoDefaultValueException extends RuntimeException { private static final long serialVersionUID = 1L; public NoDefaultValueException() { } public NoDefaultValueException(String message, Throwable cause) { super(message, cause); } public NoDefaultValueException(String message) { super(message); } public NoDefaultValueException(Throwable cause) { super(cause); } } NodeFactory.java000066400000000000000000000036401315622671000412150ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/main/java/de/fau/cs/osr/ptk/common/serialization/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common.serialization; import de.fau.cs.osr.ptk.common.ast.AstNode; public interface NodeFactory> { public T instantiateNode(Class clazz); public T instantiateDefaultChild(NamedMemberId id, Class childType); public Object instantiateDefaultProperty(NamedMemberId id, Class type); // ========================================================================= public static final class NamedMemberId { public final Class nodeType; public final String memberName; // ===================================================================== /** * You must not pass null values to either of the parameters. */ public NamedMemberId(Class nodeType, String memberName) { assert nodeType != null && memberName != null; this.nodeType = nodeType; this.memberName = memberName; } @Override public int hashCode() { return memberName.hashCode() ^ nodeType.hashCode(); } @Override public boolean equals(Object obj) { assert obj != null && getClass() == obj.getClass(); // Let's optimize a bit even if it breaks the contract of equals... NamedMemberId other = (NamedMemberId) obj; return memberName.equals(other.memberName) && (nodeType == other.nodeType); } } } SimpleNodeFactory.java000066400000000000000000000034301315622671000423640ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/main/java/de/fau/cs/osr/ptk/common/serialization/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common.serialization; import de.fau.cs.osr.ptk.common.ast.AstNode; public class SimpleNodeFactory> implements NodeFactory { public T instantiateNode(Class clazz) { try { @SuppressWarnings("unchecked") T n = (T) clazz.newInstance(); return n; } catch (InstantiationException e) { throw new IncompatibleAstNodeClassException("Class '" + clazz.getName() + "' cannot be instantiated", e); } catch (IllegalAccessException e) { throw new IncompatibleAstNodeClassException("Class '" + clazz.getName() + "' cannot be instantiated", e); } } public T instantiateDefaultChild(NamedMemberId id, Class type) { throw new NoDefaultValueException("Don't know which class to " + "instantiate as default for child '" + id.memberName + "' of node '" + id.nodeType.getName() + "'"); } public Object instantiateDefaultProperty( NamedMemberId id, Class type) { throw new NoDefaultValueException("Don't know which class to " + "instantiate as default for property '" + id.memberName + "' of node '" + id.nodeType.getName() + "'"); } } SimpleTypeNameMapper.java000066400000000000000000000061261315622671000430430ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/main/java/de/fau/cs/osr/ptk/common/serialization/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common.serialization; import de.fau.cs.osr.utils.DualHashBidiMap; import de.fau.cs.osr.utils.ReflectionUtils; import de.fau.cs.osr.utils.ReflectionUtils.ArrayInfo; import de.fau.cs.osr.utils.StringTools; public class SimpleTypeNameMapper implements TypeNameMapper { private DualHashBidiMap typeToName; // ========================================================================= public SimpleTypeNameMapper() { typeToName = new DualHashBidiMap(); } public SimpleTypeNameMapper(SimpleTypeNameMapper stnm) { typeToName = new DualHashBidiMap(stnm.typeToName); } // ========================================================================= public void add(Class type, String name) { typeToName.put(type, name); } // ========================================================================= @Override public String nameForType(Class n) { String typeAlias = (String) typeToName.get(n); if (typeAlias != null) return typeAlias; if (n.isArray()) { ArrayInfo dim = ReflectionUtils.arrayDimension(n); String elementTypeName = nameForType(dim.elementClass); return elementTypeName + StringTools.strrep("[]", dim.dim); } if (ReflectionUtils.isBasicDataType(n)) return ReflectionUtils.abbreviateBasicDataTypeName(n); return nameForUnmappedType(n); } protected String nameForUnmappedType(Class n) { return n.getName(); } // ========================================================================= @Override public Class typeForName(String name) { if (name.isEmpty()) return typeForInvalidName(name); Class type = (Class) typeToName.getKey(name); if (type != null) return type; int nameEnd = name.indexOf("[]"); if (nameEnd > 0) { int i; for (i = nameEnd + 2; i < name.length(); i += 2) { if (name.indexOf("[]", i) != i) return typeForInvalidName(name); } return ReflectionUtils.arrayClassFor( typeForName(name.substring(0, nameEnd)), (i - nameEnd) / 2); } if (ReflectionUtils.isBasicDataType(name)) return ReflectionUtils.getTypeFromAbbreviation(name); return typeForUnmappedName(name); } protected Class typeForInvalidName(String name) { throw new IllegalArgumentException("Illegal type name '" + name + "'"); } protected Class typeForUnmappedName(String name) { try { return Class.forName(name); } catch (ClassNotFoundException e1) { // Cannot map type return null; } } } SyntaxErrorException.java000066400000000000000000000021221315622671000431510ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/main/java/de/fau/cs/osr/ptk/common/serialization/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common.serialization; public class SyntaxErrorException extends RuntimeException { private static final long serialVersionUID = 1L; public SyntaxErrorException() { } public SyntaxErrorException(String message, Throwable cause) { super(message, cause); } public SyntaxErrorException(String message) { super(message); } public SyntaxErrorException(Throwable cause) { super(cause); } } TypeNameMapper.java000066400000000000000000000016411315622671000416660ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/main/java/de/fau/cs/osr/ptk/common/serialization/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common.serialization; /** * Interface for a service that bijectively maps types to names and those names * back to types. */ public interface TypeNameMapper { String nameForType(Class n); Class typeForName(String name); } UnknownTypeException.java000066400000000000000000000021221315622671000431520ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/main/java/de/fau/cs/osr/ptk/common/serialization/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common.serialization; public class UnknownTypeException extends RuntimeException { private static final long serialVersionUID = 1L; public UnknownTypeException() { } public UnknownTypeException(String message, Throwable cause) { super(message, cause); } public UnknownTypeException(String message) { super(message); } public UnknownTypeException(Throwable cause) { super(cause); } } test/000077500000000000000000000000001315622671000342345ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/main/java/de/fau/cs/osr/ptk/commonnodes/000077500000000000000000000000001315622671000353445ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/main/java/de/fau/cs/osr/ptk/common/testCtnBody.java000066400000000000000000000051161315622671000375540ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/main/java/de/fau/cs/osr/ptk/common/test/nodes/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common.test.nodes; import de.fau.cs.osr.ptk.common.ast.AstNodeList; import de.fau.cs.osr.ptk.common.ast.AstNodeListImpl; public interface CtnBody extends CtnNode, AstNodeList { public static final CtnBody.CtnNoBody NO_BODY = new CtnNoBody(); public static final CtnBody.CtnEmptyBody EMPTY = new CtnEmptyBody(); // ========================================================================= public static final class CtnNoBody extends CtnEmptyImmutableNode implements CtnBody { private static final long serialVersionUID = -1064749733891892633L; protected CtnNoBody() { } @Override public int getNodeType() { return NT_TEST_BODY; } @Override public String getNodeName() { return "body"; } @Override public void exchange(AstNodeList other) { throw new UnsupportedOperationException(genMsg()); } } // ========================================================================= public static final class CtnEmptyBody extends CtnEmptyImmutableNode implements CtnBody { private static final long serialVersionUID = -1064749733891892633L; protected CtnEmptyBody() { } @Override public int getNodeType() { return NT_TEST_BODY; } @Override public String getNodeName() { return "body"; } @Override public void exchange(AstNodeList other) { throw new UnsupportedOperationException(genMsg()); } } // ========================================================================= public static final class CtnBodyImpl extends AstNodeListImpl implements CtnBody { private static final long serialVersionUID = 1L; protected CtnBodyImpl() { } protected CtnBodyImpl(CtnNode... children) { super(children); } @Override public int getNodeType() { return NT_TEST_BODY; } @Override public String getNodeName() { return "body"; } } } CtnBuilder.java000066400000000000000000000061741315622671000402520ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/main/java/de/fau/cs/osr/ptk/common/test/nodes/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common.test.nodes; public class CtnBuilder { public static CtnText ctnText() { return new CtnText("Default text"); } public static CtnText ctnText(String text) { return new CtnText(text); } public static CtnNodeList ctnList() { return new CtnNodeList(); } public static CtnNodeList ctnList(CtnNode... children) { return new CtnNodeList(children); } public static SectionBuilder ctnSection() { return new SectionBuilder(); } public static CtnTitle ctnTitle(CtnNode... children) { return new CtnTitle.CtnTitleImpl(children); } public static CtnBody ctnBody(CtnNode... children) { return new CtnBody.CtnBodyImpl(children); } public static CtnDocument ctnDoc(CtnNode... children) { return new CtnDocument(children); } public static CtnIdNode ctnId(int i) { return new CtnIdNode(i); } public static UrlBuilder ctnUrl() { return new UrlBuilder(); } public static CtnNodeWithObjProp ctnObjProp(Object prop) { return new CtnNodeWithObjProp(prop); } public static CtnNodeWithPropAndContent ctnPropContent( Object prop, String content) { return new CtnNodeWithPropAndContent(prop, content); } // ========================================================================= public static final class SectionBuilder { private int level = 0; private CtnTitle title = new CtnTitle.CtnTitleImpl(ctnText("Default section title")); private CtnBody body = new CtnBody.CtnBodyImpl(ctnText("Default section body")); public SectionBuilder withLevel(int level) { this.level = level; return this; } public SectionBuilder withTitle(CtnTitle title) { this.title = title; return this; } public SectionBuilder withTitle(CtnNode... children) { this.title = new CtnTitle.CtnTitleImpl(children); return this; } public SectionBuilder withBody(CtnBody body) { this.body = body; return this; } public SectionBuilder withBody(CtnNode... children) { this.body = new CtnBody.CtnBodyImpl(children); return this; } public CtnSection build() { return new CtnSection(level, title, body); } } public static final class UrlBuilder { private String protocol = "http"; private String path = "example.org"; public UrlBuilder withProtocol(String protocol) { this.protocol = protocol; return this; } public UrlBuilder withPath(String path) { this.path = path; return this; } public CtnUrl build() { return new CtnUrl(protocol, path); } } } CtnDocument.java000066400000000000000000000024411315622671000404330ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/main/java/de/fau/cs/osr/ptk/common/test/nodes/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common.test.nodes; import de.fau.cs.osr.ptk.common.ast.AstNodeListImpl; public final class CtnDocument extends AstNodeListImpl implements CtnNode { private static final long serialVersionUID = 1L; // ========================================================================= protected CtnDocument() { } protected CtnDocument(CtnNode... children) { super(children); } // ========================================================================= @Override public int getNodeType() { return NT_TEST_DOCUMENT; } @Override public String getNodeName() { return "document"; } } CtnEmptyImmutableNode.java000066400000000000000000000234511315622671000424250ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/main/java/de/fau/cs/osr/ptk/common/test/nodes/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common.test.nodes; import java.io.IOException; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Map; import de.fau.cs.osr.ptk.common.ast.AstNode; import de.fau.cs.osr.ptk.common.ast.AstNodePropertyIterator; import xtc.tree.Locatable; import xtc.tree.Location; import xtc.util.Pair; public abstract class CtnEmptyImmutableNode implements CtnNode { private static final long serialVersionUID = -8143436141986490761L; // ========================================================================= protected String genMsg() { return "You are operating on an immutable " + getNodeName() + " object!"; } // ========================================================================= @Override public boolean hasLocation() { return false; } @Override public Location getLocation() { return null; } @Override public void setLocation(Location location) { // This is called by the parser, can't prevent that ... } @Override public void setLocation(Locatable locatable) { // This is called by the parser, can't prevent that ... } // ========================================================================= @Override public boolean hasAttributes() { return false; } @Override public Map getAttributes() { return Collections.emptyMap(); } @Override public void setAttributes(Map attrs) { throw new UnsupportedOperationException(genMsg()); } @Override public void clearAttributes() { throw new UnsupportedOperationException(genMsg()); } @Override public boolean hasAttribute(String name) { return false; } @Override public Object getAttribute(String name) { return null; } @Override public Object setAttribute(String name, Object value) { throw new UnsupportedOperationException(genMsg()); } @Override public Object removeAttribute(String name) { throw new UnsupportedOperationException(genMsg()); } @Override public int getIntAttribute(String name) { return 0; } @Override public Integer setIntAttribute(String name, Integer value) { throw new UnsupportedOperationException(genMsg()); } @Override public boolean getBooleanAttribute(String name) { return false; } @Override public boolean setBooleanAttribute(String name, boolean value) { throw new UnsupportedOperationException(genMsg()); } @Override public String getStringAttribute(String name) { return null; } @Override public String setStringAttribute(String name, String value) { throw new UnsupportedOperationException(genMsg()); } // ========================================================================= @Override public boolean hasProperties() { return false; } @Override public int getPropertyCount() { return 0; } @Override public Object getProperty(String name) { throw new UnsupportedOperationException(genMsg()); } @Override public Object getProperty(String name, Object default_) { return default_; } @Override public boolean hasProperty(String name) { return false; } @Override public Object setProperty(String name, Object value) { throw new UnsupportedOperationException(genMsg()); } @Override public AstNodePropertyIterator propertyIterator() { return new AstNodePropertyIterator() { @Override protected Object setValue(int index, Object value) { throw new UnsupportedOperationException(genMsg()); } @Override protected Object getValue(int index) { throw new UnsupportedOperationException(genMsg()); } @Override protected int getPropertyCount() { return 0; } @Override protected String getName(int index) { throw new UnsupportedOperationException(genMsg()); } }; } // ========================================================================= @Override public abstract int getNodeType(); @Override public boolean isNodeType(int testType) { return getNodeType() == testType; } @Override public final String getNodeTypeName() { return getClass().getName(); } @Override public abstract String getNodeName(); @Override public de.fau.cs.osr.ptk.common.ast.AstLocation getNativeLocation() { return null; } @Override public void setNativeLocation( de.fau.cs.osr.ptk.common.ast.AstLocation location) { throw new UnsupportedOperationException(genMsg()); } @Override public boolean addAll(Pair p) { throw new UnsupportedOperationException(genMsg()); } @Override public boolean isList() { return false; } @Override public String[] getChildNames() { return EMPTY_CHILD_NAMES; } @Override public void toString(Appendable out) throws IOException { out.append(getClass().getSimpleName()); out.append("()"); } @Override public Object clone() throws CloneNotSupportedException { throw new UnsupportedOperationException(genMsg()); } @Override public AstNode cloneWrapException() { throw new UnsupportedOperationException(genMsg()); } @Override public AstNode deepClone() throws CloneNotSupportedException { throw new UnsupportedOperationException(genMsg()); } @Override public AstNode deepCloneWrapException() { throw new UnsupportedOperationException(genMsg()); } // ========================================================================= @Override public void add(int index, CtnNode element) { throw new UnsupportedOperationException(genMsg()); } @Override public boolean add(CtnNode e) { throw new UnsupportedOperationException(genMsg()); } @Override public boolean addAll(Collection c) { throw new UnsupportedOperationException(genMsg()); } @Override public boolean addAll(int index, Collection c) { throw new UnsupportedOperationException(genMsg()); } @Override public void clear() { throw new UnsupportedOperationException(genMsg()); } @Override public boolean contains(Object o) { return false; } @Override public boolean containsAll(Collection c) { return false; } @Override public CtnNode get(int index) { throw new UnsupportedOperationException(genMsg()); } @Override public S get(int index, Class clazz) { throw new UnsupportedOperationException(genMsg()); } @Override public int indexOf(Object o) { return -1; } @Override public boolean isEmpty() { return true; } @Override public Iterator iterator() { return new Iterator() { @Override public void remove() { throw new UnsupportedOperationException(genMsg()); } @Override public CtnNode next() { throw new UnsupportedOperationException(genMsg()); } @Override public boolean hasNext() { return false; } }; } @Override public int lastIndexOf(Object o) { return -1; } @Override public ListIterator listIterator() { return new NullNodeListIterator(); } @Override public ListIterator listIterator(int index) { return new NullNodeListIterator(); } @Override public CtnNode remove(int index) { throw new UnsupportedOperationException(genMsg()); } @Override public boolean remove(Object o) { throw new UnsupportedOperationException(genMsg()); } @Override public boolean removeAll(Collection c) { throw new UnsupportedOperationException(genMsg()); } @Override public boolean retainAll(Collection c) { throw new UnsupportedOperationException(genMsg()); } @Override public CtnNode set(int index, CtnNode element) { throw new UnsupportedOperationException(genMsg()); } @Override public int size() { return 0; } @Override public List subList(int fromIndex, int toIndex) { if (fromIndex == toIndex) return Collections.emptyList(); throw new UnsupportedOperationException(genMsg()); } @Override public Object[] toArray() { return new Object[] {}; } @Override public T[] toArray(T[] a) { if (a.length > 0) a[0] = null; return a; } // ========================================================================= private final class NullNodeListIterator implements ListIterator { @Override public void set(CtnNode arg0) { throw new UnsupportedOperationException(genMsg()); } @Override public void remove() { throw new UnsupportedOperationException(genMsg()); } @Override public int previousIndex() { return -1; } @Override public CtnNode previous() { throw new UnsupportedOperationException(genMsg()); } @Override public int nextIndex() { return 0; } @Override public CtnNode next() { throw new UnsupportedOperationException(genMsg()); } @Override public boolean hasPrevious() { return false; } @Override public boolean hasNext() { return false; } @Override public void add(CtnNode arg0) { throw new UnsupportedOperationException(genMsg()); } } // ========================================================================= @Override public String toString() { return "---"; } @Override public boolean equals(Object obj) { if (obj == null) return false; return (obj.getClass() == getClass()); } } CtnFactory.java000066400000000000000000000070061315622671000402660ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/main/java/de/fau/cs/osr/ptk/common/test/nodes/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common.test.nodes; import java.util.HashMap; import java.util.Map; import de.fau.cs.osr.ptk.common.serialization.NodeFactory; import de.fau.cs.osr.ptk.common.serialization.SimpleNodeFactory; public class CtnFactory extends SimpleNodeFactory { private static CtnFactory factory = null; public static NodeFactory get() { if (factory == null) factory = new CtnFactory(); return factory; } // ========================================================================= private final Map, CtnNode> prototypes = new HashMap, CtnNode>(); private final Map defaultValueImmutables = new HashMap(); // ========================================================================= public CtnFactory() { addPrototype(new CtnText()); addPrototype(new CtnNodeList()); addPrototype(new CtnSection()); addPrototype(new CtnDocument()); addPrototype(new CtnUrl()); addPrototype(new CtnNodeWithObjProp()); addPrototype(new CtnNodeWithPropAndContent()); addPrototype(new CtnTitle.CtnTitleImpl(), CtnTitle.class); addPrototype(new CtnBody.CtnBodyImpl(), CtnBody.class); addDvi(CtnUrl.class, "protocol", ""); addDvi(CtnSection.class, "body", CtnBody.NO_BODY); addDvi(CtnSection.class, "title", CtnTitle.NO_TITLE); addDvi(CtnNodeWithObjProp.class, "prop", null); addDvi(CtnNodeWithPropAndContent.class, "prop", null); } private void addPrototype(CtnNode prototype) { prototypes.put(prototype.getClass(), prototype); } private void addPrototype( CtnNode prototype, Class clazz) { prototypes.put(clazz, prototype); } private void addDvi( Class clazz, String memberName, Object defaultValue) { defaultValueImmutables.put(new NamedMemberId(clazz, memberName), defaultValue); } // ========================================================================= // ========================================================================= @Override public CtnNode instantiateNode(Class clazz) { CtnNode p = prototypes.get(clazz); try { if (p != null) return (CtnNode) p.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } return super.instantiateNode(clazz); } @Override public CtnNode instantiateDefaultChild( NodeFactory.NamedMemberId id, Class type) { CtnNode p = (CtnNode) defaultValueImmutables.get(id); if (p != null) return p; if (defaultValueImmutables.containsKey(id)) return null; return super.instantiateDefaultChild(id, type); } @Override public Object instantiateDefaultProperty( NodeFactory.NamedMemberId id, Class type) { Object p = defaultValueImmutables.get(id); if (p != null) return p; if (defaultValueImmutables.containsKey(id)) return null; return super.instantiateDefaultProperty(id, type); } } CtnIdNode.java000066400000000000000000000034451315622671000400240ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/main/java/de/fau/cs/osr/ptk/common/test/nodes/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common.test.nodes; import de.fau.cs.osr.ptk.common.ast.AstLeafNodeImpl; public final class CtnIdNode extends AstLeafNodeImpl implements CtnNode { private static final long serialVersionUID = 1L; public int id = -1; // ========================================================================= protected CtnIdNode(int id) { this.id = id; } // ========================================================================= @Override public int getNodeType() { return NT_ID_NODE; } @Override public String getNodeName() { return "id"; } // ========================================================================= @Override public String toString() { return "IdNode [id=" + id + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + id; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; CtnIdNode other = (CtnIdNode) obj; if (id != other.id) return false; return true; } } CtnNode.java000066400000000000000000000026301315622671000375420ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/main/java/de/fau/cs/osr/ptk/common/test/nodes/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common.test.nodes; import de.fau.cs.osr.ptk.common.ast.AstNode; /** * Common Test Node */ public interface CtnNode extends AstNode { public static final int AST_TEST_NODE = AstNode.NT_CUSTOM_BIT; public static final int NT_TEST_DOCUMENT = AST_TEST_NODE + 1; public static final int NT_ID_NODE = AST_TEST_NODE + 2; public static final int NT_TEST_SECTION = AST_TEST_NODE + 3; public static final int NT_TEST_TITLE = AST_TEST_NODE + 4; public static final int NT_TEST_BODY = AST_TEST_NODE + 5; public static final int NT_TEST_URL = AST_TEST_NODE + 6; public static final int NT_TEST_NODE_WITH_OBJ_PROP = AST_TEST_NODE + 7; public static final int NT_TEST_NODE_WITH_PROP_AND_CONTENT = AST_TEST_NODE + 8; } CtnNodeList.java000066400000000000000000000034761315622671000404070ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/main/java/de/fau/cs/osr/ptk/common/test/nodes/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common.test.nodes; import java.util.Collection; import de.fau.cs.osr.ptk.common.ast.AstNodeListImpl; import xtc.util.Pair; public final class CtnNodeList extends AstNodeListImpl implements CtnNode { private static final long serialVersionUID = 1L; // ========================================================================= protected CtnNodeList() { } protected CtnNodeList(Collection list) { super(list); } protected CtnNodeList(Pair list) { super(list); } protected CtnNodeList(CtnNode car, Pair cdr) { super(car, cdr); } protected CtnNodeList( CtnNode a, CtnNode b, CtnNode c, CtnNode d) { super(a, b, c, d); } protected CtnNodeList(CtnNode a, CtnNode b, CtnNode c) { super(a, b, c); } protected CtnNodeList(CtnNode a, CtnNode b) { super(a, b); } protected CtnNodeList(CtnNode... children) { super(children); } protected CtnNodeList(CtnNode child) { super(child); } // ========================================================================= @Override public String getNodeName() { return "list"; } } CtnNodeWithObjProp.java000066400000000000000000000050531315622671000416740ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/main/java/de/fau/cs/osr/ptk/common/test/nodes/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common.test.nodes; import de.fau.cs.osr.ptk.common.ast.AstLeafNodeImpl; import de.fau.cs.osr.ptk.common.ast.AstNodePropertyIterator; public final class CtnNodeWithObjProp extends AstLeafNodeImpl implements CtnNode { private static final long serialVersionUID = 1L; // ===================================================================== protected CtnNodeWithObjProp() { } protected CtnNodeWithObjProp(Object prop) { setProp(prop); } // ===================================================================== @Override public int getNodeType() { return NT_TEST_NODE_WITH_OBJ_PROP; } @Override public String getNodeName() { return "nwop"; } // ===================================================================== // Properties private Object prop; public final Object getProp() { return this.prop; } public final void setProp(Object prop) { this.prop = prop; } @Override public final int getPropertyCount() { return 1; } @Override public final AstNodePropertyIterator propertyIterator() { return new AstNodePropertyIterator() { @Override protected int getPropertyCount() { return 1; } @Override protected String getName(int index) { switch (index) { case 0: return "prop"; default: throw new IndexOutOfBoundsException(); } } @Override protected Object getValue(int index) { switch (index) { case 0: return CtnNodeWithObjProp.this.getProp(); default: throw new IndexOutOfBoundsException(); } } @Override protected Object setValue(int index, Object value) { switch (index) { case 0: { Object old = CtnNodeWithObjProp.this.getProp(); CtnNodeWithObjProp.this.setProp(value); return old; } default: throw new IndexOutOfBoundsException(); } } }; } } CtnNodeWithPropAndContent.java000066400000000000000000000056611315622671000432240ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/main/java/de/fau/cs/osr/ptk/common/test/nodes/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common.test.nodes; import de.fau.cs.osr.ptk.common.ast.AstNodePropertyIterator; import de.fau.cs.osr.ptk.common.ast.AstStringNodeImpl; import de.fau.cs.osr.ptk.common.ast.Uninitialized; public final class CtnNodeWithPropAndContent extends AstStringNodeImpl implements CtnNode { private static final long serialVersionUID = 1L; // ===================================================================== protected CtnNodeWithPropAndContent() { super(Uninitialized.X); } protected CtnNodeWithPropAndContent(Object prop, String content) { super(content); setProp(prop); } // ===================================================================== @Override public int getNodeType() { return NT_TEST_NODE_WITH_PROP_AND_CONTENT; } @Override public String getNodeName() { return "nwpac"; } // ===================================================================== // Properties private Object prop; public final Object getProp() { return this.prop; } public final void setProp(Object prop) { this.prop = prop; } @Override public final int getPropertyCount() { return 1 + getSuperPropertyCount(); } public final int getSuperPropertyCount() { return super.getPropertyCount(); } @Override public final AstNodePropertyIterator propertyIterator() { return new StringContentNodePropertyIterator() { @Override protected int getPropertyCount() { return CtnNodeWithPropAndContent.this.getPropertyCount(); } @Override protected String getName(int index) { switch (index - getSuperPropertyCount()) { case 0: return "prop"; default: return super.getName(index); } } @Override protected Object getValue(int index) { switch (index - getSuperPropertyCount()) { case 0: return CtnNodeWithPropAndContent.this.getProp(); default: return super.getValue(index); } } @Override protected Object setValue(int index, Object value) { switch (index - getSuperPropertyCount()) { case 0: { Object old = CtnNodeWithPropAndContent.this.getProp(); CtnNodeWithPropAndContent.this.setProp(value); return old; } default: return super.setValue(index, value); } } }; } } CtnSection.java000066400000000000000000000070341315622671000402640ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/main/java/de/fau/cs/osr/ptk/common/test/nodes/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common.test.nodes; import de.fau.cs.osr.ptk.common.ast.AstAbstractInnerNode.AstInnerNode2; import de.fau.cs.osr.ptk.common.ast.AstNodePropertyIterator; import de.fau.cs.osr.ptk.common.ast.Uninitialized; public final class CtnSection extends AstInnerNode2 implements CtnNode { private static final long serialVersionUID = 1L; // ===================================================================== protected CtnSection() { super(Uninitialized.X); } protected CtnSection(int level, CtnTitle title, CtnBody body) { super(title, body); setLevel(level); } // ===================================================================== @Override public int getNodeType() { return NT_TEST_SECTION; } @Override public String getNodeName() { return "section"; } // ===================================================================== // Properties private int level; public final int getLevel() { return this.level; } public final void setLevel(int level) { this.level = level; } @Override public final int getPropertyCount() { return 1 + getSuperPropertyCount(); } public final int getSuperPropertyCount() { return super.getPropertyCount(); } @Override public final AstNodePropertyIterator propertyIterator() { return new AstNodePropertyIterator() { @Override protected int getPropertyCount() { return 1; } @Override protected String getName(int index) { switch (index) { case 0: return "level"; default: throw new IndexOutOfBoundsException(); } } @Override protected Object getValue(int index) { switch (index) { case 0: return CtnSection.this.getLevel(); default: throw new IndexOutOfBoundsException(); } } @Override protected Object setValue(int index, Object value) { switch (index) { case 0: { int old = CtnSection.this.getLevel(); CtnSection.this.setLevel((Integer) value); return old; } default: throw new IndexOutOfBoundsException(); } } }; } // ===================================================================== // Children public final void setTitle(CtnTitle title) { set(0, title); } public final CtnTitle getTitle() { return (CtnTitle) get(0); } public final void removeTitle() { setTitle(CtnTitle.NO_TITLE); } public final boolean hasTitle() { return getTitle() != CtnTitle.NO_TITLE; } public final void setBody(CtnBody body) { set(1, body); } public final CtnBody getBody() { return (CtnBody) get(1); } public final void removeBody() { setBody(CtnBody.NO_BODY); } public final boolean hasBody() { return getBody() != CtnBody.NO_BODY; } private static final String[] CHILD_NAMES = new String[] { "title", "body" }; public final String[] getChildNames() { return CHILD_NAMES; } } CtnText.java000066400000000000000000000023731315622671000376050ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/main/java/de/fau/cs/osr/ptk/common/test/nodes/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common.test.nodes; import de.fau.cs.osr.ptk.common.ast.AstText; import de.fau.cs.osr.ptk.common.ast.Uninitialized; public final class CtnText extends AstText implements CtnNode { private static final long serialVersionUID = 1L; // ========================================================================= protected CtnText() { super(Uninitialized.X); } protected CtnText(String text) { super(text); } // ========================================================================= @Override public String getNodeName() { return "text"; } } CtnTitle.java000066400000000000000000000051461315622671000377430ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/main/java/de/fau/cs/osr/ptk/common/test/nodes/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common.test.nodes; import de.fau.cs.osr.ptk.common.ast.AstNodeList; import de.fau.cs.osr.ptk.common.ast.AstNodeListImpl; public interface CtnTitle extends CtnNode, AstNodeList { public static final CtnTitle.CtnNoTitle NO_TITLE = new CtnNoTitle(); public static final CtnTitle.CtnEmptyTitle EMPTY = new CtnEmptyTitle(); // ========================================================================= public static final class CtnNoTitle extends CtnEmptyImmutableNode implements CtnTitle { private static final long serialVersionUID = -1064749733891892633L; protected CtnNoTitle() { } @Override public int getNodeType() { return NT_TEST_TITLE; } @Override public String getNodeName() { return "title"; } @Override public void exchange(AstNodeList other) { throw new UnsupportedOperationException(genMsg()); } } // ========================================================================= public static final class CtnEmptyTitle extends CtnEmptyImmutableNode implements CtnTitle { private static final long serialVersionUID = -1064749733891892633L; protected CtnEmptyTitle() { } @Override public int getNodeType() { return NT_TEST_TITLE; } @Override public String getNodeName() { return "title"; } @Override public void exchange(AstNodeList other) { throw new UnsupportedOperationException(genMsg()); } } // ========================================================================= public static final class CtnTitleImpl extends AstNodeListImpl implements CtnTitle { private static final long serialVersionUID = 1L; protected CtnTitleImpl() { } protected CtnTitleImpl(CtnNode... children) { super(children); } @Override public int getNodeType() { return NT_TEST_TITLE; } @Override public String getNodeName() { return "title"; } } } CtnUrl.java000066400000000000000000000062571315622671000374300ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/main/java/de/fau/cs/osr/ptk/common/test/nodes/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common.test.nodes; import de.fau.cs.osr.ptk.common.ast.AstLeafNodeImpl; import de.fau.cs.osr.ptk.common.ast.AstNodePropertyIterator; public final class CtnUrl extends AstLeafNodeImpl implements CtnNode { private static final long serialVersionUID = 1L; // ========================================================================= protected CtnUrl() { } protected CtnUrl(String protocol, String path) { super(); setProtocol(protocol); setPath(path); } // ========================================================================= @Override public int getNodeType() { return NT_TEST_URL; } @Override public String getNodeName() { return "url"; } // ===================================================================== // Properties private String protocol; public final String getProtocol() { return this.protocol; } public final void setProtocol(String protocol) { if (protocol == null) throw new NullPointerException(); this.protocol = protocol; } private String path; public final String getPath() { return this.path; } public final void setPath(String path) { if (path == null) throw new NullPointerException(); this.path = path; } @Override public final int getPropertyCount() { return 2 + getSuperPropertyCount(); } public final int getSuperPropertyCount() { return super.getPropertyCount(); } @Override public final AstNodePropertyIterator propertyIterator() { return new AstNodePropertyIterator() { @Override protected int getPropertyCount() { return CtnUrl.this.getPropertyCount(); } @Override protected String getName(int index) { switch (index) { case 0: return "protocol"; case 1: return "path"; default: throw new IndexOutOfBoundsException(); } } @Override protected Object getValue(int index) { switch (index) { case 0: return CtnUrl.this.getProtocol(); case 1: return CtnUrl.this.getPath(); default: throw new IndexOutOfBoundsException(); } } @Override protected Object setValue(int index, Object value) { switch (index) { case 0: { String old = CtnUrl.this.getProtocol(); CtnUrl.this.setProtocol((String) value); return old; } case 1: { String old = CtnUrl.this.getPath(); CtnUrl.this.setPath((String) value); return old; } default: throw new IndexOutOfBoundsException(); } } }; } } osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/test/000077500000000000000000000000001315622671000260055ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/test/java/000077500000000000000000000000001315622671000267265ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/test/java/de/000077500000000000000000000000001315622671000273165ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/test/java/de/fau/000077500000000000000000000000001315622671000300715ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/test/java/de/fau/cs/000077500000000000000000000000001315622671000304765ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/test/java/de/fau/cs/osr/000077500000000000000000000000001315622671000313015ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/test/java/de/fau/cs/osr/ptk/000077500000000000000000000000001315622671000320775ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/test/java/de/fau/cs/osr/ptk/common/000077500000000000000000000000001315622671000333675ustar00rootroot00000000000000ast/000077500000000000000000000000001315622671000340775ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/test/java/de/fau/cs/osr/ptk/commonNativeAstLocationTest.java000066400000000000000000000020751315622671000411750ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/test/java/de/fau/cs/osr/ptk/common/ast/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common.ast; import static org.junit.Assert.assertEquals; import org.junit.Test; public class NativeAstLocationTest { @Test public void testStringSerializationOfLocation() throws Exception { AstLocation loc = new AstLocation("tes\\t:", 42, 43); String expected = "tes%5Ct%3A:42:43"; assertEquals(expected, loc.toString()); assertEquals(loc, AstLocation.valueOf(expected)); } } RtDataTest.java000066400000000000000000000070251315622671000367650ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/test/java/de/fau/cs/osr/ptk/common/ast/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common.ast; import static de.fau.cs.osr.ptk.common.ast.RtData.SEP; import static de.fau.cs.osr.ptk.common.test.nodes.CtnBuilder.ctnSection; import static de.fau.cs.osr.ptk.common.test.nodes.CtnBuilder.ctnText; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import de.fau.cs.osr.ptk.common.test.nodes.CtnSection; import de.fau.cs.osr.ptk.common.test.nodes.CtnText; public class RtDataTest { @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void testRtdObjectHasRightSize() throws Exception { assertEquals(2, new RtData(2).size()); CtnText text = ctnText(); assertEquals(text.size() + 1, new RtData(text).size()); CtnSection section = ctnSection().build(); assertEquals(section.size() + 1, new RtData(section).size()); } @Test public void testNewRtdObjectIsMadeUpOfEmptyFields() throws Exception { RtData rtd = new RtData(2); for (int i = 0; i < rtd.size(); ++i) { assertNotNull(rtd.getField(i)); assertEquals(0, rtd.getField(i).length); } } @Test public void testComplexCtorsHaveRightSize() throws Exception { CtnSection section = ctnSection().build(); RtData rtd = new RtData(section, "1"); assertEquals(3, rtd.size()); } @Test public void testNullInCtorDoesNotMeanNullInRtd() throws Exception { CtnSection section = ctnSection().build(); RtData rtd = new RtData(section, "1", SEP, null, SEP, "3"); for (int i = 0; i < rtd.size(); ++i) assertNotNull(rtd.getField(i)); } @Test public void testRtdIsNicelyFormatted() throws Exception { assertEquals( "RTD[ \"1\" \"2.1, 2.2\" \"\" ]", new RtData(3, "1", SEP, "2.1", ", ", "2.2", SEP, null).toString()); } @Test public void testTooManySepRaiseException() throws Exception { thrown.expect(IndexOutOfBoundsException.class); thrown.expectMessage("too many"); new RtData(2, SEP, SEP, SEP); } @Test public void testEmptyStringResultsInEmptyField() throws Exception { assertEquals(0, new RtData(1, "").getField(0).length); } @Test public void testJoiningTextWorks() throws Exception { Object[] field0 = new RtData(1, "1", "2", "3").getField(0); assertEquals(1, field0.length); assertEquals("123", field0[0]); } @Test public void testPrependToEmptyRtData() throws Exception { RtData rtd = new RtData(2); rtd.prepend("1"); assertEquals("RTD[ \"1\" \"\" ]", rtd.toString()); } @Test public void testPrependToRtData() throws Exception { RtData rtd = new RtData(2, "1"); rtd.prepend("2"); assertEquals("RTD[ \"21\" \"\" ]", rtd.toString()); } @Test public void testPrependToRtDataWithObjects() throws Exception { RtData rtd = new RtData(2, ctnText("")); rtd.prepend("1"); assertEquals("RTD[ \"1\" \"\" ]", rtd.toString()); } } test/000077500000000000000000000000001315622671000342675ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/test/java/de/fau/cs/osr/ptk/commonnodes/000077500000000000000000000000001315622671000353775ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/test/java/de/fau/cs/osr/ptk/common/testNodeListTest.java000066400000000000000000000315611315622671000406310ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/test/java/de/fau/cs/osr/ptk/common/test/nodes/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common.test.nodes; import static de.fau.cs.osr.ptk.common.test.nodes.CtnBuilder.ctnId; import static de.fau.cs.osr.ptk.common.test.nodes.CtnBuilder.ctnList; import static de.fau.cs.osr.ptk.common.test.nodes.CtnBuilder.ctnText; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.ListIterator; import org.junit.Test; import xtc.util.Pair; public class NodeListTest { private static final boolean VERBOSE = false; // ========================================================================= @Test public void testNodeList() { CtnNodeList l = new CtnNodeList(); checkNodeList(0, l); assertTrue(l.isList()); assertTrue(l.isEmpty()); } @Test public void testNodeList_AstNode() { { CtnNodeList l = new CtnNodeList((CtnNode) null); checkNodeList(0, l); } { CtnNodeList l = new CtnNodeList(ctnId(0)); checkNodeList(1, l); assertFalse(l.isEmpty()); } } @Test public void testNodeList_AstNode_PairOfAstNode() { { Pair list = makeSimpleList3(1); CtnNodeList l = new CtnNodeList(ctnId(0), (Pair) list); checkNodeList(4, l); } { Pair list = makeSimpleList3(0); CtnNodeList l = new CtnNodeList(null, (Pair) list); checkNodeList(3, l); } { testForException(new Runnable() { @Override public void run() { new CtnNodeList(ctnId(0), (Pair) null); } }, NullPointerException.class); } } @Test public void testNodeList_AstNode_AstNode() { { CtnNodeList l = new CtnNodeList(null, (CtnNode) null); checkNodeList(0, l); } { CtnNodeList l = new CtnNodeList( new CtnNodeList(makeSimpleList3(0)), new CtnNodeList(makeNestedList5(3))); checkNodeList(8, l); } } @Test public void testNodeList_PairOfAstNode() { { Pair list = makeSimpleList3(0); CtnNodeList l = new CtnNodeList((Pair) list); checkNodeList(3, l); } { testForException(new Runnable() { @Override public void run() { new CtnNodeList((Pair) null); } }, NullPointerException.class); } } // ========================================================================= @Test public void testSet() { { CtnNodeList l = new CtnNodeList(makeSimpleList3(3)); l.set(2, ctnId(2)); l.set(0, ctnId(0)); l.set(1, ctnId(1)); checkNodeList(3, l); } { testForException(new Runnable() { @Override public void run() { new CtnNodeList(makeSimpleList3(0)).set(0, new CtnNodeList()); } }, IllegalArgumentException.class); } { testForException(new Runnable() { @Override public void run() { new CtnNodeList(makeSimpleList3(0)).set(0, null); } }, NullPointerException.class); } } @Test public void testLastIndexOf() { { CtnNodeList l = new CtnNodeList( new CtnNodeList(makeSimpleList3(3)), makeNestedList5(10)); assertEquals(l.lastIndexOf(null), -1); assertEquals(l.lastIndexOf(ctnId(7)), -1); assertEquals(l.lastIndexOf(ctnId(5)), 2); assertEquals(l.lastIndexOf(ctnId(3)), 0); assertEquals(l.lastIndexOf(ctnId(10)), 3); assertEquals(l.lastIndexOf(ctnId(14)), 7); } } @Test public void testAppend() { { CtnNodeList l = new CtnNodeList( new CtnNodeList(makeSimpleList3(0)), makeNestedList5(3)); l.add(null); l.add(ctnId(8)); l.add(null); checkNodeList(9, l); } } @SuppressWarnings("unchecked") @Test public void testAppendAll() { { CtnNodeList l = new CtnNodeList( new CtnNodeList(makeSimpleList3(0)), makeNestedList5(3)); l.addAll(Pair.EMPTY); checkNodeList(8, l); } { CtnNodeList l = new CtnNodeList( new CtnNodeList(makeSimpleList3(0)), makeNestedList5(3)); Pair l2 = makeSimpleList3(7); l2.set(0, null); l.addAll(l2); checkNodeList(10, l); } { CtnNodeList l = new CtnNodeList( new CtnNodeList(makeSimpleList3(0)), makeNestedList5(3)); Pair l2 = makeSimpleList3(7); l2.set(0, null); l2.set(1, null); l2.set(2, null); l.addAll(l2); checkNodeList(8, l); } { CtnNodeList l = new CtnNodeList( new CtnNodeList(makeSimpleList3(0)), makeNestedList5(3)); Pair l2 = makeSimpleList3(0); l2.set(0, null); l2.set(1, null); l2.set(2, new CtnNodeList(makeNestedList5(8))); l.addAll(l2); checkNodeList(13, l); } { CtnNodeList l = new CtnNodeList( new CtnNodeList(makeSimpleList3(0)), makeNestedList5(3)); Pair l2 = makeSimpleList3(8); l2.set(2, null); l.addAll(l2); l.set(9, ctnId(9)); checkNodeList(10, l); } { CtnNodeList l = new CtnNodeList( new CtnNodeList(makeSimpleList3(0)), makeNestedList5(3)); Pair l2 = makeSimpleList3(7); l2.set(2, null); l2.set(0, null); l.addAll(l2); checkNodeList(9, l); } } @Test public void testPrepend() { { CtnNodeList l = new CtnNodeList(makeSimpleList3(0)); prepend(l, null); checkNodeList(3, l); } { CtnNodeList l = new CtnNodeList(makeSimpleList3(1)); prepend(l, ctnId(0)); checkNodeList(4, l); } { CtnNodeList l = new CtnNodeList(makeNestedList5(5)); prepend(l, new CtnNodeList(makeNestedList5(0))); checkNodeList(10, l); } } private void prepend(CtnNode n, CtnNode l) { n.add(0, l); } @Test public void testClear() { { CtnNodeList l = new CtnNodeList( new CtnNodeList(makeSimpleList3(0)), makeNestedList5(3)); l.clear(); checkNodeList(0, l); } } @Test public void testSetText() throws Exception { CtnNodeList l = ctnList(ctnText("Hallo")); l.set(0, ctnText("Welt")); assertEquals(1, l.size()); assertEquals("Welt", ((CtnText) l.get(0)).getContent()); } @Test public void testSetEmptyText() throws Exception { CtnNodeList l = ctnList(ctnText("Hallo")); l.set(0, ctnText("")); assertEquals(0, l.size()); } @Test public void testSetTextAfterExistingTextNode() throws Exception { CtnText t0 = ctnText("Hallo"); CtnNodeList l = ctnList(t0, ctnId(0)); CtnText t1 = ctnText(" Welt"); l.set(1, t1); assertEquals(1, l.size()); assertEquals("Hallo Welt", ((CtnText) l.get(0)).getContent()); assertFalse(l.get(0) == t0); assertFalse(l.get(0) == t1); } @Test public void testSetTextInFrontOfExistingTextNode() throws Exception { CtnNodeList l = ctnList(ctnId(0), ctnText("Welt")); l.set(0, ctnText("Hallo ")); assertEquals(2, l.size()); assertEquals("Hallo ", ((CtnText) l.get(0)).getContent()); assertEquals("Welt", ((CtnText) l.get(1)).getContent()); } @Test public void testCtorWithTwoAdjacentTextNodes() throws Exception { CtnText t0 = ctnText("Hallo"); CtnText t1 = ctnText(" Welt"); CtnNodeList l = ctnList(t0, t1); assertEquals(1, l.size()); assertEquals("Hallo Welt", ((CtnText) l.get(0)).getContent()); assertFalse(l.get(0) == t0); assertFalse(l.get(0) == t1); } @Test public void testAddEmptyText() throws Exception { CtnNodeList l = ctnList(ctnText("Hallo")); assertFalse(l.add(ctnText(""))); assertEquals(1, l.size()); assertEquals("Hallo", ((CtnText) l.get(0)).getContent()); } @Test public void testAddTextAfterExistingText() throws Exception { CtnText t0 = ctnText("Hallo"); CtnNodeList l = ctnList(t0); CtnText t1 = ctnText(" Welt"); l.add(t1); assertEquals(1, l.size()); assertEquals("Hallo Welt", ((CtnText) l.get(0)).getContent()); assertFalse(l.get(0) == t0); assertFalse(l.get(0) == t1); } @Test public void testAddTextBeforeExistingText() throws Exception { CtnNodeList l = ctnList(ctnText("Welt")); l.add(0, ctnText("Hallo ")); assertEquals(2, l.size()); assertEquals("Hallo ", ((CtnText) l.get(0)).getContent()); assertEquals("Welt", ((CtnText) l.get(1)).getContent()); } @Test public void testAddTextWithIterator() throws Exception { CtnNodeList l = ctnList(); ListIterator i = l.listIterator(); i.add(ctnText("Hallo")); assertEquals(1, l.size()); assertEquals("Hallo", ((CtnText) l.get(0)).getContent()); } @Test public void testAddTextAfterTextWithIterator() throws Exception { CtnNodeList l = ctnList(ctnText("Hallo ")); ListIterator i = l.listIterator(); assertEquals("Hallo ", ((CtnText) i.next()).getContent()); assertFalse(i.hasNext()); i.add(ctnText("Welt")); assertFalse(i.hasNext()); assertTrue(i.hasPrevious()); assertEquals("Hallo Welt", ((CtnText) i.previous()).getContent()); assertEquals(1, l.size()); assertEquals("Hallo Welt", ((CtnText) l.get(0)).getContent()); } @Test public void testAddThreeTextNodesWithIterator() throws Exception { CtnNodeList l = ctnList(); ListIterator i = l.listIterator(); i.add(ctnText("Hallo")); i.add(ctnText(" Welt")); i.add(ctnText("!")); assertEquals(1, l.size()); assertEquals("Hallo Welt!", ((CtnText) l.get(0)).getContent()); } @Test public void testAddTextInFrontOfAnotherTextNodeWithIterator() throws Exception { CtnNodeList l = ctnList(ctnText("Welt")); ListIterator i = l.listIterator(); i.add(ctnText("Hallo ")); assertEquals(2, l.size()); assertEquals("Hallo ", ((CtnText) l.get(0)).getContent()); assertEquals("Welt", ((CtnText) l.get(1)).getContent()); } @Test public void testAddEmptyTextWithIterator() throws Exception { CtnNodeList l = ctnList(ctnText("Welt")); ListIterator i = l.listIterator(); i.add(ctnText("")); assertEquals(1, l.size()); assertEquals("Welt", ((CtnText) l.get(0)).getContent()); } @Test public void testSetEmptyTextWithIterator() throws Exception { CtnIdNode _0 = ctnId(0); CtnIdNode _2 = ctnId(2); CtnNodeList l = ctnList(_0, ctnId(1), _2); ListIterator i = l.listIterator(); i.next(); i.next(); i.set(ctnText("")); assertEquals(_0, l.get(0)); assertEquals(_2, l.get(1)); } @Test public void testSetTextNodeAfterAnotherTextNodeWithIterator() throws Exception { CtnNodeList l = ctnList(ctnText("Hallo "), ctnId(0)); ListIterator i = l.listIterator(); i.next(); i.next(); i.set(ctnText("Welt")); assertEquals(1, l.size()); assertEquals("Hallo Welt", ((CtnText) l.get(0)).getContent()); i.set(ctnText("X")); assertEquals(1, l.size()); assertEquals("X", ((CtnText) l.get(0)).getContent()); } @Test public void testSetTextNodeInFrontOfAnotherTextNodeWithIterator() throws Exception { CtnText t1 = ctnText("Welt"); CtnNodeList l = ctnList(ctnId(0), t1); ListIterator i = l.listIterator(); i.next(); i.set(ctnText("Hallo ")); assertEquals(2, l.size()); assertEquals("Hallo ", ((CtnText) l.get(0)).getContent()); assertEquals("Welt", ((CtnText) l.get(1)).getContent()); assertEquals(t1, i.next()); assertFalse(i.hasNext()); assertTrue(i.hasPrevious()); } @Test public void testSetTextNodeAfterANonTextNodeWithIterator() throws Exception { CtnIdNode _0 = ctnId(0); CtnNodeList l = ctnList(_0, ctnId(1)); ListIterator i = l.listIterator(); i.next(); i.next(); i.set(ctnText("Welt")); assertEquals(2, l.size()); assertEquals(_0, l.get(0)); assertEquals("Welt", ((CtnText) l.get(1)).getContent()); i.set(ctnText("X")); assertEquals(2, l.size()); assertEquals(_0, l.get(0)); assertEquals("X", ((CtnText) l.get(1)).getContent()); } // ========================================================================= private void checkNodeList(int size, CtnNodeList l) { assertEquals(size, l.size()); for (int i = 0; i < l.size(); ++i) { int id = ((CtnIdNode) l.get(i)).id; if (VERBOSE) System.out.println(id); assertEquals(id, i); } } private Pair makeSimpleList3(int i) { Pair list = new Pair(ctnId(i++)); list.add(ctnId(i++)); list.add(ctnId(i++)); return list; } private Pair makeNestedList5(int i) { Pair list = new Pair(ctnId(i++)); { Pair nestedList = new Pair(ctnId(i++)); nestedList.add(ctnId(i++)); nestedList.add(ctnId(i++)); list.add(new CtnNodeList(nestedList)); } list.add(ctnId(i++)); return list; } private void testForException( Runnable test, Class clazz) { try { test.run(); assertTrue(false); } catch (Throwable e) { assertTrue(e.getClass().equals(clazz)); } } } osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/test/resources/000077500000000000000000000000001315622671000300175ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/test/resources/complex.xml000066400000000000000000000042101315622671000322050ustar00rootroot00000000000000
<Text content="1st"/>
History
Etymology
Tribes
Empire
Restoration
Geography
Administrative divisions
Climate
Biodiversity
Environment
Politics
Government
Law
osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-common/src/test/resources/simple.xml000066400000000000000000000017151315622671000320360ustar00rootroot00000000000000
<Text content="1st"/>
osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-json-tools/000077500000000000000000000000001315622671000250565ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-json-tools/pom.xml000066400000000000000000000054161315622671000264010ustar00rootroot00000000000000 4.0.0 de.fau.cs.osr.ptk parser-toolkit-parent 3.0.8 ptk-json-tools jar PTK - JSON Tools 2012 This module provides facilities for reading and writing ASTs in JSON format. ../../tooling/ org.apache.commons commons-lang3 com.google.code.gson gson de.fau.cs.osr.utils utils de.fau.cs.osr.ptk ptk-common junit junit test osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-json-tools/src/000077500000000000000000000000001315622671000256455ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-json-tools/src/main/000077500000000000000000000000001315622671000265715ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-json-tools/src/main/java/000077500000000000000000000000001315622671000275125ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-json-tools/src/main/java/de/000077500000000000000000000000001315622671000301025ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-json-tools/src/main/java/de/fau/000077500000000000000000000000001315622671000306555ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-json-tools/src/main/java/de/fau/cs/000077500000000000000000000000001315622671000312625ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-json-tools/src/main/java/de/fau/cs/osr/000077500000000000000000000000001315622671000320655ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-json-tools/src/main/java/de/fau/cs/osr/ptk/000077500000000000000000000000001315622671000326635ustar00rootroot00000000000000common/000077500000000000000000000000001315622671000340745ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-json-tools/src/main/java/de/fau/cs/osr/ptkjson/000077500000000000000000000000001315622671000350455ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-json-tools/src/main/java/de/fau/cs/osr/ptk/commonAstNodeJsonTypeAdapter.java000066400000000000000000000325051315622671000422470ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-json-tools/src/main/java/de/fau/cs/osr/ptk/common/json/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common.json; import java.lang.reflect.Type; import java.util.Map; import java.util.Map.Entry; import com.google.gson.JsonArray; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import com.google.gson.JsonPrimitive; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; import de.fau.cs.osr.ptk.common.ast.AstLocation; import de.fau.cs.osr.ptk.common.ast.AstNode; import de.fau.cs.osr.ptk.common.ast.AstNodePropertyIterator; import de.fau.cs.osr.ptk.common.ast.AstStringNode; import de.fau.cs.osr.ptk.common.serialization.AstNodeConverterBase; import de.fau.cs.osr.ptk.common.serialization.SyntaxErrorException; public class AstNodeJsonTypeAdapter> extends AstNodeConverterBase implements JsonSerializer, JsonDeserializer { static final String SPECIAL_FIELD_LIST = "!list"; static final String SPECIAL_FIELD_TYPE = "!type"; static final String SPECIAL_FIELD_OBJ = "!obj"; static final String SPECIAL_FIELD_LOCATION = "!location"; // ========================================================================= public AstNodeJsonTypeAdapter(Class nodeType) { super(nodeType); } public static > AstNodeJsonTypeAdapter forNodeType( Class nodeType) { return new AstNodeJsonTypeAdapter(nodeType); } // ========================================================================= @Override public JsonElement serialize( T src, Type typeOfSrc, JsonSerializationContext context) { return marshalNode(src, true, context); } @Override public T deserialize( JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { return unmarshalNode(json, (Class) typeOfT, context); } // ========================================================================= private JsonElement marshalNode( T n, boolean typeInfoRequired, JsonSerializationContext context) { Class nodeType = n.getClass(); boolean isStringNode = isStringNode(nodeType) && !n.hasAttributes() && !n.hasLocation(); if (isStringNode) // we can only invoke this function for string nodes! isStringNode &= !hasStringNodeVisibleProperties(n); if (!isStringNode) { JsonObject gsonNode = new JsonObject(); if (typeInfoRequired) storeType(nodeType, gsonNode); storeLocation(n, gsonNode); storeAttributes(n, gsonNode, context); storeProperties(n, isStringNode, gsonNode, context); if (n.isList()) { JsonArray array = new JsonArray(); for (T c : n) { if (!isSuppressed(c)) array.add(marshalNode(c, true, context)); } gsonNode.add(SPECIAL_FIELD_LIST, array); } else { String[] childNum = n.getChildNames(); for (int i = 0; i < childNum.length; ++i) storeNamedChild(n, i, gsonNode, context); } return gsonNode; } else { return new JsonPrimitive(((AstStringNode) n).getContent()); } } private T unmarshalNode( JsonElement json, Class nodeType, JsonDeserializationContext context) { if (json.isJsonPrimitive()) { if (nodeType != null && !isStringNode(nodeType)) throw new SyntaxErrorException("Got JSON primitive but was not expecting String node"); if (nodeType == null) nodeType = getStringNodeType(); T n = instantiateNode(nodeType); ((AstStringNode) n).setContent(json.getAsString()); initializeStringNodeProperties(n); return n; } else if (json.isJsonObject()) { JsonObject jo = json.getAsJsonObject(); nodeType = getExplicitType(jo, nodeType); if (nodeType == null) throw new SyntaxErrorException("Missing node type!"); T n = instantiateNode(nodeType); String[] childNames = n.getChildNames(); boolean[] initProperties = new boolean[n.getPropertyCount()]; boolean[] initChildren = new boolean[childNames.length]; for (Entry e : jo.entrySet()) { String key = e.getKey(); JsonElement value = e.getValue(); switch (key.charAt(0)) { case '!': if (key.equals(SPECIAL_FIELD_LIST)) { for (JsonElement c : value.getAsJsonArray()) n.add(unmarshalNode(c, null, context)); } else if (key.equals(SPECIAL_FIELD_LOCATION)) { String loc = value.getAsString(); n.setNativeLocation(AstLocation.valueOf(loc)); } else if (key.equals(SPECIAL_FIELD_TYPE)) { // We've handled this already... } else { throw new SyntaxErrorException("Unexpected special key in JSON " + "object when tryingn to deserialize AST node: " + key); } break; case '@': restoreAttribute(n, key, value, context); break; case '$': restoreProperty(n, key, value, context, initProperties); break; default: restoreNamedChild(n, key, value, context, childNames, initChildren); break; } } AstNodePropertyIterator propIter = n.propertyIterator(); for (boolean b : initProperties) { propIter.next(); if (!b) setDefaultProperty(n, propIter); } for (int i = 0; i < childNames.length; ++i) { if (!initChildren[i]) setDefaultChild(n, i, childNames[i]); } return n; } else { throw new SyntaxErrorException("Expected node or text but got JSON array or null"); } } // ========================================================================= private void storeLocation(AstNode n, JsonObject gsonNode) { if (!isLocationSuppressed()) { AstLocation loc = n.getNativeLocation(); if (loc != null) gsonNode.add(SPECIAL_FIELD_LOCATION, new JsonPrimitive(loc.toString())); } } // ========================================================================= private void storeAttributes( AstNode n, JsonObject gsonNode, JsonSerializationContext context) { if (isAttributesSuppressed()) return; Map attrs = n.getAttributes(); if (!attrs.isEmpty()) { for (Entry e : attrs.entrySet()) { String name = e.getKey(); if (!isAttributeSuppressed(name)) writeAttribute(name, e.getValue(), gsonNode, context); } } } private void writeAttribute( String name, Object value, JsonObject gsonNode, JsonSerializationContext context) { JsonObject jsonValue = null; if (value != null) { jsonValue = new JsonObject(); storeType(value.getClass(), jsonValue); jsonValue.add("value", context.serialize(value)); } gsonNode.add("@" + name, jsonValue); } private void restoreAttribute( T n, String key, JsonElement gsonValue, JsonDeserializationContext context) { String name = key.substring(1); Object value = null; if (!gsonValue.isJsonNull()) { JsonObject jo = gsonValue.getAsJsonObject(); Class valueType = null; valueType = getExplicitType(jo, valueType); if (valueType == null) throw new SyntaxErrorException("Missing attribute type field!"); JsonElement valueField = jo.get("value"); if (valueField == null) throw new SyntaxErrorException("Missing attribute value field!"); value = context. deserialize(valueField, valueType); } n.setAttribute(name, value); } // ========================================================================= private boolean hasStringNodeVisibleProperties(AstNode n) { for (AstNodePropertyIterator i = n.propertyIterator(); i.next();) { Object value = i.getValue(); if (value == null) continue; String name = i.getName(); if (isPropertySuppressed(name)) continue; if ("content".equals(name)) continue; return true; } return false; } private void storeProperties( AstNode n, boolean suppressContent, JsonObject gsonNode, JsonSerializationContext context) { if (n.getPropertyCount() > 0) { for (AstNodePropertyIterator i = n.propertyIterator(); i.next();) { Object value = i.getValue(); if (value == null) continue; String name = i.getName(); if (isPropertySuppressed(name)) continue; writeProperty(n, name, value, gsonNode, context); } } } @SuppressWarnings("unchecked") private void writeProperty( AstNode parentNode, String name, Object value, JsonObject gsonNode, JsonSerializationContext context) { if (isSuppressed(value)) return; String fieldName = "$" + name; JsonElement gsonValue = null; if (value != null) { // We always have to add the type information to the property name. // Otherwise we would have to check if a serialized object is an // AST node and if so, we would have to peek into the serialized // node to learn the type of the node... Class valueType = value.getClass(); if (isTypeInfoRequired(parentNode, name, valueType)) fieldName += ":" + getTypeAlias(valueType); gsonValue = getNodeType().isAssignableFrom(valueType) ? marshalNode((T) value, isAlwaysStoreType(), context) : context.serialize(value); } gsonNode.add(fieldName, gsonValue); } private void restoreProperty( T n, String key, JsonElement gsonValue, JsonDeserializationContext context, boolean[] initProperties) { String name = key.substring(1); if (!gsonValue.isJsonNull()) { Class propType; int colon = key.indexOf(':'); if (colon != -1) { name = key.substring(1, colon); propType = getClassForAlias(key.substring(colon + 1)); } else { propType = getGetterType(n, name); } AstNodePropertyIterator propIter = n.propertyIterator(); for (int i = 0; propIter.next(); ++i) { if (propIter.getName().equals(name)) { Object value = context.deserialize(gsonValue, propType); propIter.setValue(value); initProperties[i] = true; break; } } } else { AstNodePropertyIterator propIter = n.propertyIterator(); for (int i = 0; propIter.next(); ++i) { if (propIter.getName().equals(name)) { setDefaultProperty(n, propIter); initProperties[i] = true; break; } } } } private void initializeStringNodeProperties(T n) { if (n.getPropertyCount() > 0) { for (AstNodePropertyIterator i = n.propertyIterator(); i.next();) { if (!i.getName().equals("content")) // If it's a string node the content property will be set // from a child, not a property! setDefaultProperty(n, i); } } } // ========================================================================= private void storeNamedChild( T n, int i, JsonObject gsonParent, JsonSerializationContext context) { T child = n.get(i); if (isSuppressed(child)) return; String name = n.getChildNames()[i]; String fieldName = name; boolean typeInfoRequired = isTypeInfoRequired(n, name, child.getClass()); JsonElement gsonNode = marshalNode(child, typeInfoRequired, context); gsonParent.add(fieldName, gsonNode); } private void restoreNamedChild( T n, String key, JsonElement gsonValue, JsonDeserializationContext context, String[] childNames, boolean[] initChildren) { for (int i = 0; i < childNames.length; ++i) { if (childNames[i].equals(key)) { Class childType = getGetterType(n, key); T child = unmarshalNode(gsonValue, childType, context); n.set(i, child); initChildren[i] = true; return; } } throw new SyntaxErrorException("Unexpected child element: '" + key + "' when unmarshalling node of type '" + n.getClass().getName() + "'"); } // ========================================================================= private void storeType(Class type, JsonObject gsonNode) { String alias = getTypeAlias(type); storeType(alias, gsonNode); } protected static void storeType(String alias, JsonObject gsonNode) { gsonNode.add(SPECIAL_FIELD_TYPE, new JsonPrimitive(alias)); } protected static void storeObject(JsonElement obj, JsonObject gsonNode) { gsonNode.add(SPECIAL_FIELD_OBJ, obj); } protected static String readType(JsonObject gsonNode) { JsonElement type = gsonNode.get(SPECIAL_FIELD_TYPE); if (type == null) throw new SyntaxErrorException("Expected key: " + SPECIAL_FIELD_TYPE); return type.getAsString(); } protected static JsonElement readObject(JsonObject gsonNode) { JsonElement obj = gsonNode.get(SPECIAL_FIELD_OBJ); if (obj == null) throw new SyntaxErrorException("Expected key: " + SPECIAL_FIELD_OBJ); return obj; } private Class getExplicitType(JsonObject jo, Class valueType) { JsonElement explicitType = jo.get(SPECIAL_FIELD_TYPE); if (explicitType != null) valueType = getClassForAlias(explicitType.getAsString()); return valueType; } } AstRtDataJsonTypeAdapter.java000066400000000000000000000104341315622671000425360ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-json-tools/src/main/java/de/fau/cs/osr/ptk/common/json/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common.json; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Type; import java.util.ArrayList; import com.google.gson.JsonArray; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import com.google.gson.JsonPrimitive; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; import de.fau.cs.osr.ptk.common.ast.RtData; import de.fau.cs.osr.ptk.common.serialization.AstConverterBase; import de.fau.cs.osr.ptk.common.serialization.IncompatibleAstNodeClassException; import de.fau.cs.osr.ptk.common.serialization.SyntaxErrorException; public class AstRtDataJsonTypeAdapter extends AstConverterBase implements JsonSerializer, JsonDeserializer { private final Constructor rtdCtor; // ========================================================================= public AstRtDataJsonTypeAdapter(Class rtDataType) { try { rtdCtor = rtDataType.getConstructor(int.class, Object[].class); } catch (NoSuchMethodException e) { throw new IncompatibleAstNodeClassException("Class '" + rtDataType.getName() + "' is malformed", e); } catch (SecurityException e) { throw new IncompatibleAstNodeClassException("Class '" + rtDataType.getName() + "' is malformed", e); } } // ========================================================================= @Override public JsonElement serialize( RtData src, Type typeOfSrc, JsonSerializationContext context) { JsonArray fields = new JsonArray(); int last = src.size() - 1; for (int i = 0; i <= last; ++i) { Object[] srcField = src.getField(i); if (srcField.length > 0) { for (Object srcObj : srcField) { JsonElement item = null; if (srcObj instanceof String) { item = new JsonPrimitive((String) srcObj); } else if (srcObj != null) { item = new JsonObject(); AstNodeJsonTypeAdapter.storeType(getTypeAlias(srcObj.getClass()), (JsonObject) item); AstNodeJsonTypeAdapter.storeObject(context.serialize(srcObj), (JsonObject) item); } fields.add(item); } } if (i != last) fields.add(null); } return fields; } @Override public T deserialize( JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { if (!json.isJsonArray()) throw new SyntaxErrorException("RTD deserializer expected array"); JsonArray fields = json.getAsJsonArray(); int size = 1; ArrayList l = new ArrayList(); for (JsonElement e : fields) { if (e.isJsonNull()) { l.add(RtData.SEP); ++size; } else if (e.isJsonPrimitive()) { l.add(e.getAsString()); } else { JsonObject item = e.getAsJsonObject(); Class type = getClassForAlias(AstNodeJsonTypeAdapter.readType(item)); Object obj = context.deserialize(AstNodeJsonTypeAdapter.readObject(item), type); l.add(obj); } } return newRtd(size, l); } private T newRtd(int size, ArrayList l) { try { @SuppressWarnings("unchecked") T tmp = (T) rtdCtor.newInstance(size, l.toArray()); return tmp; } catch (InstantiationException e) { throw new JsonParseException(e); } catch (IllegalAccessException e) { throw new JsonParseException(e); } catch (IllegalArgumentException e) { throw new JsonParseException(e); } catch (InvocationTargetException e) { throw new JsonParseException(e); } } } osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-json-tools/src/test/000077500000000000000000000000001315622671000266245ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-json-tools/src/test/java/000077500000000000000000000000001315622671000275455ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-json-tools/src/test/java/de/000077500000000000000000000000001315622671000301355ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-json-tools/src/test/java/de/fau/000077500000000000000000000000001315622671000307105ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-json-tools/src/test/java/de/fau/cs/000077500000000000000000000000001315622671000313155ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-json-tools/src/test/java/de/fau/cs/osr/000077500000000000000000000000001315622671000321205ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-json-tools/src/test/java/de/fau/cs/osr/ptk/000077500000000000000000000000001315622671000327165ustar00rootroot00000000000000common/000077500000000000000000000000001315622671000341275ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-json-tools/src/test/java/de/fau/cs/osr/ptkjson/000077500000000000000000000000001315622671000351005ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-json-tools/src/test/java/de/fau/cs/osr/ptk/commonArbitraryObj.java000066400000000000000000000035271315622671000403440ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-json-tools/src/test/java/de/fau/cs/osr/ptk/common/json/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common.json; import java.io.Serializable; import java.util.Arrays; final class ArbitraryObj implements Serializable { private static final long serialVersionUID = 1L; public Object nullValue = new Object(); public int intValue = -42; public String strValue = null; public double[] doubleValues = null; // ===================================================================== public void set() { nullValue = null; intValue = 42; strValue = "some string"; doubleValues = new double[] { 3.1415, 2.7182 }; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ArbitraryObj other = (ArbitraryObj) obj; if (!Arrays.equals(doubleValues, other.doubleValues)) return false; if (intValue != other.intValue) return false; if (nullValue == null) { if (other.nullValue != null) return false; } else if (!nullValue.equals(other.nullValue)) return false; if (strValue == null) { if (other.strValue != null) return false; } else if (!strValue.equals(other.strValue)) return false; return true; } } AstNodeJsonConverterTest.java000066400000000000000000000206051315622671000426650ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-json-tools/src/test/java/de/fau/cs/osr/ptk/common/json/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common.json; import static de.fau.cs.osr.ptk.common.test.nodes.CtnBuilder.ctnDoc; import static de.fau.cs.osr.ptk.common.test.nodes.CtnBuilder.ctnObjProp; import static de.fau.cs.osr.ptk.common.test.nodes.CtnBuilder.ctnPropContent; import static de.fau.cs.osr.ptk.common.test.nodes.CtnBuilder.ctnSection; import static de.fau.cs.osr.ptk.common.test.nodes.CtnBuilder.ctnText; import static de.fau.cs.osr.ptk.common.test.nodes.CtnBuilder.ctnUrl; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import de.fau.cs.osr.ptk.common.ast.AstLocation; import de.fau.cs.osr.ptk.common.test.nodes.CtnBody; import de.fau.cs.osr.ptk.common.test.nodes.CtnDocument; import de.fau.cs.osr.ptk.common.test.nodes.CtnNodeWithPropAndContent; import de.fau.cs.osr.ptk.common.test.nodes.CtnSection; import de.fau.cs.osr.ptk.common.test.nodes.CtnText; import de.fau.cs.osr.ptk.common.test.nodes.CtnTitle; import de.fau.cs.osr.ptk.common.test.nodes.CtnUrl; public class AstNodeJsonConverterTest extends AstNodeJsonConverterTestBase { @Before public void before() { super.before(); setupDefaultNodeFactory(); setupDefaultTypeMappings(); } @Test public void testRoundTripWithRoots() throws Exception { CtnDocument doc = ctnDoc(); roundtrip(doc); } @Test public void testSerializationOfIntAttribute() throws Exception { CtnDocument doc = ctnDoc(); doc.setAttribute("int", 5); roundtrip(doc); } @Test public void testSerializationOfStringAttribute() throws Exception { CtnDocument doc = ctnDoc(); doc.setAttribute("str", "Hello World"); roundtrip(doc); } @Test public void testSerializationOfPropertyWithArbitraryObjectAsValue() throws Exception { ArbitraryObj obj = new ArbitraryObj(); obj.set(); CtnDocument doc = ctnDoc(ctnObjProp(obj)); roundtrip(doc); } @Test public void testSerializationOfPropertyWithNodeAsValue() throws Exception { ArbitraryObj obj = new ArbitraryObj(); obj.set(); CtnDocument doc = ctnDoc(ctnObjProp(ctnUrl().build())); roundtrip(doc); } /** * TODO: How can we fix this situation? */ @Test @Ignore public void testSerializationOfObjectArray() throws Exception { CtnDocument doc = ctnDoc(); doc.setAttribute("array", new Object[] { ctnText("Hallo"), ctnUrl().build() }); roundtrip(doc); } @Test public void testNoContentPropertyFoundWhenTextNodeTypeSet() throws Exception { CtnDocument doc = ctnDoc(ctnText("Hallo")); assertFalse(serialize(doc).contains("\"$content\"")); getConverter().setStringNodeType(null); assertTrue(serialize(doc).contains("\"$content\"")); } @Test public void testAttributesOnTextNodeForceContentElement() throws Exception { CtnText text = ctnText("Hallo"); text.setAttribute("ruins", "it"); CtnDocument doc = ctnDoc(text); assertTrue(serialize(doc).contains("\"$content\"")); } @Test public void testInstantiationOfNullReplacementProperty() throws Exception { CtnDocument doc = ctnDoc(ctnUrl().withProtocol("").build()); getConverter().setSuppressEmptyStringProperties(true); assertFalse(serialize(doc).contains("\"$protocol\"")); roundtrip(doc); } @Test public void testNullProperty() throws Exception { CtnDocument doc = ctnDoc(ctnObjProp(null)); assertFalse(serialize(doc).contains("\"$prop")); roundtrip(doc); } @Test public void testSuppressedProperty() throws Exception { CtnDocument doc = ctnDoc(ctnObjProp("Hello World")); getConverter().suppressProperty("prop"); assertFalse(serialize(doc).contains("\"$prop")); } @Test public void testNodeWithContentAndAnotherProperty() throws Exception { // First make sure that the node is properly recognized as string node CtnDocument doc = ctnDoc(ctnObjProp(ctnPropContent(null, "Hello World"))); getConverter().setStringNodeType(CtnNodeWithPropAndContent.class); assertFalse(serialize(doc).contains("\"$content\"")); roundtrip(doc); doc = ctnDoc(ctnObjProp(ctnPropContent(42, "Hello World"))); getConverter().setStringNodeType(CtnNodeWithPropAndContent.class); assertTrue(serialize(doc).contains("\"$content\"")); roundtrip(doc); } @Test public void testNodeWithAtLeastTwoNamedChildren() throws Exception { CtnDocument doc = ctnDoc(ctnSection().build()); String serialized = serialize(doc); assertTrue(serialized.contains("\"title\":")); assertTrue(serialized.contains("\"body\":")); roundtrip(doc); } @Test public void testStoreLocation() throws Exception { CtnDocument doc = astWithLocations(); roundtrip(doc); assertTrue(serialize(doc).contains("\"!location\"")); } @Test public void testSuppressLocation() throws Exception { CtnDocument doc = astWithLocations(); getConverter().setStoreLocation(false); assertFalse(serialize(doc).contains("\"!location\"")); } private CtnDocument astWithLocations() { CtnText text = ctnText("Hello"); text.setNativeLocation(new AstLocation("some file", 42, 43)); CtnUrl url = ctnUrl().build(); url.setNativeLocation(new AstLocation("some file", 44, 45)); CtnDocument doc = ctnDoc(text, url); return doc; } @Test public void testStoreNodesWithAttributes() throws Exception { CtnDocument doc = astWithAttributes(); roundtrip(doc); } @Test public void testSuppressCertainAttributes() throws Exception { CtnDocument doc = astWithAttributes(); getConverter().suppressAttribute("area52"); String xml = serialize(doc); assertTrue(xml.contains("area51")); assertFalse(xml.contains("area52")); } @Test public void testSuppressAllAttributes() throws Exception { CtnDocument doc = astWithAttributes(); getConverter().setStoreAttributes(false); String xml = serialize(doc); assertFalse(xml.contains("area51")); assertFalse(xml.contains("area52")); } private CtnDocument astWithAttributes() { CtnUrl url = ctnUrl().build(); url.setAttribute("area51", "Hello World 1"); url.setAttribute("area52", "Hello World 2"); CtnDocument doc = ctnDoc(url); return doc; } @Test public void testStoreNullAttribute() throws Exception { CtnUrl url = ctnUrl().build(); url.setAttribute("area51", null); CtnDocument doc = ctnDoc(url); roundtrip(doc); } @Test public void testBodyInterfaceNode() throws Exception { CtnSection sec = ctnSection().build(); CtnDocument doc = ctnDoc(sec); assertEquals(CtnBody.CtnBodyImpl.class, sec.getBody().getClass()); assertTrue(sec.hasBody()); assertTrue(serialize(doc).contains("\"body\"")); roundtrip(doc); } @Test public void testNoBodyNode() throws Exception { CtnSection sec = ctnSection().build(); sec.removeBody(); CtnDocument doc = ctnDoc(sec); assertEquals(CtnBody.CtnNoBody.class, sec.getBody().getClass()); assertFalse(sec.hasBody()); roundtrip(doc); String json = serialize(doc); assertFalse(json.contains("\"body\"")); CtnDocument restoredDoc = (CtnDocument) deserialize(json, CtnDocument.class); assertFalse(((CtnSection) restoredDoc.get(0)).hasBody()); } @Test public void testNoTitleNodeToCoverAllPaths() throws Exception { CtnSection sec = ctnSection().build(); sec.removeTitle(); CtnDocument doc = ctnDoc(sec); assertEquals(CtnTitle.CtnNoTitle.class, sec.getTitle().getClass()); assertFalse(sec.hasTitle()); assertTrue(sec.hasBody()); roundtrip(doc); String json = serialize(doc); assertFalse(json.contains("\"title\"")); CtnDocument restoredDoc = (CtnDocument) deserialize(json, CtnDocument.class); assertFalse(((CtnSection) restoredDoc.get(0)).hasTitle()); } @Test public void testStoreComplexArrayAsAttribute() throws Exception { CtnDocument doc = ctnDoc(); doc.setAttribute("DoubleTrouble", new Double[][] { new Double[] { 3.1415, 2 * 3.1415 }, new Double[] { 2.7182, 2 * 2.7182 } }); roundtrip(doc); } } AstNodeJsonConverterTestBase.java000066400000000000000000000114671315622671000434660ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-json-tools/src/test/java/de/fau/cs/osr/ptk/common/json/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common.json; import org.apache.commons.lang3.StringUtils; import org.junit.Before; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import de.fau.cs.osr.ptk.common.ast.AstNode; import de.fau.cs.osr.ptk.common.comparer.AstComparer; import de.fau.cs.osr.ptk.common.serialization.SimpleTypeNameMapper; import de.fau.cs.osr.ptk.common.test.nodes.CtnBody; import de.fau.cs.osr.ptk.common.test.nodes.CtnDocument; import de.fau.cs.osr.ptk.common.test.nodes.CtnFactory; import de.fau.cs.osr.ptk.common.test.nodes.CtnIdNode; import de.fau.cs.osr.ptk.common.test.nodes.CtnNode; import de.fau.cs.osr.ptk.common.test.nodes.CtnNodeList; import de.fau.cs.osr.ptk.common.test.nodes.CtnNodeWithObjProp; import de.fau.cs.osr.ptk.common.test.nodes.CtnNodeWithPropAndContent; import de.fau.cs.osr.ptk.common.test.nodes.CtnSection; import de.fau.cs.osr.ptk.common.test.nodes.CtnText; import de.fau.cs.osr.ptk.common.test.nodes.CtnTitle; import de.fau.cs.osr.ptk.common.test.nodes.CtnUrl; import de.fau.cs.osr.utils.ComparisonException; public class AstNodeJsonConverterTestBase { private AstNodeJsonTypeAdapter converter; private Gson gson; // ========================================================================= @Before public void before() { converter = AstNodeJsonTypeAdapter.forNodeType(CtnNode.class); converter.setStringNodeType(CtnText.class); GsonBuilder builder = new GsonBuilder(); builder.registerTypeHierarchyAdapter(AstNode.class, converter); builder.serializeNulls(); builder.setPrettyPrinting(); gson = builder.create(); } public void setupDefaultNodeFactory() { converter.setNodeFactory(CtnFactory.get()); } public void setupDefaultTypeMappings() { SimpleTypeNameMapper typeNameMapper = new SimpleTypeNameMapper(); typeNameMapper.add(CtnText.class, "text"); typeNameMapper.add(CtnNodeList.class, "list"); typeNameMapper.add(CtnSection.class, "section"); typeNameMapper.add(CtnTitle.class, "title"); typeNameMapper.add(CtnBody.class, "body"); typeNameMapper.add(CtnDocument.class, "document"); typeNameMapper.add(CtnIdNode.class, "id"); typeNameMapper.add(CtnUrl.class, "url"); typeNameMapper.add(CtnNodeWithObjProp.class, "nwop"); typeNameMapper.add(CtnNodeWithPropAndContent.class, "nwpac"); converter.setTypeNameMapper(typeNameMapper); converter.suppressNode(CtnBody.CtnNoBody.class); converter.suppressNode(CtnTitle.CtnNoTitle.class); converter.suppressTypeInfo(CtnBody.CtnEmptyBody.class); converter.suppressTypeInfo(CtnBody.CtnBodyImpl.class); converter.suppressTypeInfo(CtnTitle.CtnEmptyTitle.class); converter.suppressTypeInfo(CtnTitle.CtnTitleImpl.class); } public AstNodeJsonTypeAdapter getConverter() { return converter; } public Gson getGson() { return gson; } public String serialize(Object what) { return gson.toJson(what); } public CtnDocument deserialize(String json, Class typeOfT) { return (CtnDocument) gson.fromJson(json, typeOfT); } public void roundtrip(CtnNode node) throws ComparisonException { String json = serialize(node); CtnNode restoredNode = (CtnNode) deserialize(json, CtnDocument.class); try { AstComparer.compareAndThrow(node, restoredNode, true, true); } catch (ComparisonException e) { printJson(json); printRestoredJson(restoredNode); throw e; } } public void printSerialized(CtnNode node) { System.out.println(StringUtils.repeat("=", 80)); System.out.println("\"\"\"" + serialize(node) + "\"\"\""); System.out.println(StringUtils.repeat("=", 80)); } public void printJson(String json) { System.err.println("Original JSON:"); System.err.println(StringUtils.repeat("=", 80)); System.err.println("\"\"\"" + json + "\"\"\""); System.err.println(StringUtils.repeat("=", 80)); } public void printRestoredJson(Object restoredNode) { System.err.println("JSON after round trip:"); System.err.println(StringUtils.repeat("=", 80)); try { System.err.println("\"\"\"" + serialize(restoredNode) + "\"\"\""); } catch (Exception e) { System.err.println("Failed to serialize restored AST!"); e.printStackTrace(System.err); } System.err.println(StringUtils.repeat("=", 80)); } } osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-xml-tools/000077500000000000000000000000001315622671000247055ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-xml-tools/pom.xml000066400000000000000000000077501315622671000262330ustar00rootroot00000000000000 4.0.0 de.fau.cs.osr.ptk parser-toolkit-parent 3.0.8 ptk-xml-tools jar PTK - XML Tools 2012 This module provides facilities for reading and writing ASTs in XML format. ../../tooling/ org.apache.commons commons-lang3 com.thoughtworks.xstream xstream de.fau.cs.osr.utils utils de.fau.cs.osr.ptk ptk-common junit junit test org.apache.maven.plugins maven-enforcer-plugin enforce-ban-duplicate-classes org.xmlpull.v1.XmlPullParser org.xmlpull.v1.XmlPullParserException true osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-xml-tools/src/000077500000000000000000000000001315622671000254745ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-xml-tools/src/main/000077500000000000000000000000001315622671000264205ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-xml-tools/src/main/java/000077500000000000000000000000001315622671000273415ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-xml-tools/src/main/java/de/000077500000000000000000000000001315622671000277315ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-xml-tools/src/main/java/de/fau/000077500000000000000000000000001315622671000305045ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-xml-tools/src/main/java/de/fau/cs/000077500000000000000000000000001315622671000311115ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-xml-tools/src/main/java/de/fau/cs/osr/000077500000000000000000000000001315622671000317145ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-xml-tools/src/main/java/de/fau/cs/osr/ptk/000077500000000000000000000000001315622671000325125ustar00rootroot00000000000000common/000077500000000000000000000000001315622671000337235ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-xml-tools/src/main/java/de/fau/cs/osr/ptkxml/000077500000000000000000000000001315622671000345235ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-xml-tools/src/main/java/de/fau/cs/osr/ptk/commonAstNodeXmlConverter.java000066400000000000000000000365771315622671000413160ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-xml-tools/src/main/java/de/fau/cs/osr/ptk/common/xml/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common.xml; import java.util.Map; import java.util.Map.Entry; import com.thoughtworks.xstream.converters.Converter; import com.thoughtworks.xstream.converters.MarshallingContext; import com.thoughtworks.xstream.converters.UnmarshallingContext; import com.thoughtworks.xstream.io.HierarchicalStreamReader; import com.thoughtworks.xstream.io.HierarchicalStreamWriter; import de.fau.cs.osr.ptk.common.ast.AstLocation; import de.fau.cs.osr.ptk.common.ast.AstNode; import de.fau.cs.osr.ptk.common.ast.AstNodePropertyIterator; import de.fau.cs.osr.ptk.common.ast.AstStringNode; import de.fau.cs.osr.ptk.common.serialization.AstNodeConverterBase; import de.fau.cs.osr.ptk.common.serialization.SyntaxErrorException; public class AstNodeXmlConverter> extends AstNodeConverterBase implements Converter { protected static final String NODE_NAME_ATTRIBUTE = "ptk:a"; protected static final String ATTR_NAME_LOCATION = "ptk:location"; protected static final String ATTR_NAME_TYPE = "ptk:type"; // ========================================================================= protected boolean explicitRoots = false; // ========================================================================= public AstNodeXmlConverter(Class nodeType) { super(nodeType); } public static > AstNodeXmlConverter forNodeType( Class nodeType) { return new AstNodeXmlConverter(nodeType); } // ========================================================================= public void setExplicitRoots(boolean explicitRoots) { this.explicitRoots = explicitRoots; } // ========================================================================= @Override public boolean canConvert(@SuppressWarnings("rawtypes") Class type) { return getNodeType().isAssignableFrom(type); } @Override @SuppressWarnings("unchecked") public void marshal( Object source, HierarchicalStreamWriter writer, MarshallingContext context) { dispatch((T) source, explicitRoots, writer, context); } @Override public Object unmarshal( HierarchicalStreamReader reader, UnmarshallingContext context) { if (explicitRoots) { if (!reader.hasMoreChildren()) throw new SyntaxErrorException("Expected child element for explicit root node"); reader.moveDown(); } Class type = context.getRequiredType(); T node = unmarshalNode(type, reader, context); if (explicitRoots) reader.moveUp(); return node; } // ========================================================================= private void marshalNode( T n, boolean explicit, HierarchicalStreamWriter writer, MarshallingContext context) { if (explicit) { writer.startNode(getTypeAlias(n)); /* From the context it is always clear that here the node name * is also the type name. An explicit ptk:type="..." attribute * would only repeat the node name verbatim. if (isAlwaysStoreType()) storeType(n, writer); */ } boolean isStringNode = isStringNode(n.getClass()) && !n.hasAttributes(); storeLocation(n, writer); storeAttributes(n, writer, context); boolean hasVisibleProperties = true; if (isStringNode) { // we can only invoke this function for string nodes! hasVisibleProperties = hasStringNodeVisibleProperties(n); isStringNode &= !hasVisibleProperties; } if (hasVisibleProperties) storeProperties(n, isStringNode, writer, context); if (isStringNode) { writer.setValue(((AstStringNode) n).getContent()); } else if (n.isList()) { for (T c : n) dispatch(c, true, writer, context); } else { String[] childNum = n.getChildNames(); for (int i = 0; i < childNum.length; ++i) storeNamedChild(n, i, writer, context); } if (explicit) writer.endNode(); } private T unmarshalNode( Class nodeType, HierarchicalStreamReader reader, UnmarshallingContext context) { T n = instantiateNode(nodeType); restoreLocation(n, reader); boolean down = false; boolean isStringNode = isStringNode(nodeType); boolean initializedProperties = false; if (reader.hasMoreChildren()) { // A node with children cannot be serialized as pure text node isStringNode = false; reader.moveDown(); down = restoreAttributes(n, reader, context); if (down) { // If restoreAttributes() returns down = false then there are no // more children. This means that we don't have to check if // there are any more children and go down again. down = restoreProperties(n, reader, context); initializedProperties = true; } } if (!initializedProperties) initializeProperties(n, isStringNode); if (isStringNode) { // If restoreAttributes() or restoreProperties() returns down = // true then there are children! if (down) failOnUnexpectedChild(nodeType, reader); ((AstStringNode) n).setContent(reader.getValue()); } else if (down) { // If restoreAttributes() or restoreProperties() returns down = // false then there are no more children. This means that we don't // have to check if there are any more children and go down again. if (n.isList()) { restoreListOfChildren(reader, context, n); } else { restoreNamedChildren(nodeType, reader, context, n); } } else initializeChildren(n); return n; } // ========================================================================= private void storeLocation(AstNode n, HierarchicalStreamWriter writer) { if (!isLocationSuppressed()) { AstLocation loc = n.getNativeLocation(); if (loc != null) writer.addAttribute(ATTR_NAME_LOCATION, loc.toString()); } } private void restoreLocation(T n, HierarchicalStreamReader reader) { String locStr = reader.getAttribute(ATTR_NAME_LOCATION); if (locStr != null) n.setNativeLocation(AstLocation.valueOf(locStr)); } // ========================================================================= private void storeAttributes( AstNode n, HierarchicalStreamWriter writer, MarshallingContext context) { if (isAttributesSuppressed()) return; Map attrs = n.getAttributes(); if (!attrs.isEmpty()) { for (Entry e : attrs.entrySet()) { String name = e.getKey(); if (!isAttributeSuppressed(name)) writeAttribute(name, e.getValue(), writer, context); } } } private void writeAttribute( String name, Object value, HierarchicalStreamWriter writer, MarshallingContext context) { writer.startNode(NODE_NAME_ATTRIBUTE); writer.addAttribute("name", name); if (value == null) { writer.addAttribute("null", "true"); } else { storeType(value, writer); context.convertAnother(value); } writer.endNode(); } private boolean restoreAttributes( T n, HierarchicalStreamReader reader, UnmarshallingContext context) { while (true) { boolean down = readAttribute(n, reader, context); if (down) // The child was not an attribute. // Current still points to the child. return true; if (!reader.hasMoreChildren()) // There was an attribute but there are no more children. // Current points to the parent node again. return false; // There was an attribute and there are more children, move on. reader.moveDown(); } } private boolean readAttribute( T n, HierarchicalStreamReader reader, UnmarshallingContext context) { if (!reader.getNodeName().equals(NODE_NAME_ATTRIBUTE)) return true; String name = reader.getAttribute("name"); String nullAttr = reader.getAttribute("null"); boolean isNull = (nullAttr != null) && nullAttr.equals("true"); if (isNull) { n.setAttribute(name, null); } else { Class type = getExplicitType(reader); n.setAttribute(name, context.convertAnother(n, type)); } reader.moveUp(); return false; } // ========================================================================= private boolean hasStringNodeVisibleProperties(AstNode n) { for (AstNodePropertyIterator i = n.propertyIterator(); i.next();) { Object value = i.getValue(); if (value == null) continue; String name = i.getName(); if (isPropertySuppressed(name)) continue; if ("content".equals(name)) continue; return true; } return false; } private void storeProperties( AstNode n, boolean suppressContent, HierarchicalStreamWriter writer, MarshallingContext context) { if (n.getPropertyCount() > 0) { for (AstNodePropertyIterator i = n.propertyIterator(); i.next();) { Object value = i.getValue(); if (value == null) continue; String name = i.getName(); if (isPropertySuppressed(name)) continue; writeProperty(n, name, value, writer, context); } } } private void writeProperty( AstNode parentNode, String name, Object value, HierarchicalStreamWriter writer, MarshallingContext context) { if (isSuppressed(value)) return; writer.startNode(name); //if (!serializedTypeIsExpectedType(parentNode, name, value.getClass())) if (isTypeInfoRequired(parentNode, name, value.getClass())) storeType(value, writer); context.convertAnother(value); writer.endNode(); } private boolean restoreProperties( T n, HierarchicalStreamReader reader, UnmarshallingContext context) { if (n.getPropertyCount() == 0) // We should not be able to find properties here. return true; AstNodePropertyIterator curProp = n.propertyIterator(); while (true) { String name = reader.getNodeName(); boolean down = true; // We write out properties in the order they appear in the iterator. // We assume that this order is fixed and that everybody else does // it like that too. This way we can save time if our assumption // holds but loose time if it doesn't hold then it goes BOOM. AstNodePropertyIterator i = curProp; while (i.next()) { if (i.getName().equals(name)) { Class type = getTypeFromGetter(n, reader); i.setValue(context.convertAnother(n, type)); reader.moveUp(); down = false; break; } else { setDefaultProperty(n, i); } } if (down) // No matching property found. This means syntax error or we've // reached the parent node's children. return true; if (!reader.hasMoreChildren()) { // There was a property but there are no more children. // Current points to the parent node again. while (i.next()) setDefaultProperty(n, i); return false; } // There was a property and there are more children, move on. reader.moveDown(); } } private void initializeProperties(T n, boolean isStringNode) { if (n.getPropertyCount() > 0) { for (AstNodePropertyIterator i = n.propertyIterator(); i.next();) { if (!(isStringNode && i.getName().equals("content"))) // If it's a string node the content property will be set // form a child, not a property! setDefaultProperty(n, i); } } } // ========================================================================= private void storeNamedChild( T n, int i, HierarchicalStreamWriter writer, MarshallingContext context) { T child = n.get(i); if (isSuppressed(child)) return; String name = n.getChildNames()[i]; writer.startNode(name); //if (!serializedTypeIsExpectedType(n, name, child.getClass())) if (isTypeInfoRequired(n, name, child.getClass())) storeType(child, writer); dispatch(child, false, writer, context); writer.endNode(); } private void restoreNamedChildren( Class nodeType, HierarchicalStreamReader reader, UnmarshallingContext context, T n) { // The current node is already the first child int childIndex = 0; String[] childNames = n.getChildNames(); while (true) { if (childIndex >= childNames.length) { // There are still children in the XML but we don't expect // any more. failOnUnexpectedChild(nodeType, reader); return; } // Skip all children for which no value was stored in the XML String childName = reader.getNodeName(); while (true) { String expectedChildName = childNames[childIndex]; if (childName.equals(expectedChildName)) break; setDefaultChild(n, childIndex, expectedChildName); ++childIndex; if (childIndex >= childNames.length) { failOnUnexpectedChild(nodeType, reader); return; } } // We found a match Class childType = getTypeFromGetter(n, reader); T child = unmarshalNode(childType, reader, context); n.set(childIndex, child); // Continue... reader.moveUp(); ++childIndex; if (!reader.hasMoreChildren()) { // No more children in the XML -> skip remaining children for (; childIndex < childNames.length; ++childIndex) setDefaultChild(n, childIndex, childNames[childIndex]); return; } reader.moveDown(); } } private void restoreListOfChildren( HierarchicalStreamReader reader, UnmarshallingContext context, T n) { // The current node is already the first child while (true) { Class type = getClassForAlias(reader.getNodeName()); T child = unmarshalNode(type, reader, context); n.add(child); reader.moveUp(); if (!reader.hasMoreChildren()) break; reader.moveDown(); } } private void initializeChildren(T n) { String[] childNames = n.getChildNames(); for (int i = 0; i < childNames.length; ++i) setDefaultChild(n, i, childNames[i]); } // ========================================================================= private void dispatch( T n, boolean explicit, HierarchicalStreamWriter writer, MarshallingContext context) { if (n == null) throw new NullPointerException(); if (isSuppressed(n)) return; marshalNode(n, explicit, writer, context); } private void storeType(Object obj, HierarchicalStreamWriter writer) { Class type = obj.getClass(); //if (!isTypeInfoSuppressed(type)) writer.addAttribute(ATTR_NAME_TYPE, getTypeAlias(type)); } private Class getExplicitType(HierarchicalStreamReader reader) { String typeName = reader.getAttribute(ATTR_NAME_TYPE); if (typeName == null) throw new SyntaxErrorException("Expected attribute '" + ATTR_NAME_TYPE + "'!"); return getClassForAlias(typeName); } /** * Explicit type attribute override the getter type. */ private Class getTypeFromGetter( AstNode parent, HierarchicalStreamReader reader) { String typeName = reader.getAttribute(ATTR_NAME_TYPE); if (typeName == null) return getGetterType(parent, reader.getNodeName()); return getClassForAlias(typeName); } private void failOnUnexpectedChild( Class nodeType, HierarchicalStreamReader reader) { throw new SyntaxErrorException("Unexpected child element: '" + reader.getNodeName() + "' when unmarshalling node of type '" + nodeType.getName() + "'"); } } osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-xml-tools/src/test/000077500000000000000000000000001315622671000264535ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-xml-tools/src/test/java/000077500000000000000000000000001315622671000273745ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-xml-tools/src/test/java/de/000077500000000000000000000000001315622671000277645ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-xml-tools/src/test/java/de/fau/000077500000000000000000000000001315622671000305375ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-xml-tools/src/test/java/de/fau/cs/000077500000000000000000000000001315622671000311445ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-xml-tools/src/test/java/de/fau/cs/osr/000077500000000000000000000000001315622671000317475ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-xml-tools/src/test/java/de/fau/cs/osr/ptk/000077500000000000000000000000001315622671000325455ustar00rootroot00000000000000common/000077500000000000000000000000001315622671000337565ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-xml-tools/src/test/java/de/fau/cs/osr/ptkxml/000077500000000000000000000000001315622671000345565ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-xml-tools/src/test/java/de/fau/cs/osr/ptk/commonArbitraryObj.java000066400000000000000000000035261315622671000400210ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-xml-tools/src/test/java/de/fau/cs/osr/ptk/common/xml/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common.xml; import java.io.Serializable; import java.util.Arrays; final class ArbitraryObj implements Serializable { private static final long serialVersionUID = 1L; public Object nullValue = new Object(); public int intValue = -42; public String strValue = null; public double[] doubleValues = null; // ===================================================================== public void set() { nullValue = null; intValue = 42; strValue = "some string"; doubleValues = new double[] { 3.1415, 2.7182 }; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ArbitraryObj other = (ArbitraryObj) obj; if (!Arrays.equals(doubleValues, other.doubleValues)) return false; if (intValue != other.intValue) return false; if (nullValue == null) { if (other.nullValue != null) return false; } else if (!nullValue.equals(other.nullValue)) return false; if (strValue == null) { if (other.strValue != null) return false; } else if (!strValue.equals(other.strValue)) return false; return true; } } ArticleContainer.java000066400000000000000000000026121315622671000406500ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-xml-tools/src/test/java/de/fau/cs/osr/ptk/common/xml/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common.xml; import com.thoughtworks.xstream.annotations.XStreamAlias; import com.thoughtworks.xstream.annotations.XStreamAsAttribute; import de.fau.cs.osr.ptk.common.test.nodes.CtnDocument; @XStreamAlias("article-container") public class ArticleContainer { @XStreamAsAttribute public final String xmlns = XMLNS; public static final String XMLNS = "http://sweble.org/projects/parser-toolkit/ptk-xml-tools"; @XStreamAsAttribute @XStreamAlias("xmlns:ptk") public final String xmlns_ptk = XMLNS_PTK; public static final String XMLNS_PTK = "http://sweble.org/projects/parser-toolkit"; @XStreamAlias("document") protected final CtnDocument doc; public ArticleContainer(CtnDocument doc) { this.doc = doc; } } AstNodeXmlConverterTest.java000066400000000000000000000276331315622671000422020ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-xml-tools/src/test/java/de/fau/cs/osr/ptk/common/xml/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common.xml; import static de.fau.cs.osr.ptk.common.test.nodes.CtnBuilder.ctnDoc; import static de.fau.cs.osr.ptk.common.test.nodes.CtnBuilder.ctnObjProp; import static de.fau.cs.osr.ptk.common.test.nodes.CtnBuilder.ctnPropContent; import static de.fau.cs.osr.ptk.common.test.nodes.CtnBuilder.ctnSection; import static de.fau.cs.osr.ptk.common.test.nodes.CtnBuilder.ctnText; import static de.fau.cs.osr.ptk.common.test.nodes.CtnBuilder.ctnUrl; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Test; import org.w3c.dom.Element; import de.fau.cs.osr.ptk.common.ast.AstLocation; import de.fau.cs.osr.ptk.common.comparer.AstComparer; import de.fau.cs.osr.ptk.common.test.nodes.CtnBody; import de.fau.cs.osr.ptk.common.test.nodes.CtnDocument; import de.fau.cs.osr.ptk.common.test.nodes.CtnNodeWithPropAndContent; import de.fau.cs.osr.ptk.common.test.nodes.CtnSection; import de.fau.cs.osr.ptk.common.test.nodes.CtnText; import de.fau.cs.osr.ptk.common.test.nodes.CtnTitle; import de.fau.cs.osr.ptk.common.test.nodes.CtnUrl; import de.fau.cs.osr.utils.ComparisonException; public class AstNodeXmlConverterTest extends AstNodeXmlConverterTestBase { @Before public void before() { super.before(); setupDefaultNodeFactory(); setupDefaultTypeMappings(); } @Test public void testRoundTripWithImplicitRoots() throws Exception { CtnDocument doc = ctnDoc(); roundtrip(doc); } @Test public void testRoundTripWithExplicitRoots() throws Exception { getConverter().setExplicitRoots(true); CtnDocument doc = ctnDoc(); roundtrip(doc); } @Test public void testXmlFormatWithImplicitRoots() throws Exception { org.w3c.dom.Document doc = parseXml(serialize(ctnDoc())); // Has correct root node? String root = "/" + CtnDocument.class.getName().replace("$", "_-"); assertNotNull(queryNode(root, doc)); // Implicit root has no other children? assertEquals(0, queryNodeSet(root + "/*", doc).getLength()); } @Test public void testXmlFormatWithExplicitRoots() throws Exception { CtnDocument doc = ctnDoc(); getConverter().setExplicitRoots(true); org.w3c.dom.Document xmlDoc = parseXml(serialize(doc)); // Has correct root node? String root = "/" + CtnDocument.class.getName().replace("$", "_-"); assertNotNull(queryNode(root, xmlDoc)); // Has one explicit element as root? assertEquals(1, queryNodeSet(root + "/document", xmlDoc).getLength()); // Explicit root has no other children? assertEquals(0, queryNodeSet(root + "/document/*", xmlDoc).getLength()); } @Test public void testSerializationOfIntAttribute() throws Exception { CtnDocument doc = ctnDoc(); doc.setAttribute("int", 5); roundtrip(doc); } @Test public void testSerializationOfStringAttribute() throws Exception { CtnDocument doc = ctnDoc(); doc.setAttribute("str", "Hello World"); roundtrip(doc); } @Test public void testSerializationOfPropertyWithArbitraryObjectAsValue() throws Exception { ArbitraryObj obj = new ArbitraryObj(); obj.set(); CtnDocument doc = ctnDoc(ctnObjProp(obj)); roundtrip(doc); } @Test public void testSerializationOfPropertyWithNodeAsValue() throws Exception { ArbitraryObj obj = new ArbitraryObj(); obj.set(); CtnDocument doc = ctnDoc(ctnObjProp(ctnUrl().build())); roundtrip(doc); } @Test public void testSerializationOfPropertyWithNodeAsValueAndExplicitRoots() throws Exception { getConverter().setExplicitRoots(true); ArbitraryObj obj = new ArbitraryObj(); obj.set(); CtnDocument doc = ctnDoc(ctnObjProp(ctnUrl().build())); roundtrip(doc); } @Test public void testSerializationOfObjectArray() throws Exception { CtnDocument doc = ctnDoc(); doc.setAttribute("array", new Object[] { ctnText("Hallo"), ctnUrl().build() }); roundtrip(doc); } @Test public void testNoContentPropertyFoundWhenTextNodeTypeSet() throws Exception { CtnDocument doc = ctnDoc(ctnText("Hallo")); assertFalse(serialize(doc).contains("")); getConverter().setStringNodeType(null); assertTrue(serialize(doc).contains("")); } @Test public void testAttributesOnTextNodeForceContentElement() throws Exception { CtnText text = ctnText("Hallo"); text.setAttribute("ruins", "it"); CtnDocument doc = ctnDoc(text); assertTrue(serialize(doc).contains("")); } @Test public void testWrapAstInArticleContainerAndRoundtrip() throws Exception { CtnDocument doc = ctnDoc(ctnText("Hallo Welt")); ArticleContainer ac = new ArticleContainer(doc); String xml = serialize(ac); ArticleContainer restoredAc = (ArticleContainer) deserialize(xml); try { AstComparer.compareAndThrow(doc, restoredAc.doc, true, true); } catch (ComparisonException e) { printXml(xml); printRestoredXml(restoredAc); throw e; } } @Test public void testWrapAstInArticleContainerAndCheckXml() throws Exception { ArticleContainer ac = new ArticleContainer(ctnDoc(ctnText("Hallo Welt"))); org.w3c.dom.Document doc = parseXml(serialize(ac)); Element rootElem = (Element) queryNode("/article-container", doc); assertNotNull(rootElem); assertEquals(ArticleContainer.XMLNS, rootElem.getAttribute("xmlns")); assertEquals(ArticleContainer.XMLNS_PTK, rootElem.getAttribute("xmlns:ptk")); assertEquals(1, queryNodeSet("/article-container/*", doc).getLength()); assertNotNull(queryNode("/article-container/document", doc)); assertEquals(1, queryNodeSet("/article-container/document/*", doc).getLength()); assertNotNull(queryNode("/article-container/document/text[text() = 'Hallo Welt']", doc)); } @Test public void testInstantiationOfNullReplacementProperty() throws Exception { CtnDocument doc = ctnDoc(ctnUrl().withProtocol("").build()); getConverter().setSuppressEmptyStringProperties(true); org.w3c.dom.Document xmlDoc = parseXml(serialize(doc)); assertEquals(0, queryNodeSet("//protocol", xmlDoc).getLength()); roundtrip(doc); } @Test public void testNullProperty() throws Exception { CtnDocument doc = ctnDoc(ctnObjProp(null)); org.w3c.dom.Document xmlDoc = parseXml(serialize(doc)); assertEquals(0, queryNodeSet("//prop", xmlDoc).getLength()); roundtrip(doc); } @Test public void testSuppressedProperty() throws Exception { CtnDocument doc = ctnDoc(ctnObjProp("Hello World")); getConverter().suppressProperty("prop"); org.w3c.dom.Document xmlDoc = parseXml(serialize(doc)); assertEquals(0, queryNodeSet("//prop", xmlDoc).getLength()); } @Test public void testNodeWithContentAndAnotherProperty() throws Exception { // First make sure that the node is properly recognized as string node CtnDocument doc = ctnDoc(ctnPropContent(null, "Hello World")); getConverter().setStringNodeType(CtnNodeWithPropAndContent.class); org.w3c.dom.Document xmlDoc = parseXml(serialize(doc)); assertEquals(0, queryNodeSet("//content", xmlDoc).getLength()); roundtrip(doc); doc = ctnDoc(ctnPropContent(42, "Hello World")); getConverter().setStringNodeType(CtnNodeWithPropAndContent.class); xmlDoc = parseXml(serialize(doc)); assertEquals(1, queryNodeSet("//content", xmlDoc).getLength()); roundtrip(doc); } @Test public void testNodeWithAtLeastTwoNamedChildren() throws Exception { CtnDocument doc = ctnDoc(ctnSection().build()); org.w3c.dom.Document xmlDoc = parseXml(serialize(doc)); assertNotNull(queryNode("//title", xmlDoc)); assertNotNull(queryNode("//body", xmlDoc)); roundtrip(doc); } @Test public void testStoreLocation() throws Exception { CtnDocument doc = astWithLocations(); roundtrip(doc); org.w3c.dom.Document xmlDoc = parseXml(serialize(doc)); assertNotNull(((Element) queryNode("//text", xmlDoc)).getAttributeNode("ptk:location")); assertNotNull(((Element) queryNode("//url", xmlDoc)).getAttributeNode("ptk:location")); } @Test public void testSuppressLocation() throws Exception { CtnDocument doc = astWithLocations(); getConverter().setStoreLocation(false); org.w3c.dom.Document xmlDoc = parseXml(serialize(doc)); assertNull(((Element) queryNode("//text", xmlDoc)).getAttributeNode("ptk:location")); assertNull(((Element) queryNode("//url", xmlDoc)).getAttributeNode("ptk:location")); } private CtnDocument astWithLocations() { CtnText text = ctnText("Hello"); text.setNativeLocation(new AstLocation("some file", 42, 43)); CtnUrl url = ctnUrl().build(); url.setNativeLocation(new AstLocation("some file", 44, 45)); CtnDocument doc = ctnDoc(text, url); return doc; } @Test public void testStoreNodesWithAttributes() throws Exception { CtnDocument doc = astWithAttributes(); roundtrip(doc); } @Test public void testSuppressCertainAttributes() throws Exception { CtnDocument doc = astWithAttributes(); getConverter().suppressAttribute("area52"); String xml = serialize(doc); assertTrue(xml.contains("area51")); assertFalse(xml.contains("area52")); } @Test public void testSuppressAllAttributes() throws Exception { CtnDocument doc = astWithAttributes(); getConverter().setStoreAttributes(false); String xml = serialize(doc); assertFalse(xml.contains("area51")); assertFalse(xml.contains("area52")); } private CtnDocument astWithAttributes() { CtnUrl url = ctnUrl().build(); url.setAttribute("area51", "Hello World 1"); url.setAttribute("area52", "Hello World 2"); CtnDocument doc = ctnDoc(url); return doc; } @Test public void testStoreNullAttribute() throws Exception { CtnUrl url = ctnUrl().build(); url.setAttribute("area51", null); CtnDocument doc = ctnDoc(url); roundtrip(doc); } @Test public void testBodyInterfaceNode() throws Exception { CtnSection sec = ctnSection().build(); CtnDocument doc = ctnDoc(sec); assertEquals(CtnBody.CtnBodyImpl.class, sec.getBody().getClass()); assertTrue(sec.hasBody()); org.w3c.dom.Document xmlDoc = parseXml(serialize(doc)); assertNotNull(queryNode("//section/body", xmlDoc)); roundtrip(doc); } @Test public void testNoBodyNode() throws Exception { CtnSection sec = ctnSection().build(); sec.removeBody(); CtnDocument doc = ctnDoc(sec); assertEquals(CtnBody.CtnNoBody.class, sec.getBody().getClass()); assertFalse(sec.hasBody()); roundtrip(doc); String xml = serialize(doc); org.w3c.dom.Document xmlDoc = parseXml(xml); assertNull(queryNode("//section/body", xmlDoc)); CtnDocument restoredDoc = (CtnDocument) deserialize(xml); assertFalse(((CtnSection) restoredDoc.get(0)).hasBody()); } @Test public void testNoTitleNodeToCoverAllPaths() throws Exception { CtnSection sec = ctnSection().build(); sec.removeTitle(); CtnDocument doc = ctnDoc(sec); assertEquals(CtnTitle.CtnNoTitle.class, sec.getTitle().getClass()); assertFalse(sec.hasTitle()); assertTrue(sec.hasBody()); roundtrip(doc); String xml = serialize(doc); org.w3c.dom.Document xmlDoc = parseXml(xml); assertNull(queryNode("//section/title", xmlDoc)); CtnDocument restoredDoc = (CtnDocument) deserialize(xml); assertFalse(((CtnSection) restoredDoc.get(0)).hasTitle()); } @Test public void testStoreComplexArrayAsAttribute() throws Exception { CtnDocument doc = ctnDoc(); doc.setAttribute("DoubleTrouble", new Double[][] { new Double[] { 3.1415, 2 * 3.1415 }, new Double[] { 2.7182, 2 * 2.7182 } }); roundtrip(doc); } } AstNodeXmlConverterTestBase.java000066400000000000000000000136251315622671000427710ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-xml-tools/src/test/java/de/fau/cs/osr/ptk/common/xml/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common.xml; import java.io.ByteArrayInputStream; import javax.xml.namespace.QName; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathFactory; import org.apache.commons.lang3.StringUtils; import org.junit.Before; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.io.xml.DomDriver; import de.fau.cs.osr.ptk.common.comparer.AstComparer; import de.fau.cs.osr.ptk.common.serialization.SimpleTypeNameMapper; import de.fau.cs.osr.ptk.common.test.nodes.CtnBody; import de.fau.cs.osr.ptk.common.test.nodes.CtnDocument; import de.fau.cs.osr.ptk.common.test.nodes.CtnFactory; import de.fau.cs.osr.ptk.common.test.nodes.CtnIdNode; import de.fau.cs.osr.ptk.common.test.nodes.CtnNode; import de.fau.cs.osr.ptk.common.test.nodes.CtnNodeList; import de.fau.cs.osr.ptk.common.test.nodes.CtnNodeWithObjProp; import de.fau.cs.osr.ptk.common.test.nodes.CtnNodeWithPropAndContent; import de.fau.cs.osr.ptk.common.test.nodes.CtnSection; import de.fau.cs.osr.ptk.common.test.nodes.CtnText; import de.fau.cs.osr.ptk.common.test.nodes.CtnTitle; import de.fau.cs.osr.ptk.common.test.nodes.CtnUrl; import de.fau.cs.osr.utils.ComparisonException; public class AstNodeXmlConverterTestBase { private XStream xstream; private AstNodeXmlConverter converter; // ========================================================================= @Before public void before() { converter = AstNodeXmlConverter.forNodeType(CtnNode.class); converter.setStringNodeType(CtnText.class); xstream = new XStream(new DomDriver()); xstream.registerConverter(converter); xstream.setMode(XStream.NO_REFERENCES); xstream.processAnnotations(ArticleContainer.class); } public void setupDefaultNodeFactory() { converter.setNodeFactory(CtnFactory.get()); } public void setupDefaultTypeMappings() { SimpleTypeNameMapper typeNameMapper = new SimpleTypeNameMapper(); typeNameMapper.add(CtnText.class, "text"); typeNameMapper.add(CtnNodeList.class, "list"); typeNameMapper.add(CtnSection.class, "section"); typeNameMapper.add(CtnTitle.class, "title"); typeNameMapper.add(CtnBody.class, "body"); typeNameMapper.add(CtnDocument.class, "document"); typeNameMapper.add(CtnIdNode.class, "id"); typeNameMapper.add(CtnUrl.class, "url"); typeNameMapper.add(CtnNodeWithObjProp.class, "nwop"); typeNameMapper.add(CtnNodeWithPropAndContent.class, "nwpac"); converter.setTypeNameMapper(typeNameMapper); converter.suppressNode(CtnBody.CtnNoBody.class); converter.suppressNode(CtnTitle.CtnNoTitle.class); converter.suppressTypeInfo(CtnBody.CtnEmptyBody.class); converter.suppressTypeInfo(CtnBody.CtnBodyImpl.class); converter.suppressTypeInfo(CtnTitle.CtnEmptyTitle.class); converter.suppressTypeInfo(CtnTitle.CtnTitleImpl.class); } public AstNodeXmlConverter getConverter() { return converter; } public XStream getXstream() { return xstream; } public String serialize(Object what) { return xstream.toXML(what); } public Object deserialize(String xml) { return xstream.fromXML(xml); } public void roundtrip(CtnNode node) throws ComparisonException { String xml = serialize(node); CtnNode restoredNode = (CtnNode) deserialize(xml); try { AstComparer.compareAndThrow(node, restoredNode, true, true); } catch (ComparisonException e) { printXml(xml); printRestoredXml(restoredNode); throw e; } } public void printSerialized(CtnNode node) { System.out.println(StringUtils.repeat("=", 80)); System.out.println("\"\"\"" + serialize(node) + "\"\"\""); System.out.println(StringUtils.repeat("=", 80)); } public void printXml(String xml) { System.err.println("Original XML:"); System.err.println(StringUtils.repeat("=", 80)); System.err.println("\"\"\"" + xml + "\"\"\""); System.err.println(StringUtils.repeat("=", 80)); } public void printRestoredXml(Object restoredNode) { System.err.println("XML after round trip:"); System.err.println(StringUtils.repeat("=", 80)); try { System.err.println("\"\"\"" + serialize(restoredNode) + "\"\"\""); } catch (Exception e) { System.err.println("Failed to serialize restored AST!"); e.printStackTrace(System.err); } System.err.println(StringUtils.repeat("=", 80)); } public Document parseXml(String xml) throws Exception { ByteArrayInputStream is = new ByteArrayInputStream(xml.getBytes()); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(is); is.close(); doc.getDocumentElement().normalize(); return doc; } public Node queryNode(String expression, Node doc) throws Exception { return (Node) xpath(expression, doc, XPathConstants.NODE); } public NodeList queryNodeSet(String expression, Node doc) throws Exception { return (NodeList) xpath(expression, doc, XPathConstants.NODESET); } public Object xpath(String expression, Node doc, QName returnType) throws Exception { XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); return xpath.evaluate(expression, doc, returnType); } } osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-xpath/000077500000000000000000000000001315622671000240735ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-xpath/pom.xml000066400000000000000000000051031315622671000254070ustar00rootroot00000000000000 4.0.0 de.fau.cs.osr.ptk parser-toolkit-parent 3.0.8 ptk-xpath jar PTK - XPath 2016 Query ASTs using XPath expressions ../../tooling/ commons-jxpath commons-jxpath de.fau.cs.osr.ptk ptk-common de.fau.cs.osr.utils utils junit junit test osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-xpath/src/000077500000000000000000000000001315622671000246625ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-xpath/src/main/000077500000000000000000000000001315622671000256065ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-xpath/src/main/java/000077500000000000000000000000001315622671000265275ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-xpath/src/main/java/de/000077500000000000000000000000001315622671000271175ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-xpath/src/main/java/de/fau/000077500000000000000000000000001315622671000276725ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-xpath/src/main/java/de/fau/cs/000077500000000000000000000000001315622671000302775ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-xpath/src/main/java/de/fau/cs/osr/000077500000000000000000000000001315622671000311025ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-xpath/src/main/java/de/fau/cs/osr/ptk/000077500000000000000000000000001315622671000317005ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-xpath/src/main/java/de/fau/cs/osr/ptk/common/000077500000000000000000000000001315622671000331705ustar00rootroot00000000000000jxpath/000077500000000000000000000000001315622671000344075ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-xpath/src/main/java/de/fau/cs/osr/ptk/commonAstNodeFieldIterator.java000066400000000000000000000170071315622671000412720ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-xpath/src/main/java/de/fau/cs/osr/ptk/common/jxpath/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common.jxpath; import org.apache.commons.jxpath.ri.Compiler; import org.apache.commons.jxpath.ri.QName; import org.apache.commons.jxpath.ri.compiler.NodeNameTest; import org.apache.commons.jxpath.ri.compiler.NodeTest; import org.apache.commons.jxpath.ri.compiler.NodeTypeTest; import org.apache.commons.jxpath.ri.model.NodeIterator; import org.apache.commons.jxpath.ri.model.NodePointer; import de.fau.cs.osr.ptk.common.ast.AstNode; public class AstNodeFieldIterator implements NodeIterator { /** A pointer to the node over whose children we are iterating. */ private NodePointer parent; /** The actual node over whose children we are iterating. */ private AstNode node; /** The node test to apply to children. */ private NodeTest test; /** The child we are currently pointing to. */ private AstNode child = null; /** Iteration direction. */ private boolean reverse; /** * Position in the filtered list of children. Position `0' has the * special meaning, that the iterator has not yet been initialized. */ private int position = 0; private int positionInNode = -1; private int size; // ========================================================================= /** * @param parent * The node over whose children this iterator iterates. * @param nodeTest * The test to apply while iterating over parent's children. Only * children who pass the test will be assigned an consectuvie * index and get returned. * @param reverse * Run through the children in reverse direction. * @param startWith * A pointer to a child node that will be considered the "base" * child and will have the index `0'. Children in front of this * node will have negative indices. NOT YET SUPPORTED! */ public AstNodeFieldIterator( NodePointer parent, NodeTest nodeTest, boolean reverse, NodePointer startWith) { this.parent = parent; this.node = (AstNode) parent.getImmediateNode(); this.test = nodeTest; this.reverse = reverse; this.size = node.size(); if (startWith != null) throw new IllegalArgumentException("Not yet supported!"); //debug("AstNodeFieldIterator"); } // ========================================================================= @Override public NodePointer getNodePointer() { try { // Position `0' means that the iterator has not yet been initialized // and therefore points to the start item (the first by default). if (position == 0) setPosition(1); if (child == null) { return null; } else { int i = getChildIndex(); if (i < node.getChildNames().length) { return new AstNodeFieldPointer(parent, node, getChildIndex()); } else { return new AstNodePointer(parent, child); } } } finally { //debug("getNodePointer", position, child); } } @Override public int getPosition() { //debug("setPosition", position); return position; } @Override public boolean setPosition(int position) { /* Can happen ... they don't filter these out of queries if (position <= 0) throw new IndexOutOfBoundsException(); */ try { if (position <= 0) return false; while (this.position < position) { if (!next()) return false; } while (this.position > position) { if (!previous()) return false; } return true; } finally { //debug("setPosition", position, this.position, child); } } private boolean next() { if (positionInNode >= size) { return false; } else { ++position; ++positionInNode; while (!testChild()) ++positionInNode; return child != null; } } private boolean previous() { if (positionInNode < 0) { return false; } else { --position; --positionInNode; while (!testChild()) --positionInNode; return child != null; } } // ========================================================================= /** * @return True when there is no node at `positionInNode' or if there is a * node which passes the test. False otherwise: There is a node, but * it fails the test. Basically tells you whether to continue the * search. */ private boolean testChild() { child = null; if (positionInNode < 0 || positionInNode >= size) { return true; } else if (test == null) { child = node.get(getChildIndex()); return true; } else { if (test instanceof NodeNameTest) { NodeNameTest nodeNameTest = (NodeNameTest) test; QName testName = nodeNameTest.getNodeName(); // We don't support prefixes if (testName.getPrefix() != null) return false; // Wildcards don't match when prefixes differ, so check for // wildcards only after we made sure that we are not looking // for a prefixed name. if (nodeNameTest.isWildcard()) { child = node.get(getChildIndex()); return true; } // Perform actual name check return testName(testName.getName()); } else if (test instanceof NodeTypeTest) { NodeTypeTest nodeTypeTest = (NodeTypeTest) test; switch (nodeTypeTest.getNodeType()) { case Compiler.NODE_TYPE_NODE: child = node.get(getChildIndex()); return true; case Compiler.NODE_TYPE_TEXT: case Compiler.NODE_TYPE_COMMENT: case Compiler.NODE_TYPE_PI: default: return false; } } else { // Unhandled: ProcessingInstructionTest // An AstNodeInterface can never be a PI. return false; } } } private int getChildIndex() { return reverse ? size - 1 - positionInNode : positionInNode; } private boolean testName(String test) { String[] fixedNames = node.getChildNames(); int i = getChildIndex(); if (i < fixedNames.length) { if (namesEqual(fixedNames[i], test)) { child = node.get(i); return true; } else return false; } else { child = node.get(i); if (child != null) { if (!namesEqual(child.getNodeName(), test)) { child = null; return false; } else return true; } else { child = null; return false; } } } private static final boolean namesEqual(String s1, String s2) { return s1 == s2 || s1.equals(s2); } // ========================================================================= /* private void debug(String where, Object... params) { StringBuilder b = new StringBuilder(); String path = parent.asPath(); b.append(String.format( "@%8x : %s : %s%s.%s ; ", System.identityHashCode(this), path, StringUtils.strrep(' ', 28 - path.length()), getClass().getSimpleName(), where)); int i = 0; for (Object o : params) { if (i++ != 0) b.append(", "); b.append(o == null ? "null" : o.toString()); } System.out.println(b.toString()); } */ } AstNodeFieldPointer.java000066400000000000000000000211721315622671000411170ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-xpath/src/main/java/de/fau/cs/osr/ptk/common/jxpath/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common.jxpath; import org.apache.commons.jxpath.ri.Compiler; import org.apache.commons.jxpath.ri.QName; import org.apache.commons.jxpath.ri.compiler.NodeNameTest; import org.apache.commons.jxpath.ri.compiler.NodeTest; import org.apache.commons.jxpath.ri.compiler.NodeTypeTest; import org.apache.commons.jxpath.ri.model.NodeIterator; import org.apache.commons.jxpath.ri.model.NodePointer; import de.fau.cs.osr.ptk.common.ast.AstNode; import de.fau.cs.osr.utils.FmtInternalLogicError; public class AstNodeFieldPointer extends NodePointer { private static final long serialVersionUID = 1L; /** This pointer points to a field of this node. */ private AstNode node; /** The index of the field in `node' this pointer points to. */ private int fieldIndex; // ========================================================================= public AstNodeFieldPointer( NodePointer parent, AstNode node, int index) { // Only called by an AstNodeFieldIterator. // The `parent' pointer points to `node'. Index refers to the field // in `node'. super(parent); this.node = node; this.fieldIndex = index; //debug("AstNodeFieldPointer"); } // ========================================================================= @Override public NodeIterator attributeIterator(QName name) { //debug("attributeIterator"); /* This looks like a bug! // Shortcut ... if (((AstNodeInterface) getImmediateNode()).hasAttributes()) return null; */ return new AstPropertyIterator(this, name); } @Override public NodeIterator childIterator( NodeTest test, boolean reverse, NodePointer startWith) { //debug("childIterator"); AstNode pointee = (AstNode) getImmediateNode(); // Shortcut ... if (isLeaf()) { //throw new FormattedInternalLogicError("This should not happen!?"); // But it does :( return null; } if (pointee.isNodeType(AstNode.NT_NODE_LIST)) { return new AstNodeFieldIterator( this, test, reverse, startWith); } else { return new AstNodeFieldIterator( new AstNodePointer(this, pointee), test, reverse, startWith); } } @Override public boolean isLeaf() { AstNode pointee = (AstNode) getImmediateNode(); return pointee == null || pointee.isEmpty(); } @Override public boolean isActual() { return true; } @Override public boolean isCollection() { return false; } @Override public int getLength() { return 1; } @Override public QName getName() { // Since we don't handle namespaces, we probably should return // `null' as namespace prefix in names. return new QName(null, getSimpleName()); } @Override public Object getBaseValue() { return getImmediateNode(); } @Override public Object getImmediateNode() { return node.get(fieldIndex); } @Override public void setValue(Object value) { throw new UnsupportedOperationException("Not supported yet."); } @Override public int compareChildNodePointers( NodePointer pointer1, NodePointer pointer2) { //debug("compareChildNodePointers"); if (pointer1.getBaseValue() == pointer2.getBaseValue()) return 0; boolean p1IsProp = pointer1 instanceof AstPropertyPointer; boolean p2IsProp = pointer2 instanceof AstPropertyPointer; if (p1IsProp && !p2IsProp) { return -1; } else if (!p1IsProp && p2IsProp) { return 1; } else if (p1IsProp && p2IsProp) { AstPropertyPointer p1 = (AstPropertyPointer) pointer1; AstPropertyPointer p2 = (AstPropertyPointer) pointer2; int cmp = p1.getName2().compareTo(p2.getName2()); if (cmp == 0) throw new FmtInternalLogicError(); return cmp; } else { AstNode node1 = (AstNode) pointer1.getBaseValue(); AstNode node2 = (AstNode) pointer2.getBaseValue(); for (AstNode child : (AstNode) getImmediateNode()) { if (child == node1) { return -1; } else if (child == node2) { return 1; } } throw new FmtInternalLogicError(); } } // ========================================================================= @Override public int hashCode() { return getImmediateNode().hashCode(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; AstNodeFieldPointer other = (AstNodeFieldPointer) obj; if (getImmediateNode() != other.getImmediateNode()) return false; return true; } // ========================================================================= @Override public String asPath() { StringBuffer buffer = new StringBuffer(); if (parent != null) buffer.append(parent.asPath()); // If the parent pointer is not one of our pointer types, it is the // parent's responsibility to produce the node test part of the path if (parent instanceof AstNodePointer || parent instanceof AstNodeFieldPointer) { if (buffer.length() == 0 || buffer.charAt(buffer.length() - 1) != '/') buffer.append('/'); buffer.append(getSimpleName()); if (parent != null) { buffer.append('['); buffer.append(getRelativePosition()); buffer.append(']'); } } return buffer.toString(); } private int getRelativePosition() { if (parent != null) { if (parent instanceof AstNodePointer || parent instanceof AstNodeFieldPointer) { NodePointer p = (NodePointer) parent; AstNode thisNode = (AstNode) getImmediateNode(); int i = 1; for (AstNode n : (AstNode) p.getImmediateNode()) { if (n == thisNode) return i; ++i; } throw new FmtInternalLogicError(); } /* else if (parent instanceof AstNodeFieldPointer) { AstNodeFieldPointer p = (AstNodeFieldPointer) parent; int i = 1; for (AstNodeInterface n : (AstNodeInterface) p.getImmediateNode()) { if (n == node) return i; ++i; } throw new FormattedInternalLogicError(); } */ else return 1; } else return 1; } // ========================================================================= @Override public boolean testNode(NodeTest test) { //debug("testNode", test); if (test == null) { return true; } else if (test instanceof NodeNameTest) { NodeNameTest nodeNameTest = (NodeNameTest) test; QName testName = nodeNameTest.getNodeName(); // We don't support prefixes if (testName.getPrefix() != null) return false; // Wildcards don't match when prefixes differ, so check this after // we made sure that we are not looking for a prefixed name. if (nodeNameTest.isWildcard()) return true; // Perform actual name check String s1 = getSimpleName(); String s2 = testName.getName(); // s1 cannot be `null' return s1 == s2 || s1.equals(s2); } else if (test instanceof NodeTypeTest) { NodeTypeTest nodeTypeTest = (NodeTypeTest) test; switch (nodeTypeTest.getNodeType()) { case Compiler.NODE_TYPE_NODE: return true; case Compiler.NODE_TYPE_TEXT: case Compiler.NODE_TYPE_COMMENT: case Compiler.NODE_TYPE_PI: default: return false; } } else { // Unhandled: ProcessingInstructionTest // An AstNodeInterface can never be a PI. return false; } } // ========================================================================= private String getSimpleName() { return node.getChildNames()[fieldIndex]; } // ========================================================================= /* private void debug(String where, Object... params) { StringBuilder b = new StringBuilder(); String path = asPath(); b.append(String.format( "@%8x : %s : %s%s.%s ; ", System.identityHashCode(this), path, StringUtils.strrep(' ', 28 - path.length()), getClass().getSimpleName(), where)); int i = 0; for (Object o : params) { if (i++ != 0) b.append(", "); b.append(o == null ? "null" : o.toString()); } System.out.println(b.toString()); } */ } AstNodePointer.java000066400000000000000000000217241315622671000401560ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-xpath/src/main/java/de/fau/cs/osr/ptk/common/jxpath/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common.jxpath; import org.apache.commons.jxpath.ri.Compiler; import org.apache.commons.jxpath.ri.QName; import org.apache.commons.jxpath.ri.compiler.NodeNameTest; import org.apache.commons.jxpath.ri.compiler.NodeTest; import org.apache.commons.jxpath.ri.compiler.NodeTypeTest; import org.apache.commons.jxpath.ri.model.NodeIterator; import org.apache.commons.jxpath.ri.model.NodePointer; import de.fau.cs.osr.ptk.common.ast.AstNode; import de.fau.cs.osr.utils.FmtInternalLogicError; public class AstNodePointer extends NodePointer { private static final long serialVersionUID = 1L; /** The node this pointer points to. */ private AstNode node; // ========================================================================= public AstNodePointer(AstNode node) { super(null); this.node = node; //debug("AstNodePointer(AstNodeInterface node)"); } public AstNodePointer(NodePointer parent, AstNode node) { // Usually called by an AstNodeIterator. In this case, `parent' would // point to the node that we iterated over and `node' would be the // child node we found. super(parent); this.node = node; //debug("AstNodePointer(NodePointer parent, AstNodeInterface node)"); } // ========================================================================= @Override public NodeIterator attributeIterator(QName name) { //debug("attributeIterator"); if (node.hasAttributes() || node.hasProperties()) return new AstPropertyIterator(this, name); return null; } @Override public NodeIterator childIterator( NodeTest test, boolean reverse, NodePointer startWith) { //debug("childIterator"); if (isLeaf()) { //throw new FormattedInternalLogicError("This should not happen!?"); // But it does :( return null; } return new AstNodeFieldIterator(this, test, reverse, startWith); } @Override public boolean isLeaf() { /* boolean isEmpty = node.isEmpty(); if (!isEmpty) { isEmpty = true; for (AstNodeInterface child : node) if (child != null) { isEmpty = false; break; } } return isEmpty; */ return node.isEmpty(); } @Override public boolean isActual() { return true; } @Override public boolean isCollection() { // As far as I can tell, collection semantics is not really part of // XPath. Anyway, I don't get how it's supposed to work ... return false; // If it has a variable number of children, then the non-fixed children // will have to be exposed as a collection //return node.hasVariable() || !node.isEmpty(); } @Override public int getLength() { return 1; //if (isCollection()) // return node.size(); //else // return 1; } @Override public QName getName() { // Since we don't handle namespaces, we probably should return // `null' as namespace prefix in names. return new QName(null, getSimpleName()); //Class> clazz = node.getClass(); //return new QName( // clazz.getPackage().getName(), // clazz.getSimpleName()); } @Override public Object getBaseValue() { return node; } @Override public Object getImmediateNode() { return node; } @Override public void setValue(Object value) { throw new UnsupportedOperationException("Not supported yet."); } @Override public int compareChildNodePointers( NodePointer pointer1, NodePointer pointer2) { //debug("compareChildNodePointers"); if (pointer1.getBaseValue() == pointer2.getBaseValue()) return 0; boolean p1IsProp = pointer1 instanceof AstPropertyPointer; boolean p2IsProp = pointer2 instanceof AstPropertyPointer; if (p1IsProp && !p2IsProp) { return -1; } else if (!p1IsProp && p2IsProp) { return 1; } else if (p1IsProp && p2IsProp) { AstPropertyPointer p1 = (AstPropertyPointer) pointer1; AstPropertyPointer p2 = (AstPropertyPointer) pointer2; int cmp = p1.getName2().compareTo(p2.getName2()); if (cmp == 0) throw new FmtInternalLogicError(); return cmp; } else { AstNode node1 = (AstNode) pointer1.getBaseValue(); AstNode node2 = (AstNode) pointer2.getBaseValue(); for (AstNode child : node) { if (child == node1) { return -1; } else if (child == node2) { return 1; } } throw new FmtInternalLogicError(); } } // ========================================================================= @Override public String asPath() { StringBuffer buffer = new StringBuffer(); if (parent != null) { buffer.append(parent.asPath()); // If the parent pointer is not one of our pointer types, it is the // parent's responsibility to produce the node test part of the path if (parent instanceof AstNodePointer || parent instanceof AstNodeFieldPointer) { if (buffer.length() == 0 || buffer.charAt(buffer.length() - 1) != '/') buffer.append('/'); buffer.append(getSimpleName()); if (parent != null) { buffer.append('['); buffer.append(getRelativePosition()); buffer.append(']'); } } } else { buffer.append('/'); } return buffer.toString(); } private int getRelativePosition() { if (parent != null) { if (parent instanceof AstNodePointer || parent instanceof AstNodeFieldPointer) { NodePointer p = (NodePointer) parent; AstNode thisNode = (AstNode) getImmediateNode(); int i = 1; for (AstNode n : (AstNode) p.getImmediateNode()) { if (n == thisNode) return i; ++i; } throw new FmtInternalLogicError(); } /* else if (parent instanceof AstNodeFieldPointer) { AstNodeFieldPointer p = (AstNodeFieldPointer) parent; int i = 1; for (AstNodeInterface n : (AstNodeInterface) p.getImmediateNode()) { if (n == node) return i; ++i; } throw new FormattedInternalLogicError(); } */ else return 1; } else return 1; } // ========================================================================= @Override public int hashCode() { return node.hashCode(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; AstNodePointer other = (AstNodePointer) obj; if (node != other.node) return false; return true; } // ========================================================================= @Override public boolean testNode(NodeTest test) { //debug("testNode", test); if (test == null) { return true; } else if (test instanceof NodeNameTest) { NodeNameTest nodeNameTest = (NodeNameTest) test; QName testName = nodeNameTest.getNodeName(); // We don't support prefixes if (testName.getPrefix() != null) return false; // Wildcards don't match when prefixes differ, so check this after // we made sure that we are not looking for a prefixed name. if (nodeNameTest.isWildcard()) return true; // Perform actual name check String s1 = getSimpleName(); String s2 = testName.getName(); // s1 cannot be `null' return s1 == s2 || s1.equals(s2); } else if (test instanceof NodeTypeTest) { NodeTypeTest nodeTypeTest = (NodeTypeTest) test; switch (nodeTypeTest.getNodeType()) { case Compiler.NODE_TYPE_NODE: return true; case Compiler.NODE_TYPE_TEXT: case Compiler.NODE_TYPE_COMMENT: case Compiler.NODE_TYPE_PI: default: return false; } } else { // Unhandled: ProcessingInstructionTest // An AstNodeInterface can never be a PI. return false; } } // ========================================================================= private String getSimpleName() { return node.getClass().getSimpleName(); } // ========================================================================= /* private void debug(String where, Object... params) { StringBuilder b = new StringBuilder(); String path = asPath(); b.append(String.format( "@%8x : %s : %s%s.%s ; ", System.identityHashCode(this), path, StringUtils.strrep(' ', 28 - path.length()), getClass().getSimpleName(), where)); int i = 0; for (Object o : params) { if (i++ != 0) b.append(", "); b.append(o == null ? "null" : o.toString()); } System.out.println(b.toString()); } */ } AstNodePointerFactory.java000066400000000000000000000030701315622671000415000ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-xpath/src/main/java/de/fau/cs/osr/ptk/common/jxpath/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common.jxpath; import java.util.Locale; import org.apache.commons.jxpath.ri.QName; import org.apache.commons.jxpath.ri.model.NodePointer; import org.apache.commons.jxpath.ri.model.NodePointerFactory; import de.fau.cs.osr.ptk.common.ast.AstNode; public class AstNodePointerFactory implements NodePointerFactory { // We have to beat Collection (order == 10) public static final int AST_NODE_POINTER_FACTORY_ORDER = 9; @Override public int getOrder() { return AST_NODE_POINTER_FACTORY_ORDER; } @Override public NodePointer createNodePointer( QName name, Object bean, Locale locale) { return bean instanceof AstNode ? new AstNodePointer((AstNode) bean) : null; } @Override public NodePointer createNodePointer( NodePointer parent, QName name, Object bean) { return bean instanceof AstNode ? new AstNodePointer(parent, (AstNode) bean) : null; } } AstPropertyIterator.java000066400000000000000000000125461315622671000412700ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-xpath/src/main/java/de/fau/cs/osr/ptk/common/jxpath/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common.jxpath; import java.util.Map; import java.util.Map.Entry; import org.apache.commons.jxpath.ri.QName; import org.apache.commons.jxpath.ri.model.NodeIterator; import org.apache.commons.jxpath.ri.model.NodePointer; import de.fau.cs.osr.ptk.common.ast.AstNode; import de.fau.cs.osr.ptk.common.ast.AstNodePropertyIterator; import de.fau.cs.osr.ptk.common.ast.NoSuchPropertyException; public class AstPropertyIterator implements NodeIterator { private NodePointer parent; private Property[] properties; private int position = 0; // ========================================================================= public AstPropertyIterator(NodePointer parent, QName qname) { this.parent = parent; AstNode node = (AstNode) parent.getNode(); properties = null; if (qname.getPrefix() == null) { String name = qname.getName(); if (name.equals("*")) { Map props = node.getAttributes(); int size = node.getPropertyCount() + props.size(); properties = new Property[size]; int i = 0; AstNodePropertyIterator j = node.propertyIterator(); while (j.next()) properties[i++] = new Property(node, j.getName(), j.getValue()); for (Entry prop : props.entrySet()) properties[i++] = new Property(node, prop); } else { Object value = null; try { value = node.getProperty(name); } catch (NoSuchPropertyException e) { value = node.getAttribute(name); } if (value != null) properties = new Property[] { new Property(node, name, value) }; } } if (properties == null) properties = new Property[0]; //debug("AstPropertyIterator", qname, Arrays.toString(properties)); } @Override public NodePointer getNodePointer() { Property prop = null; try { if (position == 0) { if (!setPosition(1)) return null; } prop = properties[position - 1]; return new AstPropertyPointer(parent, prop); } finally { //debug("getNodePointer", position, prop); } } @Override public int getPosition() { //debug("getPosition", position); return position; } @Override public boolean setPosition(int position) { try { if (position >= 1 && position <= properties.length) { this.position = position; return true; } else return false; } finally { //debug("setPosition", position, this.position, properties.length); } } // ========================================================================= public static final class Property { private final AstNode owner; private final String name; private final Object value; public Property(AstNode owner, String name, Object value) { this.owner = owner; this.name = name; this.value = value; } public Property(AstNode owner, Entry entry) { this.owner = owner; this.name = entry.getKey(); this.value = entry.getValue(); } public String getName() { return name; } public Object getValue() { return value; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + ((owner == null) ? 0 : owner.hashCode()); result = prime * result + ((value == null) ? 0 : value.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Property other = (Property) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; if (owner == null) { if (other.owner != null) return false; } else if (!owner.equals(other.owner)) return false; if (value == null) { if (other.value != null) return false; } else if (!value.equals(other.value)) return false; return true; } @Override public String toString() { return "AstNodeProperty [name=" + name + ", value=" + value + "]"; } } // ========================================================================= /* private void debug(String where, Object... params) { StringBuilder b = new StringBuilder(); String path = parent.asPath(); b.append(String.format( "@%8x : %s : %s%s.%s ; ", System.identityHashCode(this), path, StringUtils.strrep(' ', 28 - path.length()), getClass().getSimpleName(), where)); int i = 0; for (Object o : params) { if (i++ != 0) b.append(", "); b.append(o == null ? "null" : o.toString()); } System.out.println(b.toString()); } */ } AstPropertyPointer.java000066400000000000000000000076571315622671000411260ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-xpath/src/main/java/de/fau/cs/osr/ptk/common/jxpath/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common.jxpath; import org.apache.commons.jxpath.ri.Compiler; import org.apache.commons.jxpath.ri.QName; import org.apache.commons.jxpath.ri.compiler.NodeTest; import org.apache.commons.jxpath.ri.compiler.NodeTypeTest; import org.apache.commons.jxpath.ri.model.NodePointer; import de.fau.cs.osr.ptk.common.jxpath.AstPropertyIterator.Property; public class AstPropertyPointer extends NodePointer { private static final long serialVersionUID = 1L; private Property property; // ========================================================================= public AstPropertyPointer(NodePointer parent, Property prop) { super(parent); this.property = prop; //debug("AstPropertyPointer"); } // ========================================================================= @Override public boolean isLeaf() { return true; } @Override public boolean isActual() { return true; } @Override public boolean isCollection() { return false; } @Override public int getLength() { return 1; } @Override public QName getName() { return new QName(null, getName2()); } @Override public Object getBaseValue() { return getImmediateNode(); } @Override public Object getImmediateNode() { return property; } @Override public Object getValue() { return property.getValue(); } @Override public boolean testNode(NodeTest nodeTest) { //debug("testNode", nodeTest); if (nodeTest != null) { if (nodeTest instanceof NodeTypeTest) { NodeTypeTest nodeTypeTest = (NodeTypeTest) nodeTest; return nodeTypeTest.getNodeType() == Compiler.NODE_TYPE_NODE; } } return false; } @Override public String asPath() { StringBuffer buffer = new StringBuffer(); buffer.append(parent.asPath()); if (buffer.length() == 0 || buffer.charAt(buffer.length() - 1) != '/') buffer.append('/'); buffer.append('@'); buffer.append(getName2()); return buffer.toString(); } @Override public int hashCode() { return property.hashCode(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; AstPropertyPointer other = (AstPropertyPointer) obj; if (!property.equals(other.property)) return false; return true; } @Override public void setValue(Object value) { throw new UnsupportedOperationException("Not supported yet."); } @Override public int compareChildNodePointers( NodePointer pointer1, NodePointer pointer2) { throw new UnsupportedOperationException( "Should not happen! Attributes don't have children."); } String getName2() { return property.getName(); } // ========================================================================= /* private void debug(String where, Object... params) { StringBuilder b = new StringBuilder(); String path = asPath(); b.append(String.format( "@%8x : %s : %s%s.%s ; ", System.identityHashCode(this), path, StringUtils.strrep(' ', 28 - path.length()), getClass().getSimpleName(), where)); int i = 0; for (Object o : params) { if (i++ != 0) b.append(", "); b.append(o == null ? "null" : o.toString()); } System.out.println(b.toString()); } */ } osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-xpath/src/test/000077500000000000000000000000001315622671000256415ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-xpath/src/test/java/000077500000000000000000000000001315622671000265625ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-xpath/src/test/java/de/000077500000000000000000000000001315622671000271525ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-xpath/src/test/java/de/fau/000077500000000000000000000000001315622671000277255ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-xpath/src/test/java/de/fau/cs/000077500000000000000000000000001315622671000303325ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-xpath/src/test/java/de/fau/cs/osr/000077500000000000000000000000001315622671000311355ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-xpath/src/test/java/de/fau/cs/osr/ptk/000077500000000000000000000000001315622671000317335ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-xpath/src/test/java/de/fau/cs/osr/ptk/common/000077500000000000000000000000001315622671000332235ustar00rootroot00000000000000jxpath/000077500000000000000000000000001315622671000344425ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-xpath/src/test/java/de/fau/cs/osr/ptk/commonDomXPathTest.java000066400000000000000000000057531315622671000376430ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-xpath/src/test/java/de/fau/cs/osr/ptk/common/jxpath/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common.jxpath; import java.io.IOException; import java.io.InputStream; import java.io.StringWriter; import java.util.Iterator; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.apache.commons.jxpath.JXPathContext; import org.apache.commons.jxpath.ri.model.NodePointer; import org.junit.Ignore; import org.junit.Test; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.xml.sax.SAXException; /** * This is not a real test case. It's just some code to get acquainted with * XPath idiosyncrasies. */ public class DomXPathTest { private static final boolean QUIET = true; private static TransformerFactory transformerFactory = null; private static Transformer transformer = null; @Test @Ignore public void test() throws ParserConfigurationException, SAXException, IOException, TransformerException { InputStream is = getClass().getResourceAsStream("/simple.xml"); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(is); JXPathContext context = JXPathContext.newContext(doc); printResult(context, "/*//*"); } private void printResult(JXPathContext context, String xpath) throws TransformerException { if (!QUIET) { System.out.println(); System.out.println("Query: " + xpath); } for (Iterator i = context.iteratePointers(xpath); i.hasNext();) { NodePointer o = (NodePointer) i.next(); if (!QUIET) { print((Node) o.getImmediateNode()); } } } private void print(Node node) throws TransformerException { if (transformerFactory == null) { transformerFactory = TransformerFactory.newInstance(); transformer = transformerFactory.newTransformer(); } StringWriter x = new StringWriter(); DOMSource source = new DOMSource(node); StreamResult result = new StreamResult(x); transformer.transform(source, result); System.out.println(x.toString().replaceAll("", "")); } } XPathTest.java000066400000000000000000000151441315622671000371760ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-xpath/src/test/java/de/fau/cs/osr/ptk/common/jxpath/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common.jxpath; import static de.fau.cs.osr.ptk.common.test.nodes.CtnBuilder.ctnDoc; import static de.fau.cs.osr.ptk.common.test.nodes.CtnBuilder.ctnId; import static de.fau.cs.osr.ptk.common.test.nodes.CtnBuilder.ctnSection; import static de.fau.cs.osr.ptk.common.test.nodes.CtnBuilder.ctnText; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.apache.commons.jxpath.JXPathContext; import org.apache.commons.jxpath.ri.JXPathContextReferenceImpl; import org.junit.Assert; import org.junit.Test; import de.fau.cs.osr.ptk.common.jxpath.AstPropertyIterator.Property; import de.fau.cs.osr.ptk.common.test.nodes.CtnNode; import de.fau.cs.osr.ptk.common.test.nodes.CtnSection; public class XPathTest { private static final boolean QUIET = true; // ========================================================================= private static final CtnSection AST1 = ctnSection() .withLevel(0) .withTitle(ctnText("1st")) .withBody( ctnText("2nd"), ctnId(3), ctnSection() .withLevel(1) .withTitle() .withBody() .build()) .build(); private static final CtnNode AST2 = ctnDoc( ctnSection() .withLevel(1) .withTitle() .withBody() .build(), ctnSection() .withLevel(2) .withTitle() .withBody() .build()); private static final CtnNode AST3 = ctnDoc( ctnText("1"), ctnId(2)); // ========================================================================= private JXPathContext context; // ========================================================================= public XPathTest() { JXPathContextReferenceImpl.addNodePointerFactory( new AstNodePointerFactory()); } // ========================================================================= @Test public void test01() { context = JXPathContext.newContext(AST1); runTest("/body/*[2]", AST1.getBody().get(1)); } @Test public void test02() { context = JXPathContext.newContext(AST1); runTest("/@*", AST1.getProperty("level")); } @Test public void test03() { context = JXPathContext.newContext(AST1); runTest("/*/*[2]", AST1.getBody().get(1)); } @Test public void test04() { context = JXPathContext.newContext(AST1); runTest("/body[last()-1]"); } @Test public void test05() { context = JXPathContext.newContext(AST1); runTest("/body/*[last()]", AST1.getBody().get(2)); } @Test public void test06() { context = JXPathContext.newContext(AST1); runTest("/body/text/@content", AST1.getBody().get(0).getProperty("content")); } @Test public void test07() { context = JXPathContext.newContext(AST1); runTest("/body/body[last()-1]"); } @Test public void test08() { context = JXPathContext.newContext(AST1); runTest("//@level", AST1.getProperty("level"), AST1.getBody().get(2).getProperty("level")); } @Test public void test09() { context = JXPathContext.newContext(AST1); runTest("/descendant-or-self::node()", AST1, AST1.getTitle(), AST1.getTitle().get(0), AST1.getBody(), AST1.getBody().get(0), AST1.getBody().get(1), AST1.getBody().get(2), AST1.getBody().get(2).get(0), AST1.getBody().get(2).get(1)); } @Test public void test10() { context = JXPathContext.newContext(AST1); runTest("/descendant-or-self::node()[@level]", AST1, AST1.getBody().get(2)); } @Test public void test11() { context = JXPathContext.newContext(AST1); runTest("/descendant-or-self::node()/*", AST1.getTitle(), AST1.getTitle().get(0), AST1.getBody(), AST1.getBody().get(0), AST1.getBody().get(1), AST1.getBody().get(2), AST1.getBody().get(2).get(0), AST1.getBody().get(2).get(1)); } @Test public void test12() { context = JXPathContext.newContext(AST1); runTest("/descendant-or-self::node()/*[@level]", AST1.getBody().get(2)); } @Test public void test13() { context = JXPathContext.newContext(AST1); runTest("//*[@level]", AST1.getBody().get(2)); } @Test public void test14() { context = JXPathContext.newContext(AST1); runTest("/body[last()]", AST1.getBody()); } @Test public void testPredicate01() { context = JXPathContext.newContext(AST2); runTest("/*[@level]", AST2.get(0), AST2.get(1)); } @Test public void testPredicate02() { context = JXPathContext.newContext(AST2); runTest("/*/@level", AST2.get(0).getProperty("level"), AST2.get(1).getProperty("level")); } @Test public void testPredicate03() { context = JXPathContext.newContext(AST3); runTest("//*[@content]", AST3.get(0)); } // ========================================================================= public void runTest(String xpath, Object... expected) { if (!QUIET) { System.out.println(); System.out.println("Query: " + xpath); } Map> e = new HashMap>(); for (Object o : expected) { List l = e.get(o); if (l == null) l = new ArrayList(); l.add(o); e.put(o, l); } Map> a = new HashMap>(); for (Iterator i = context.iterate(xpath); i.hasNext();) { Object o = i.next(); if (!QUIET) System.out.format(" - %s\n", o.toString()); if (o instanceof Property) o = ((Property) o).getValue(); List l = a.get(o); if (l == null) l = new ArrayList(); l.add(o); a.put(o, l); } Assert.assertEquals(e.size(), a.size()); contains(e, a); contains(a, e); } private void contains( Map> e, Map> a) { for (Entry> x : e.entrySet()) { Assert.assertNotNull(a.get(x.getKey())); Assert.assertEquals(a.get(x.getKey()).size(), x.getValue().size()); for (Object o : x.getValue()) Assert.assertTrue(a.get(o).contains(o)); } } } osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-xpath/src/test/resources/000077500000000000000000000000001315622671000276535ustar00rootroot00000000000000osr-common-osr-common-3.0.8/parser-toolkit-parent/ptk-xpath/src/test/resources/simple.xml000066400000000000000000000017151315622671000316720ustar00rootroot00000000000000
<Text content="1st"/>
osr-common-osr-common-3.0.8/pom.xml000066400000000000000000000036621315622671000172310ustar00rootroot00000000000000 4.0.0 de.fau.cs.osr tooling 3.0.8 ./tooling/ osr-common-aggregator pom Open Source Research Common Aggergator Project An aggregator project for the projects in the de.fau.cs.osr group of the Open Source Research Group. parser-toolkit-parent tooling utils-parent ./tooling/ true true true true true true osr-common-osr-common-3.0.8/tooling/000077500000000000000000000000001315622671000173605ustar00rootroot00000000000000osr-common-osr-common-3.0.8/tooling/bin/000077500000000000000000000000001315622671000201305ustar00rootroot00000000000000osr-common-osr-common-3.0.8/tooling/bin/generate-changelog000077500000000000000000000025261315622671000236020ustar00rootroot00000000000000#!/bin/bash # # Copyright 2011 The Open Source Research Group, # University of Erlangen-Nürnberg # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # set -ue msgFile="commit-msg.txt" subject="$@" if [[ -n "$subject" ]]; then echo "$subject" > "$msgFile" echo >> "$msgFile" echo >> "$msgFile" else rm -f "$msgFile" fi git submodule summary | grep -e '^\*' | while read subModule; do project=$(echo "$subModule" | sed -e 's/^\*\s\+\(\S\+\).*/\1/') commitRange=$(echo "$subModule" | sed -e 's/^\*\s\+\S\+\s\+\(\S\+\).*/\1/' | sed -e 's/^0\+\.\.\.//') echo "$subModule" pushd "$project" &>/dev/null echo "$subModule" >> ../"$msgFile" echo >> ../"$msgFile" git log --first-parent "$commitRange" | grep -ve '^Author:\|Date:\|Merge:' | sed -e 's/\(.*\)/ \1/' >> ../"$msgFile" echo >> ../"$msgFile" echo >> ../"$msgFile" popd &>/dev/null done osr-common-osr-common-3.0.8/tooling/bin/release000077500000000000000000000232301315622671000214760ustar00rootroot00000000000000#!/bin/bash # # Copyright 2011 The Open Source Research Group, # University of Erlangen-Nürnberg # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # set -ue # ------------------------------------------------------------------------------ # Defaults stage=${stage:-clean} localRepoId="temp-release-repo" localRepoPath="$HOME/$localRepoId" # ------------------------------------------------------------------------------ # Parse command line arguments while getopts "h?s:d:r:t:c:g:a:b:m:" opt; do case "$opt" in h|\?) echo "Usage: $( basename $0 ) [-h|-?] [-s ] [-r ] [-d ] [-t ] [-c ] [-g ] [-a ] [-b ] [-m ]" echo echo "Stages are:" echo " clean - Execute 'mvn clean'" echo " deploy-final-snapshot - Execute 'mvn deploy' on current branch" echo " switch-to-release-branch - Switch to release branch" echo " prepare-release - Have maven prepare the release" echo " perform-release - Have maven perform the release" echo " merge-release-tag-into-master - Merge release into master branch" echo " tag-release - Tag the release on the master branch (requires GPG)" echo " merge-release-into-develop - Merge release branch back into develop branch" echo " tag-develop - Tag the commit that continues the development branch (useful for 'git describe')" echo " deploy-initial-snapshot - Execute 'mvn deploy' on develop branch" echo " deploy-signed-release-locally - Test deploy artifacts locally (to $localRepoPath)" echo " deploy-signed-release - Execute 'mvn deploy' on release tag" echo " push-to-vcs - Push to remote (master, develop, tag, and development tag)" exit 0 ;; s) stage=$OPTARG ;; r) releaseVersion=$OPTARG ;; d) developmentVersion=$OPTARG ;; t) tag=$OPTARG ;; c) developTag=$OPTARG ;; g) gpgKeyName=$OPTARG ;; a) altDeploymentRepository=$OPTARG ;; b) developBranch=$OPTARG ;; m) masterBranch=$OPTARG ;; esac done shift $((OPTIND-1)) [ "${1:-}" = "--" ] && shift logFile=release.log # ------------------------------------------------------------------------------ # Helper functions readonly sep=$( printf '%*s\n' "${COLUMNS:-$(tput cols)}" '' | tr ' ' = ) function getPomField { q="from lxml.etree import parse; from sys import stdin;" q="${q}print ''.join(parse(stdin).xpath(" q="${q} '$1'," q="${q} namespaces={'x':'http://maven.apache.org/POM/4.0.0'}));" python -c "$q" < pom.xml } function assureGpgAgent { if [[ -z ${GPG_AGENT_INFO:-} ]]; then if [[ -z ${GNUPGHOME:-} ]]; then export GNUPGHOME=${HOME}/.gnupg fi export GPG_AGENT_INFO=${GNUPGHOME}/S.gpg-agent:0:1 fi } function logEcho { echo "$@" | tee -a $logFile } function logHeading { echo $sep >> $logFile echo "== $@" >> $logFile echo $sep >> $logFile } function logEchoHeading { logHeading "$@" echo "$@" } function logExec { echo >> $logFile echo ">> $@" >> $logFile "$@" >> $logFile 2> >(tee -a $logFile >&2) } function logCommandOnExec { echo >> $logFile echo ">> $@" >> $logFile "$@" } function askYesNo { while true; do read -p "$1 [y|n]: " -n 1 -r if [[ $REPLY =~ ^[YyNn]$ ]]; then break fi echo done } # ------------------------------------------------------------------------------ # Actual release process groupId=$( getPomField "/x:project/x:groupId/text()" ) artifactId=$( getPomField "/x:project/x:artifactId/text()" ) version=$( getPomField "/x:project/x:version/text()" ) logEcho logEcho "Current coordinates are: $groupId:$artifactId:$version" if [[ -z ${releaseVersion:-} ]] || [[ -z ${developmentVersion:-} ]]; then logEcho; fi if [[ -z ${releaseVersion:-} ]]; then read -p "Type the release version, followed by [ENTER]: " releaseVersion fi if [[ -z ${developmentVersion:-} ]]; then read -p "Type the new development version, followed by [ENTER]: " developmentVersion fi if [[ -z ${tag:-} ]]; then tag="$artifactId-$releaseVersion" fi if [[ -z ${developTag:-} ]]; then developTag="develop-$developmentVersion" fi if [[ -z ${developBranch:-} ]]; then developBranch="develop" fi if [[ -z ${masterBranch:-} ]]; then masterBranch="master" fi logEcho logEcho " release version : $releaseVersion" logEcho " development version : $developmentVersion" logEcho " release VCS tag : $tag" logEcho " development VCS tag : $developTag" logEcho " master branch : $masterBranch" logEcho " develop branch : $developBranch" logEcho " stage : $stage" logEcho " local repo path : $localRepoPath" if [[ -z ${altDeploymentRepository:-} ]]; then altDeploymentRepository="" else logEcho " alt. deployment repo. : $altDeploymentRepository" altDeploymentRepository="-DaltDeploymentRepository=${altDeploymentRepository}" fi logEcho askYesNo "Is this correct?" logEcho if [[ ! $REPLY =~ ^[Yy]$ ]]; then logEcho logEcho "Aborted" exit 1 fi case $stage in clean) logEcho logEchoHeading "Cleaning (maven)" logExec mvn clean ;& deploy-final-snapshot) logEcho askYesNo "Do you want to deploy a last snapshot?" logHeading "Do you want to deploy a last snapshot? [y|n]: " $REPLY logEcho logExec git checkout $developBranch if [[ $REPLY =~ ^[Yy]$ ]]; then logExec mvn deploy fi ;& switch-to-release-branch) logEcho logEchoHeading "Switching to release branch" logExec git checkout $developBranch logExec git checkout -b release ;& prepare-release) logEcho logEchoHeading "Preparing release" # We cannot log this since the release plugin often asks questions logExec git checkout release logCommandOnExec mvn -q release:prepare -DpushChanges=false \ -DreleaseVersion=${releaseVersion} \ -DdevelopmentVersion=${developmentVersion} \ -Dtag=${tag} ;& perform-release) logEcho logEchoHeading "Performing release to local repository: $localRepoPath" logExec mkdir -p $localRepoPath logExec mvn release:perform \ -DlocalCheckout=true \ -DpushChanges=false \ -Darguments=-DaltDeploymentRepository=${localRepoId}::default::file://${localRepoPath} ;& merge-release-tag-into-master) logEcho logEchoHeading "Merging release tag into $masterBranch branch" logExec git checkout $masterBranch logExec git merge --no-ff ${tag} ;& tag-release) assureGpgAgent logExec git checkout $masterBranch logExec git tag -d ${tag} logCommandOnExec git tag -u "$gpgKeyName" -m "Release $tag" ${tag} $masterBranch ;& merge-release-into-develop) logEcho logEchoHeading "Merging $masterBranch branch into $developBranch branch" logExec git checkout $developBranch logExec git merge --no-ff release logExec git branch -d release ;& tag-develop) logExec git checkout $developBranch logCommandOnExec git tag -a -m "Starting development on $developmentVersion" ${developTag} $developBranch ;& deploy-initial-snapshot) logEcho askYesNo "Do you want to deploy a first SNAPSHOT version?" logHeading "Do you want to deploy a first SNAPSHOT version? [y|n]: " $REPLY logEcho logExec git checkout $developBranch if [[ $REPLY =~ ^[Yy]$ ]]; then logExec mvn deploy fi ;& deploy-signed-release-locally) logEcho askYesNo "Do you want to deploy signed artifacts locally?" logHeading "Do you want to deploy signed artifacts locally? [y|n]: " $REPLY logEcho logExec git checkout $developBranch if [[ $REPLY =~ ^[Yy]$ ]]; then assureGpgAgent logExec git checkout -q ${tag} logExec mvn install deploy -Psign -Prelease \ -Dgpg.keyname=$gpgKeyName \ -DaltDeploymentRepository=${localRepoId}::default::file://${localRepoPath} fi ;& deploy-signed-release) assureGpgAgent logEcho askYesNo "Do you want to stage the release in the configured remote repository?" logHeading "Do you want to stage the release in the configured remote repository? [y|n]: " $REPLY logEcho logExec git checkout -q ${tag} if [[ $REPLY =~ ^[Yy]$ ]]; then if [[ ! -z "$altDeploymentRepository" ]]; then logExec mvn install deploy -Psign -Prelease -Dgpg.keyname=$gpgKeyName "$altDeploymentRepository" else logExec mvn install deploy -Psign -Prelease -Dgpg.keyname=$gpgKeyName fi fi ;& push-to-vcs) logEcho askYesNo "Do you want to push the new commits and the release tag to the repository?" logHeading "Do you want to push the new commits and the release tag to the repository? [y|n]: " $REPLY logEcho if [[ $REPLY =~ ^[Yy]$ ]]; then logExec git checkout $masterBranch logExec git push origin $masterBranch logExec git checkout $developBranch logExec git push origin $developBranch logExec git push origin ${tag} logExec git push origin ${developTag} fi ;& esac logEcho logHeading "Done." osr-common-osr-common-3.0.8/tooling/etc/000077500000000000000000000000001315622671000201335ustar00rootroot00000000000000osr-common-osr-common-3.0.8/tooling/etc/apache-license-v2-header.txt000066400000000000000000000011531315622671000253100ustar00rootroot00000000000000Copyright 2011 The Open Source Research Group, University of Erlangen-Nürnberg Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.osr-common-osr-common-3.0.8/tooling/etc/checkstyle.xml000066400000000000000000000244741315622671000230260ustar00rootroot00000000000000 osr-common-osr-common-3.0.8/tooling/etc/eclipse-formatter/000077500000000000000000000000001315622671000235605ustar00rootroot00000000000000osr-common-osr-common-3.0.8/tooling/etc/eclipse-formatter/README000066400000000000000000000031221315622671000244360ustar00rootroot00000000000000http://eclipse-n-mati.blogspot.ch/2015/06/eclipse-mars-how-to-switch-back-to.html Java code formatter in Eclipse 4.5 has been completely rewritten. There's a lot less of bugs, the behavior is more consistent, and line wrapping is a bit smarter. It also opens way to easier implementation of new improvements in the future. While most users will probably be happy with the new formatter, for some the changes may be unwelcome. Probably the most controversial change is a more restrictive approach to the "Never join already wrapped lines" option - a lot of line breaks that used to be tolerated by the old formatter, will be now removed if they don't fit the line wrapping settings. Also, some teams just don't want to force everyone to immediately switch to the newest Eclipse, so during the transition it would be problematic if part of the team used different formatter. If you also find that problems related to changed formatter behavior outweigh the benefits of bug fixes and improvements, you'll be glad to hear that Eclipse Mars has a new extension point for Java formatter. So it's easy to take the code of the old formatter and wrap it in a plugin. I did just that for your convenience, the plugin can be downloaded here. Although I tested it a bit, the plugin is provided "as is" and I take no responsibility for anything that happens because of it. Just unzip the provided jar into the "plugins" directory of your Eclipse installation, restart, and in the Preferences -> Code Style -> Formatter page select Formatter implementation: Old formatter. Happy formatting! Posted by Mateusz Matela at 1:26 AM osr-common-osr-common-3.0.8/tooling/etc/eclipse-formatter/profile.xml000066400000000000000000000747371315622671000257640ustar00rootroot00000000000000 osr-common-osr-common-3.0.8/tooling/etc/forbiddenapis.txt000066400000000000000000000000711315622671000235030ustar00rootroot00000000000000 # Deprecated. Use org.junit instead. junit.framework.** osr-common-osr-common-3.0.8/tooling/pom.xml000066400000000000000000001136321315622671000207030ustar00rootroot00000000000000 4.0.0 de.fau.cs.osr tooling 3.0.8 pom Tooling ${site-url} 2011 The parent project for all projects in the de.fau.cs.osr group of the Open Source Research Group. UTF-8 1.6 ${maven.compiler.source} ${project.basedir} ${tooling.path}/etc ${tooling.etc-path}/forbiddenapis.txt ${tooling.etc-path}/apache-license-v2-header.txt ${tooling.etc-path}/checkstyle.xml http://sweble.org ${maven-site-plugin.topSiteURL}/sites/${project.groupId}/${project.artifactId}/${project.version} ${project.build.outputDirectory}/${project.groupId}/${project.artifactId}/git.properties false false false false false false false false false false 2.5 3.1 2.8.1 2.18.1 2.4 2.6 3.5 2.16 2.4 2.4 2.9 2.9.1 2.3 2.9 2.16 2.2 2.4 2.17 2.10 1.4.1 1.4 2.4.1 1.6 2.2.1 2.9 1.7 1.8 1.2.1 2.7 2.0 2.1.12 2.5 1.3.2 1.9.4 1.0-beta-4 1.6 3.2.2 1.8.1 1.4 1.3 3.4 3.2 18.0 2.3 1.2.17 1.7.12 2.3.1 2.2.5 9.7.0-1 2.7.2 2.11.0 1.4.01 1.8.5 4.12 1.10.8 org.aspectj aspectjrt ${aspectj.version} commons-codec commons-codec ${commons-codec.version} commons-collections commons-collections ${commons-collections.version} org.apache.commons commons-compress ${commons-compress.version} commons-io commons-io ${commons-io.version} commons-jxpath commons-jxpath ${commons-jxpath.version} org.apache.commons commons-lang3 ${commons-lang3.version} org.apache.commons commons-math3 ${commons-math3.version} com.google.guava guava ${guava.version} joda-time joda-time ${joda-time.version} org.slf4j slf4j-api ${slf4j.version} org.slf4j slf4j-log4j12 ${slf4j.version} log4j log4j ${log4j.version} com.google.code.gson gson ${gson.version} com.sun.xml.bind jaxb-impl ${jaxb-impl.version} net.sf.saxon Saxon-HE ${Saxon-HE.version} xalan xalan ${xalan.version} xerces xercesImpl ${xercesImpl.version} xml-apis xml-apis ${xml-apis.version} junit junit ${junit.version} org.hamcrest hamcrest-core 1.3 org.mockito mockito-core ${mockito.version} de.thetaphi forbiddenapis pl.project13.maven git-commit-id-plugin com.mycila license-maven-plugin maven-checkstyle-plugin maven-dependency-plugin maven-enforcer-plugin maven-site-plugin attach-site-descriptor attach-descriptor false maven-clean-plugin ${maven-clean-plugin.version} maven-compiler-plugin ${maven-compiler-plugin.version} ${maven.compiler.source} ${maven.compiler.target} -deprecation maven-deploy-plugin ${maven-deploy-plugin.version} ${maven-deploy-plugin.skip} maven-failsafe-plugin ${maven-failsafe-plugin.version} maven-install-plugin ${maven-install-plugin.version} ${maven-install-plugin.skip} maven-resources-plugin ${maven-resources-plugin.version} maven-site-plugin ${maven-site-plugin.version} ${maven-site-plugin.skip} ${maven-site-plugin.topSiteURL} maven-surefire-plugin ${maven-surefire-plugin.version} false true maven-jar-plugin ${maven-jar-plugin.version} true true maven-war-plugin ${maven-war-plugin.version} true true maven-changes-plugin ${maven-changes-plugin.version} maven-javadoc-plugin ${maven-javadoc-plugin.version} true ${javadoc.opts} maven-jxr-plugin ${maven-jxr-plugin.version} maven-project-info-reports-plugin ${maven-project-info-reports-plugin.version} maven-surefire-report-plugin ${maven-surefire-report-plugin.version} maven-archetype-plugin ${maven-archetype-plugin.version} maven-assembly-plugin ${maven-assembly-plugin.version} maven-checkstyle-plugin ${maven-checkstyle-plugin.version} ${maven-checkstyle-plugin.skip} ${maven-checkstyle-plugin.config} UTF-8 true true false check-code-style validate check maven-dependency-plugin ${maven-dependency-plugin.version} analyze-dependency-usage verify analyze-only ${maven-dependency-plugin.skip} true maven-enforcer-plugin ${maven-enforcer-plugin.version} ${maven-enforcer-plugin.skip} enforce-ban-version-downgrades validate enforce true true true clean,deploy,site enforce-ban-duplicate-classes verify enforce true true org.codehaus.mojo extra-enforcer-rules ${extra-enforcer-rules.version} maven-gpg-plugin ${maven-gpg-plugin.version} true maven-release-plugin ${maven-release-plugin.version} deploy ${maven-release-plugin.skip} org.apache.maven.scm maven-scm-provider-gitexe ${maven-scm-provider-gitexe.version} maven-shade-plugin ${maven-shade-plugin.version} maven-source-plugin ${maven-source-plugin.version} maven-eclipse-plugin ${maven-eclipse-plugin.version} org.eclipse.m2e lifecycle-mapping 1.0.0 org.apache.maven.plugins maven-checkstyle-plugin [0,) check org.codehaus.mojo build-helper-maven-plugin ${build-helper-maven-plugin.version} org.codehaus.mojo aspectj-maven-plugin ${aspectj-maven-plugin.version} org.aspectj aspectjtools ${aspectj.version} ${maven.compiler.source} ${maven.compiler.source} ${maven.compiler.target} compile org.codehaus.mojo exec-maven-plugin ${exec-maven-plugin.version} de.thetaphi forbiddenapis ${forbiddenapis-plugin.version} ${forbiddenapis-plugin.skip} true false jdk-deprecated ${forbiddenapis-plugin.signatures} check-for-forbidden-apis verify check testCheck pl.project13.maven git-commit-id-plugin ${git-commit-id-plugin.version} ${git-commit-id-plugin.skip} true ${git-commit-id-plugin.properties-filename} true gather-git-information initialize revision com.mycila license-maven-plugin ${license-maven-plugin.version} ${license-maven-plugin.skip}
${license-maven-plugin.header}
true true bin/* tooling etc/checkstyle.xml etc/forbiddenapis.txt etc/eclipse-formatter/** **/LICENSE **/NOTICE **/README **/README.md **/*.log **/.gitignore
check-licenses verify check
com.google.code.maven-replacer-plugin maven-replacer-plugin ${maven-replacer-plugin.version}
true maven-changes-plugin ${project.basedir}/src/site/changes.xml changes-report maven-javadoc-plugin true ${javadoc.opts} site-javadoc javadoc maven-jxr-plugin maven-project-info-reports-plugin maven-surefire-report-plugin The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt repo University of Erlangen-Nürnberg - Open Source Research Group http://osr.cs.fau.de driehle Dirk Riehle dirk.riehle@fau.de Director University of Erlangen-Nürnberg - Open Source Research Group +1 hdohrn Hannes Dohrn hannes.dohrn@fau.de Developer University of Erlangen-Nürnberg - Open Source Research Group +1 GitHub https://github.com/sweble/osr-common/issues scm:git://git@github.com/sweble/osr-common.git scm:git://git@mojo-forge.cs.fau.de/sweble-public/osr-common.git https://github.com/sweble/osr-common osr-common-3.0.8 true true daily warn osr-public-repository OSR Public Repository http://mojo-maven.cs.fau.de/content/repositories/public true true daily warn osr-public-plugin-repository OSR Public Plugin Repository http://mojo-maven.cs.fau.de/content/repositories/public sonatype-nexus-staging Sonatype Nexus Staging https://oss.sonatype.org/service/local/staging/deploy/maven2 osr-public-snapshots-deployment OSR Public Snapshots Deployment http://mojo-maven.cs.fau.de/content/repositories/public-snapshots default-site Default Site ${site-url} quick true true true true true true true true maven-changes-plugin maven-javadoc-plugin true ${javadoc.opts} maven-jxr-plugin true maven-project-info-reports-plugin index summary maven-surefire-report-plugin true release maven-javadoc-plugin attach-javadoc-jar package jar true ${javadoc.opts} maven-source-plugin attach-sources-jar package jar-no-fork maven-deploy-plugin deploy deploy deploy sign maven-gpg-plugin sign-artifacts verify sign disable-checkstyle-plugin-for-tooling-module tooling true java8-doclint-disabled [1.8,) -Xdoclint:none
osr-common-osr-common-3.0.8/tooling/src/000077500000000000000000000000001315622671000201475ustar00rootroot00000000000000osr-common-osr-common-3.0.8/tooling/src/site/000077500000000000000000000000001315622671000211135ustar00rootroot00000000000000osr-common-osr-common-3.0.8/tooling/src/site/site.xml000066400000000000000000000026731315622671000226110ustar00rootroot00000000000000 org.apache.maven.skins maven-fluido-skin 1.5 osr-common-osr-common-3.0.8/tooling/tooling000066400000000000000000000000651315622671000207570ustar00rootroot00000000000000This file helps maven to identify the tooling module.osr-common-osr-common-3.0.8/utils-parent/000077500000000000000000000000001315622671000203345ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/pom.xml000066400000000000000000000073261315622671000216610ustar00rootroot00000000000000 4.0.0 de.fau.cs.osr tooling 3.0.8 ../tooling/ de.fau.cs.osr.utils utils-parent pom Utils Parent POM 2016 An aggregator project for the projects in the de.fau.cs.osr.utils group of the Open Source Research Group. utils utils-getopt utils-testing ../tooling/ true 3.0.8 de.fau.cs.osr.utils utils ${osr-common.version} jenkins env.BUILD_NUMBER org.codehaus.mojo cobertura-maven-plugin ${cobertura-maven-plugin.version} xml true true package cobertura osr-common-osr-common-3.0.8/utils-parent/utils-getopt/000077500000000000000000000000001315622671000227745ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils-getopt/pom.xml000066400000000000000000000050161315622671000243130ustar00rootroot00000000000000 4.0.0 de.fau.cs.osr.utils utils-parent 3.0.8 utils-getopt jar Utils GetOpt 2016 Utility classes for parsing command line options. ../../tooling/ 4.3 net.sf.jopt-simple jopt-simple ${jopt-simple.version} de.fau.cs.osr.utils utils junit junit test osr-common-osr-common-3.0.8/utils-parent/utils-getopt/src/000077500000000000000000000000001315622671000235635ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils-getopt/src/main/000077500000000000000000000000001315622671000245075ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils-getopt/src/main/java/000077500000000000000000000000001315622671000254305ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils-getopt/src/main/java/de/000077500000000000000000000000001315622671000260205ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils-getopt/src/main/java/de/fau/000077500000000000000000000000001315622671000265735ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils-getopt/src/main/java/de/fau/cs/000077500000000000000000000000001315622671000272005ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils-getopt/src/main/java/de/fau/cs/osr/000077500000000000000000000000001315622671000300035ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils-getopt/src/main/java/de/fau/cs/osr/utils/000077500000000000000000000000001315622671000311435ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils-getopt/src/main/java/de/fau/cs/osr/utils/getopt/000077500000000000000000000000001315622671000324455ustar00rootroot00000000000000Configuration.java000066400000000000000000000222701315622671000360430ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils-getopt/src/main/java/de/fau/cs/osr/utils/getopt/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.utils.getopt; import java.io.PrintStream; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.StringTokenizer; import de.fau.cs.osr.utils.FmtIllegalArgumentException; import joptsimple.OptionSet; import joptsimple.internal.ColumnarData; public class Configuration { private final Map options = new HashMap(); private final Map properties = new HashMap(); private final Properties propSet = new Properties(); private OptionSet optSet; // ========================================================================= protected void add(OptionState optionState) { for (String name : optionState.getNames()) options.put(name, optionState); properties.put(optionState.getPropertyKey(), optionState); } public void setOptionSet(OptionSet optSet) { this.optSet = optSet; } public void loadProperties(Properties p) { for (Object key : p.keySet()) { OptionState option = properties.get(key); if (option == null || option.isFixed()) throw new UnrecognizedPropertyException((String) key); } propSet.putAll(p); } // ========================================================================= protected OptionState updateState(char shortOpt) { OptionState state = getOptByShort(shortOpt); state.setValid(true); return state; } protected OptionState updateState(String longOpt) { OptionState state = getOptByName(longOpt); state.setValid(true); return state; } protected void checkForInvalidOptions() throws IllegalOptionException { if (optSet == null) return; for (OptionState state : options.values()) { if (optSet.has(state.getSpec()) && !state.isValid()) throw new IllegalOptionException(state.formatNames()); } } private OptionState getOptByShort(char shortOpt) { OptionState state = options.get(String.valueOf(shortOpt)); if (state == null) throw new FmtIllegalArgumentException( "Short option `%s' was not specified.", String.valueOf(shortOpt)); return state; } private OptionState getOptByName(String name) { OptionState state = get(name); if (state == null) throw new FmtIllegalArgumentException( "Option or property key `%s' was not specified.", name); return state; } private OptionState get(String option) { OptionState o = options.get(option); if (o != null) return o; return properties.get(option); } // ========================================================================= public boolean has(String option) { OptionState o = getOptByName(option); if (optSet != null && optSet.has(o.getSpec())) return true; if (o.getPropertyKey() != null && propSet.containsKey(o.getPropertyKey())) return true; return false; } public String valueOf(String option) { OptionState o = getOptByName(option); String value = valueOfNoDefault(o); if (value != null) return value; return o.getSafeDefaultValue(); } public String valueOf(String option, String default_) { String value = valueOfNoDefault(option); if (value != null) return value; return default_; } public String valueOfNoDefault(String option) { return valueOfNoDefault(getOptByName(option)); } private String valueOfNoDefault(OptionState o) { String value = null; if (optSet != null && o.getSpec() != null) { value = (String) optSet.valueOf(o.getSpec()); if (value != null) return value; } if (o.getPropertyKey() != null) { value = propSet.getProperty(o.getPropertyKey()); if (value != null) return value; } return null; } public List valuesOf(String option) { OptionState o = getOptByName(option); List values = valuesOfNoDefault(o); if (values != null) return values; return o.getSafeDefaultValues(); } @SuppressWarnings("unchecked") private List valuesOfNoDefault(OptionState o) { List values = null; if (optSet != null) { values = (List) optSet.valuesOf(o.getSpec()); if (values != null) return values; } if (o.getPropertyKey() != null) { values = propToList(o); if (values != null) return values; } return null; } private List propToList(OptionState o) { String value = propSet.getProperty(o.getPropertyKey()); StringTokenizer lexer = new StringTokenizer(value, o.getSafeDelim()); List values = new ArrayList(); while (lexer.hasMoreTokens()) values.add(lexer.nextToken()); return values; } public List nonOptionArguments() { if (optSet != null) return optSet.nonOptionArguments(); return Collections.emptyList(); } public Properties propertySubset(String prefix) { if (!prefix.endsWith(".")) prefix = prefix + "."; int beginIndex = prefix.length(); Properties subset = new Properties(); for (OptionState o : properties.values()) { String key = o.getPropertyKey(); if (key == null) continue; if (!key.startsWith(prefix)) continue; String value = valueOfNoDefault(o); if (value == null) value = o.getSafeDefaultValue(); if (value != null) { String newKey = key.substring(beginIndex); subset.setProperty(newKey, value); } } return subset; } // ========================================================================= public void propertiesHelp(PrintStream out) { ColumnarData grid = new ColumnarData("Property key", "Description"); ArrayList list = new ArrayList(); for (OptionState s : properties.values()) { if (s.getPropertyKey() != null) list.add(s); } Collections.sort(list, new Comparator() { @Override public int compare(OptionState o1, OptionState o2) { return o1.getPropertyKey().compareTo(o2.getPropertyKey()); } }); for (OptionState o : list) { if (o.isFixed()) continue; // -- left column StringBuilder name = new StringBuilder(); name.append(o.getPropertyKey()); if (o.getArgName() != null && !o.getArgName().isEmpty()) { name.append("=<"); name.append(o.getArgName()); name.append('>'); } // -- right column StringBuilder desc = new StringBuilder(); desc.append(o.getDescription()); // -- right column - see also boolean sa = false; if (o.getNames() != null && !o.getNames().isEmpty()) { desc.append(" (see also: "); boolean first = true; for (String n : o.getNames()) { if (!first) desc.append(", "); desc.append(n.length() == 1 ? "-" : "--"); desc.append(n); first = false; } sa = true; } // -- right column - default values List defaults = o.getSafeDefaultValues(); if (defaults != null && !defaults.isEmpty()) { desc.append(sa ? "; " : " ("); desc.append("default: "); boolean first = true; boolean hasDelim = !o.getSafeDelim().equals("\u0000"); for (String d : defaults) { if (!first && hasDelim) desc.append(o.getSafeDelim()); desc.append(d); first = false; } desc.append(")"); } else if (sa) { desc.append(")"); } grid.addRow(name.toString(), desc.toString()); } out.print(grid.format()); } // ========================================================================= public void fixedOptionsHelp(PrintStream out) { ColumnarData grid = new ColumnarData("Name", "Description"); ArrayList list = new ArrayList(); for (OptionState s : properties.values()) { if (s.isFixed()) list.add(s); } Collections.sort(list, new Comparator() { @Override public int compare(OptionState o1, OptionState o2) { return o1.getPropertyKey().compareTo(o2.getPropertyKey()); } }); for (OptionState o : list) { if (!o.isFixed()) continue; // -- left column StringBuilder name = new StringBuilder(); name.append(o.getPropertyKey()); // -- left column: value List defaults = o.getSafeDefaultValues(); if (defaults != null && !defaults.isEmpty()) { name.append("="); boolean first = true; boolean hasDelim = !o.getSafeDelim().equals("\u0000"); for (String d : defaults) { if (!first && hasDelim) name.append(o.getSafeDelim()); name.append(d); first = false; } } // -- right column String desc = o.getDescription() != null ? o.getDescription() : "-"; // -- right column - default values grid.addRow(name.toString(), desc); } out.print(grid.format()); } } Converter.java000066400000000000000000000014231315622671000352000ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils-getopt/src/main/java/de/fau/cs/osr/utils/getopt/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.utils.getopt; public interface Converter { public T convert(String option, String value); } ExpectedOneOfOptionException.java000066400000000000000000000022141315622671000407700ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils-getopt/src/main/java/de/fau/cs/osr/utils/getopt/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.utils.getopt; import java.util.Arrays; import joptsimple.OptionException; public class ExpectedOneOfOptionException extends OptionException { private static final long serialVersionUID = 2789906429506224185L; public ExpectedOneOfOptionException(String[] longOpts) { super(Arrays.asList(longOpts)); } @Override public String getMessage() { return "One and only one of the following " + "options has to be specified: " + multipleOptionMessage(); } } FailedConversionException.java000066400000000000000000000027251315622671000403500ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils-getopt/src/main/java/de/fau/cs/osr/utils/getopt/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.utils.getopt; import java.util.Arrays; import joptsimple.OptionException; public class FailedConversionException extends OptionException { private static final long serialVersionUID = -5076229021503080077L; private final String value; private final Class clazz; // ========================================================================= public FailedConversionException(String option, String value, Class clazz) { super(Arrays.asList(option)); this.value = value; this.clazz = clazz; } // ========================================================================= @Override public String getMessage() { return String.format( "Conversion of value `%s' to type `%s' failed for option: %s", value, clazz.getSimpleName(), singleOptionMessage()); } } IllegalOptionArgumentException.java000066400000000000000000000030421315622671000413540ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils-getopt/src/main/java/de/fau/cs/osr/utils/getopt/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.utils.getopt; import java.util.List; import joptsimple.OptionException; public class IllegalOptionArgumentException extends OptionException { private static final long serialVersionUID = -5076229021503080077L; private String illegalArgument; // ========================================================================= public IllegalOptionArgumentException( List illegalOptions, String illegalArgument) { super(illegalOptions); this.illegalArgument = illegalArgument; } // ========================================================================= public String getIllegalArgument() { return illegalArgument; } // ========================================================================= @Override public String getMessage() { return "Argument `" + illegalArgument + "' is not allowed for option " + multipleOptionMessage(); } } IllegalOptionException.java000066400000000000000000000024501315622671000376530ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils-getopt/src/main/java/de/fau/cs/osr/utils/getopt/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.utils.getopt; import java.util.List; import joptsimple.OptionException; public class IllegalOptionException extends OptionException { private static final long serialVersionUID = -5076229021503080077L; // ========================================================================= public IllegalOptionException(List illegalOptions) { super(illegalOptions); } // ========================================================================= @Override public String getMessage() { return "The given combination of options does not allow for the " + "following option " + multipleOptionMessage(); } } MissingOptionException.java000066400000000000000000000021171315622671000377130ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils-getopt/src/main/java/de/fau/cs/osr/utils/getopt/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.utils.getopt; import java.util.List; import joptsimple.OptionException; public class MissingOptionException extends OptionException { private static final long serialVersionUID = 8750899610789962547L; public MissingOptionException(List missingOptions) { super(missingOptions); } @Override public String getMessage() { return "Missing required option " + multipleOptionMessage(); } } OptionBuilder.java000066400000000000000000000104541315622671000360140ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils-getopt/src/main/java/de/fau/cs/osr/utils/getopt/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.utils.getopt; import java.util.ArrayList; import java.util.List; import joptsimple.ArgumentAcceptingOptionSpec; import joptsimple.OptionParser; import joptsimple.OptionSpec; import joptsimple.OptionSpecBuilder; public final class OptionBuilder { private char shortOpt = 0; private String longOpt = null; private String description = null; private String argName = null; private boolean optionalArg = false; private boolean requiredArg = false; private char valueSep = 0; private String propertyKey = null; private boolean isFixed = false; private String[] defaultValues = null; // ========================================================================= private final Configuration config; private final OptionParser optionParser; public OptionBuilder(Configuration config, OptionParser optionParser) { this.config = config; this.optionParser = optionParser; } // ========================================================================= public void create() throws IllegalArgumentException { List names = new ArrayList(); OptionSpec spec = null; String delim = "\u0000"; boolean hasCmdLine = (shortOpt != 0 || longOpt != null); if (!hasCmdLine && propertyKey == null) throw new IllegalArgumentException( "must specify either short option, long option or property key"); if (!isFixed && hasCmdLine) { if (shortOpt != 0) names.add(String.valueOf(shortOpt)); if (longOpt != null) names.add(longOpt); OptionSpecBuilder builder = optionParser.acceptsAll(names, description); spec = builder; ArgumentAcceptingOptionSpec aaSpec = null; if (optionalArg) { aaSpec = builder.withOptionalArg(); } else if (requiredArg) { aaSpec = builder.withRequiredArg(); } if (aaSpec != null) { spec = aaSpec; if (argName != null) aaSpec.describedAs(argName); if (valueSep != 0) { aaSpec.withValuesSeparatedBy(valueSep); delim = String.valueOf(valueSep); } if (defaultValues != null) aaSpec.defaultsTo(defaultValues); } } config.add(new OptionState( spec, names, propertyKey, isFixed, defaultValues, delim, argName, description)); } // ========================================================================= public OptionBuilder withShortOpt(char shortOpt) { this.shortOpt = shortOpt; return this; } public OptionBuilder withLongOpt(String longOpt) { this.longOpt = longOpt; return this; } public OptionBuilder withDescription(String description) { this.description = description; return this; } public OptionBuilder withValueSeparator(char valueSep) { this.valueSep = valueSep; return this; } public OptionBuilder withRequiredArg() { this.requiredArg = true; this.optionalArg = false; return this; } public OptionBuilder hasOptionalArg() { this.requiredArg = false; this.optionalArg = true; return this; } public OptionBuilder withArgName(String name) { this.argName = name; return this; } public OptionBuilder withPropertyKey(String propertyKey) { this.propertyKey = propertyKey; return this; } public OptionBuilder withDefault(String[] values) { this.defaultValues = values; return this; } public OptionBuilder withDefault(String value, String... values) { int len = 1; if (values != null) len += values.length; this.defaultValues = new String[len]; int i = 0; this.defaultValues[i++] = value; if (values != null) { for (String v : values) this.defaultValues[i++] = v; } return this; } protected OptionBuilder withIsFixed() { this.isFixed = true; return this; } } OptionEnum.java000066400000000000000000000014011315622671000353220ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils-getopt/src/main/java/de/fau/cs/osr/utils/getopt/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.utils.getopt; public interface OptionEnum { public String getOptionName(); } OptionState.java000066400000000000000000000057601315622671000355120ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils-getopt/src/main/java/de/fau/cs/osr/utils/getopt/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.utils.getopt; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import joptsimple.OptionSpec; final class OptionState { private final OptionSpec spec; private final List names; private final String propertyKey; private final boolean isFixed; private final String[] defaultValues; private final String delim; private final String argName; private final String description; // ========================================================================= private boolean valid = false; // ========================================================================= public OptionState( OptionSpec spec, List names, String propertyKey, boolean isFixed, String[] defaultValues, String delim, String argName, String description) { this.names = names; this.propertyKey = propertyKey; this.isFixed = isFixed; this.spec = spec; this.defaultValues = defaultValues; this.delim = delim; this.argName = argName; this.description = description; } // ========================================================================= public boolean isValid() { return valid; } public void setValid(boolean valid) { this.valid = valid; } // ========================================================================= public List getNames() { return names; } public String getPropertyKey() { return propertyKey; } public OptionSpec getSpec() { return spec; } public boolean isFixed() { return isFixed; } public String getSafeDefaultValue() { if (defaultValues != null) { List values = Arrays.asList(defaultValues); if (!values.isEmpty()) return values.get(0); } return null; } public List getSafeDefaultValues() { if (defaultValues == null) return Collections.emptyList(); return Arrays.asList(defaultValues); } public String getSafeDelim() { return delim; } public String getArgName() { return argName; } public String getDescription() { return description; } public List formatNames() { List result = new ArrayList(); if (names != null) { for (String n : names) result.add((n.length() == 1 ? "-" : "--") + n); } if (propertyKey != null) result.add(propertyKey); return result; } } Options.java000066400000000000000000000367331315622671000347000ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils-getopt/src/main/java/de/fau/cs/osr/utils/getopt/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.utils.getopt; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import de.fau.cs.osr.utils.FmtIllegalArgumentException; import joptsimple.OptionParser; public final class Options { private final OptionParser optionParser = new OptionParser(); private final Configuration config = new Configuration(); private final Map, Converter> converters = new HashMap, Converter>(); private boolean quiet = false; // ========================================================================= public Options() { Converter strConv = new Converter() { @Override public String convert(String option, String value) { return value; } }; addConverter(String.class, strConv); Converter intConv = new Converter() { @Override public Integer convert(String option, String value) { try { return Integer.parseInt(value); } catch (NumberFormatException e) { throw new FailedConversionException( option, value, Integer.class); } } }; addConverter(Integer.class, intConv); addConverter(int.class, intConv); Converter boolConv = new Converter() { @Override public Boolean convert(String option, String value) { if (value == null) return true; String cmp = value.trim().toLowerCase(); return cmp.equals("true") || cmp.equals("yes") || cmp.equals("1"); } }; addConverter(Boolean.class, boolConv); addConverter(boolean.class, boolConv); } // ========================================================================= /** * Start creation of an option with only a short name. * * @param shortOpt * The short name of the option. * @return An OptionBuilder object. You have to call .create() on this * object to actually create the option. */ public OptionBuilder createOption(char shortOpt) { return new OptionBuilder(config, optionParser).withShortOpt(shortOpt); } /** * Start creation of an option with only a long name. * * @param longOpt * The long name of the option. * @return An OptionBuilder object. You have to call .create() on this * object to actually create the option. */ public OptionBuilder createOption(String longOpt) { return new OptionBuilder(config, optionParser).withLongOpt(longOpt); } /** * Start creation of an option with both short and long name. * * @param shortOpt * The short name of the option. * @param longOpt * The long name of the option. * @return An OptionBuilder object. You have to call .create() on this * object to actually create the option. */ public OptionBuilder createOption(char shortOpt, String longOpt) { return new OptionBuilder(config, optionParser) .withShortOpt(shortOpt) .withLongOpt(longOpt); } /** * Start creation of an option that can only be specified in a properties * file but not on the command line. * * @param propertyKey * The key (name) of the property. * @return An OptionBuilder object. You have to call .create() on this * object to actually create the option. */ public OptionBuilder createPropertyOnlyOption(String propertyKey) { return new OptionBuilder(config, optionParser) .withPropertyKey(propertyKey); } /** * Create an option with a fixed value. The user cannot override this option * on the command line or in a properties file. * * @param name * The name of the option. The name is used as long name and * property key. * @param value * The fixed value of this option. */ public void createFixedValueOption(String name, String value) { new OptionBuilder(config, optionParser) .withIsFixed() .withLongOpt(name) .withPropertyKey(name) .withRequiredArg() .withDefault(value) .create(); } // ========================================================================= /** * Whether this Options object prints warning messages on the console. */ public boolean isQuiet() { return quiet; } /** * Set whether this Options object shall print warning message on the * console. */ public void setQuiet(boolean quiet) { this.quiet = quiet; } // ========================================================================= /** * Parse a command line after specifying all possible options. */ public void parse(String[] args) { config.setOptionSet(optionParser.parse(args)); } /** * Merge given properties. */ public void load(Properties properties) { config.loadProperties(properties); } /** * Load options from input stream. */ public void load(FileInputStream inputStream) throws IOException { Properties p = new Properties(); p.load(inputStream); load(p); } /** * Load options from properties file. */ public void load(File file) throws IOException { FileInputStream is = new FileInputStream(file); try { load(is); } finally { is.close(); } } /** * Print a help message after specifying all possible options. * * @param sink * Where to print the help message to. * * @deprecated Use cmdLineHelp() instead. */ public void help(PrintStream sink) { cmdLineHelp(sink); } /** * Print a help message after specifying all possible options. * * @param sink * Where to print the help message to. */ public void cmdLineHelp(OutputStream sink) { try { optionParser.printHelpOn(sink); } catch (IOException e) { throw new RuntimeException("Printing help message failed", e); } } /** * Print a help message after specifying all possible property keys. * * @param out * Where to print the help message to. */ public void propertiesHelp(PrintStream out) { config.propertiesHelp(out); } /** * Print a help message after specifying all possible fixed options. * * @param out * Where to print the help message to. */ public void fixedOptionsHelp(PrintStream out) { config.fixedOptionsHelp(out); } /** * Tell whether an options was specified on the command line or in a * properties file. This method only returns true if the option was actually * specified. If it was not specified but has a default value, this method * still returns false. * * @param option * The name of the options to query. This can be either the short * or long name or the property key of this option. */ public boolean has(String option) { return config.has(option); } /** * Return the value of an option. First the value is searched on the command * line. Then the properties are scanned. And finally, if the option has a * default value, the default value will be returned. If none of the * aforementioned sources can provide a value, null is returned. * * @param option * The name of the options to query. This can be either the short * or long name or the property key of this option. */ public String value(String option) { return config.valueOf(option); } /** * Return the value of an option. First the value is searched on the command * line. Then the properties are scanned. If none of the aforementioned * sources can provide a value, the default value given as parameter is * returned. * * @param option * The name of the options to query. This can be either the short * or long name or the property key of this option. * @param default_ * The default value to use if neither the command line nor * properties can provide a value. */ public String value(String option, String default_) { return config.valueOf(option, default_); } public T value(String option, Class clazz) { return convert(option, value(option), clazz); } public T value(String option, Class clazz, T default_) { T value = default_; if (has(option)) value = convert(option, config.valueOfNoDefault(option), clazz); return value; } public String[] values(String option) { return config.valuesOf(option).toArray(new String[0]); } public List getFreeArguments() { return config.nonOptionArguments(); } public Properties propertySubset(String prefix) { return config.propertySubset(prefix); } // ========================================================================= @SuppressWarnings("unchecked") public Converter addConverter(Class clazz, Converter converter) { return (Converter) converters.put(clazz, converter); } // ========================================================================= /** * Assert that an expected short option was given on the command line. This * method also fails if the option was not given but had a default value. * * @throws MissingOptionException */ public void expected(char shortOpt) throws MissingOptionException { OptionState state = config.updateState(shortOpt); if (!config.has(String.valueOf(shortOpt))) throw new MissingOptionException(state.formatNames()); } /** * Assert that an expected long option was given on the command line or * found in a properties file. This method also fails if the option was not * given but had a default value. * * @param name * The name of the long option or the property key. * * @throws MissingOptionException */ public void expected(String name) throws MissingOptionException { OptionState state = config.updateState(name); if (!config.has(name)) throw new MissingOptionException(state.formatNames()); } /** * Assert that exactly one of a set of expected long options was given on * the command line or found in a properties file. * * @param names * The names of the long options or the property keys. * * @throws MissingOptionException */ public String expectedOneOf(String... names) throws ExpectedOneOfOptionException { int found = 0; String last = null; for (String name : names) { config.updateState(name); if (config.has(name)) { ++found; last = name; } } if (found != 1) throw new ExpectedOneOfOptionException(names); return last; } /** * Indicate that a short option is optional. This becomes important when * calling checkForInvalidOptions() to check for unexpected options on the * command line. */ public void optional(char shortOpt) { config.updateState(shortOpt); } /** * Indicate that a long option option is optional. This becomes important * when calling checkForInvalidOptions() to check for unexpected options on * the command line. * * Note that while certain options can be required (see expected()) in * properties files as well, all non-required properties are automatically * optional. Therefore this method does not affect the options defined in * properties files. */ public void optional(String longOpt) { config.updateState(longOpt); } /** * Indicate that a short option is ignored. This becomes important when * calling checkForInvalidOptions() to check for unexpected options on the * command line. * * This method also prints a warning to stderr if the option was given on * the command line. */ public void ignore(char shortOpt) { ignore(shortOpt, false); } /** * Indicate that a short option is ignored. This becomes important when * calling checkForInvalidOptions() to check for unexpected options on the * command line. * * This method also prints a warning to stderr if the option was given on * the command line. * * @param quiet * Supress the warning message. */ public void ignore(char shortOpt, boolean quiet) { if (!quiet && !this.quiet && config.has(String.valueOf(shortOpt))) System.err.format("Option `%c' is ignored!\n", shortOpt); config.updateState(shortOpt); } /** * Indicate that a long option or property key is ignored. This becomes * important when calling checkForInvalidOptions() to check for unexpected * options on the command line. It is not required for properties. * * This method also prints a warning to stderr if the option was given on * the command line or defined in a properties file. */ public void ignore(String name) { ignore(name, false); } /** * Indicate that a long option or property key is ignored. This becomes * important when calling checkForInvalidOptions() to check for unexpected * options on the command line. It is not required for properties. * * This method also prints a warning to stderr if the option was given on * the command line or defined in a properties file. * * @param quiet * Supress the warning message. */ public void ignore(String name, boolean quiet) { if (!quiet && !this.quiet && config.has(name)) System.err.format("Option `%s' is ignored!\n", name); config.updateState(name); } /** * Assert that a given short option's value is one of given set. * * @throws IllegalOptionArgumentException */ public > E optionOneOf(char shortOpt, Class enum_) throws IllegalOptionArgumentException { return optionOneOf(String.valueOf(shortOpt), enum_); } /** * Assert that a given long option or property's value is one of given set. * * @throws IllegalOptionArgumentException */ @SuppressWarnings("unchecked") public > E optionOneOf(String name, Class enum_) throws IllegalOptionArgumentException { OptionState state = config.updateState(name); String value = (String) config.valueOf(name); if (value == null) throw new MissingOptionException(state.formatNames()); E[] values; try { values = (E[]) enum_.getMethod("values").invoke(null); } catch (Exception e) { throw new FmtIllegalArgumentException( e, "Argument `enum_' of illegal type"); } E actualValue = null; for (E valueType : values) { if (!(valueType instanceof OptionEnum)) throw new FmtIllegalArgumentException( "Argument `enum_' does not inherit `OptionEnum'"); if (((OptionEnum) valueType).getOptionName().equals(value)) { actualValue = valueType; break; } } if (actualValue == null) throw new IllegalOptionArgumentException(state.formatNames(), value); return actualValue; } public void checkForInvalidOptions() throws IllegalOptionException { config.checkForInvalidOptions(); } // ========================================================================= protected T convert(String option, String value, Class clazz) { @SuppressWarnings("unchecked") Converter converter = (Converter) converters.get(clazz); if (converter == null) throw new UnknownConversionException(option, clazz); return converter.convert(option, value); } } UnknownConversionException.java000066400000000000000000000026121315622671000406160ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils-getopt/src/main/java/de/fau/cs/osr/utils/getopt/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.utils.getopt; import java.util.Arrays; import joptsimple.OptionException; public class UnknownConversionException extends OptionException { private static final long serialVersionUID = -5076229021503080077L; private final Class clazz; // ========================================================================= public UnknownConversionException(String option, Class clazz) { super(Arrays.asList(option)); this.clazz = clazz; } // ========================================================================= @Override public String getMessage() { return String.format( "No converter for type `%s' found when processing option: %s", clazz.getSimpleName(), singleOptionMessage()); } } UnrecognizedPropertyException.java000066400000000000000000000024021315622671000413070ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils-getopt/src/main/java/de/fau/cs/osr/utils/getopt/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.utils.getopt; import java.util.Arrays; import joptsimple.OptionException; public class UnrecognizedPropertyException extends OptionException { private static final long serialVersionUID = 1L; // ========================================================================= protected UnrecognizedPropertyException(String option) { super(Arrays.asList(option)); } // ========================================================================= @Override public String getMessage() { return String.format( "%s is not a known property key", singleOptionMessage()); } } osr-common-osr-common-3.0.8/utils-parent/utils-getopt/src/test/000077500000000000000000000000001315622671000245425ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils-getopt/src/test/java/000077500000000000000000000000001315622671000254635ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils-getopt/src/test/java/de/000077500000000000000000000000001315622671000260535ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils-getopt/src/test/java/de/fau/000077500000000000000000000000001315622671000266265ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils-getopt/src/test/java/de/fau/cs/000077500000000000000000000000001315622671000272335ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils-getopt/src/test/java/de/fau/cs/osr/000077500000000000000000000000001315622671000300365ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils-getopt/src/test/java/de/fau/cs/osr/utils/000077500000000000000000000000001315622671000311765ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils-getopt/src/test/java/de/fau/cs/osr/utils/getopt/000077500000000000000000000000001315622671000325005ustar00rootroot00000000000000TestOptions.java000066400000000000000000000233501315622671000355620ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils-getopt/src/test/java/de/fau/cs/osr/utils/getopt/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.utils.getopt; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.util.Properties; import org.junit.Assert; import org.junit.Before; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import joptsimple.OptionException; public class TestOptions { private Options options; private Properties properties; @Rule public ExpectedException thrown = ExpectedException.none(); // ========================================================================= @Before public void initialize() { options = new Options(); properties = new Properties(); properties.setProperty("some.opt", "some opt value"); } // ========================================================================= @Test public void testUnspecifiedOptionNotAvailable() throws Exception { options.createOption("some-opt") .create(); Assert.assertFalse(options.has("some-opt")); } // ========================================================================= @Test public void testOptionValueRetrievableByLongOption() { options.createOption('d', "dump") .withRequiredArg() .create(); options.parse(new String[] { "--dump=bla" }); Assert.assertTrue(options.has("dump")); Assert.assertEquals("bla", options.value("dump")); } @Test public void testOptionValueRetrievableByShortOption() { options.createOption('d') .withRequiredArg() .create(); options.parse(new String[] { "-d", "bla" }); Assert.assertTrue(options.has("d")); Assert.assertEquals("bla", options.value("d")); } @Test public void testDefaultOptionRetrievable() { options.createOption('d') .withRequiredArg() .withDefault("bla") .create(); options.parse(new String[] {}); Assert.assertFalse(options.has("d")); Assert.assertEquals("bla", options.value("d")); } @Test public void testPropertyAvailableAsKeyAndLongOpt() throws Exception { options.createOption("some-opt") .withPropertyKey("some.opt") .withRequiredArg() .create(); options.load(properties); Assert.assertTrue(options.has("some-opt")); Assert.assertTrue(options.has("some.opt")); Assert.assertEquals(properties.getProperty("some.opt"), options.value("some.opt")); Assert.assertEquals(properties.getProperty("some.opt"), options.value("some-opt")); } @Test public void testCmdLineArgAvailableAsKeyAndLongOpt() throws Exception { options.createOption("some-opt") .withPropertyKey("some.opt") .withRequiredArg() .create(); final String value = "cmd line value"; options.parse(new String[] { "--some-opt=" + value }); Assert.assertTrue(options.has("some-opt")); Assert.assertTrue(options.has("some.opt")); Assert.assertEquals(value, options.value("some.opt")); Assert.assertEquals(value, options.value("some-opt")); } @Test public void testCmdLineOverridesProps() throws Exception { options.createOption("some-opt") .withPropertyKey("some.opt") .withRequiredArg() .create(); final String value = "cmd line value"; options.parse(new String[] { "--some-opt=" + value }); options.load(properties); Assert.assertTrue(options.has("some-opt")); Assert.assertTrue(options.has("some.opt")); Assert.assertEquals(value, options.value("some.opt")); Assert.assertEquals(value, options.value("some-opt")); } // ========================================================================= @Test public void testUnknownCmdLineOptRaisesException() throws Exception { options.createOption("some-opt") .create(); thrown.expect(OptionException.class); thrown.expectMessage("'blub' is not a recognized option"); options.parse(new String[] { "--blub" }); } @Test public void testUnknownPropertyKeyRaisesException() throws Exception { options.createOption("some-other-opt") .create(); thrown.expect(UnrecognizedPropertyException.class); thrown.expectMessage("'some.opt' is not a known property key"); options.load(properties); } @Test public void testUnexpectedOptionRaisesException() throws Exception { options.createOption("some-opt") .create(); options.parse(new String[] { "--some-opt=hallo" }); Assert.assertTrue(options.has("some-opt")); thrown.expect(IllegalOptionException.class); thrown.expectMessage("'--some-opt'"); options.checkForInvalidOptions(); } @Test public void testUnexpectedPropertyDoesNotRaiseException() throws Exception { options.createOption("some-opt") .withPropertyKey("some.opt") .create(); options.load(properties); Assert.assertTrue(options.has("some-opt")); options.checkForInvalidOptions(); } @Test public void testGivenOptionalCmdLineOptDoesNotRaiseException() throws Exception { options.createOption("some-opt") .withPropertyKey("some.opt") .create(); options.parse(new String[] { "--some-opt=hallo" }); Assert.assertTrue(options.has("some-opt")); options.optional("some-opt"); options.checkForInvalidOptions(); } @Test public void testUnspecifiedOptionalCmdLineOptDoesNotRaiseException() throws Exception { options.createOption("some-opt") .withPropertyKey("some.opt") .create(); options.parse(new String[] {}); Assert.assertFalse(options.has("some-opt")); options.optional("some-opt"); options.checkForInvalidOptions(); } @Test public void testGivenRequiredCmdLineOptDoesNotRaiseException() throws Exception { options.createOption("some-opt") .withPropertyKey("some.opt") .create(); options.parse(new String[] { "--some-opt" }); Assert.assertTrue(options.has("some-opt")); options.expected("some-opt"); options.checkForInvalidOptions(); } @Test public void testMissingRequiredCmdLineOptRaisesException() throws Exception { options.createOption("some-opt") .withPropertyKey("some.opt") .create(); options.parse(new String[] {}); Assert.assertFalse(options.has("some-opt")); thrown.expect(MissingOptionException.class); thrown.expectMessage("'--some-opt'"); options.expected("some-opt"); } @Test public void testPropertySatisfiesRequiredOption() throws Exception { options.createOption("some-opt") .withPropertyKey("some.opt") .create(); options.load(properties); Assert.assertTrue(options.has("some-opt")); options.expected("some-opt"); } @Test public void testIgnoredButGivenCmdLineOptCausesWarning() throws Exception { options.createOption("some-opt") .withPropertyKey("some.opt") .create(); options.parse(new String[] { "--some-opt" }); Assert.assertTrue(options.has("some-opt")); ByteArrayOutputStream baos = new ByteArrayOutputStream(); System.setErr(new PrintStream(baos)); options.ignore("some-opt"); baos.close(); Assert.assertTrue(baos.toString().contains("some-opt")); options.checkForInvalidOptions(); } @Test public void testIgnoredButGivenPropertyCausesWarning() throws Exception { options.createOption("some-opt") .withPropertyKey("some.opt") .create(); options.parse(new String[] { "--some-opt" }); Assert.assertTrue(options.has("some-opt")); ByteArrayOutputStream baos = new ByteArrayOutputStream(); System.setErr(new PrintStream(baos)); options.ignore("some-opt"); baos.close(); Assert.assertTrue(baos.toString().contains("some-opt")); options.checkForInvalidOptions(); } // ========================================================================= @Test public void testFixedValueIsNotRecognizedAsCmdLineArg() throws Exception { options.createFixedValueOption("some-opt", "100"); thrown.expect(OptionException.class); thrown.expectMessage("'some-opt'"); options.parse(new String[] { "--some-opt" }); } @Test public void testFixedValueIsNotRecognizedAsProperty() throws Exception { options.createFixedValueOption("some.opt", "100"); thrown.expect(UnrecognizedPropertyException.class); thrown.expectMessage("'some.opt'"); options.load(properties); } @Test public void testFixedValueIsNotReportedByHasButHasValue() throws Exception { options.createFixedValueOption("some.opt", "100"); Assert.assertFalse(options.has("some.opt")); Assert.assertEquals("100", options.value("some.opt")); } // ========================================================================= @Test public void testPropertySubset() throws Exception { options.createOption("some-number") .withArgName("N") .withDescription("Some numbers' description") .withDefault("42") .withRequiredArg() .withPropertyKey("subset.some-number") .create(); options.createOption("some-other-number") .withPropertyKey("some-other-subset.some-other-number") .withRequiredArg() .create(); options.parse(new String[] { "--some-number=8", "--some-other-number=42" }); Properties p = options.propertySubset("subset"); Assert.assertEquals(1, p.size()); Assert.assertEquals("8", p.getProperty("some-number")); } // ========================================================================= @Test @Ignore public void testHelpMessage() throws Exception { /* TODO: We have to test: - options.cmdLineHelp(System.out); - options.propertiesHelp(System.out); - options.fixedOptionsHelp(System.out); */ } } osr-common-osr-common-3.0.8/utils-parent/utils-testing/000077500000000000000000000000001315622671000231475ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils-testing/pom.xml000066400000000000000000000051621315622671000244700ustar00rootroot00000000000000 4.0.0 de.fau.cs.osr.utils utils-parent 3.0.8 utils-testing jar Utils Testing 2016 Utility classes for writing unit tests. ../../tooling/ commons-io commons-io junit junit de.fau.cs.osr.utils utils de.thetaphi forbiddenapis commons-io-unsafe-1.4 osr-common-osr-common-3.0.8/utils-parent/utils-testing/src/000077500000000000000000000000001315622671000237365ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils-testing/src/main/000077500000000000000000000000001315622671000246625ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils-testing/src/main/java/000077500000000000000000000000001315622671000256035ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils-testing/src/main/java/de/000077500000000000000000000000001315622671000261735ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils-testing/src/main/java/de/fau/000077500000000000000000000000001315622671000267465ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils-testing/src/main/java/de/fau/cs/000077500000000000000000000000001315622671000273535ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils-testing/src/main/java/de/fau/cs/osr/000077500000000000000000000000001315622671000301565ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils-testing/src/main/java/de/fau/cs/osr/utils/000077500000000000000000000000001315622671000313165ustar00rootroot00000000000000FileCompare.java000066400000000000000000000114411315622671000342710ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils-testing/src/main/java/de/fau/cs/osr/utils/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.utils; import java.io.File; import java.io.IOException; import java.util.regex.Pattern; import org.junit.Assert; public class FileCompare { private static final Object IGNORE_TEST = "IGNORE THIS TEST"; private static Pattern inputPathToRefPathSearch; private static String inputPathToRefPathReplaceWith; private final TestResourcesFixture resources; private final boolean randomRefName; private final boolean putInitialRefFilesIntoRefFileDir; // ========================================================================= /** * This constructor generates a file comparison object that writes generated * reference files to the current working directory. The generated files * contain random elements to prevent collisions. */ public FileCompare(TestResourcesFixture resources) { this.resources = resources; this.randomRefName = false; this.putInitialRefFilesIntoRefFileDir = false; } /** * This constructor generates a file comparison object that tries to write * generated reference files back into the source tree. * * This is done by replacing pathPatternToReplace with * pathToReplacePatternWith in the path to the reference file * (which initially would be located in the output directory of the * project). */ public FileCompare( TestResourcesFixture resources, boolean randomRefName, boolean putInitialRefFilesIntoRefFileDir) { this.resources = resources; this.randomRefName = randomRefName; this.putInitialRefFilesIntoRefFileDir = putInitialRefFilesIntoRefFileDir; } // ========================================================================= public void compareWithExpectedOrGenerateExpectedFromActual( File expectedFile, String actual) throws IOException { actual = fixActualText(actual); checkReferenceFile(expectedFile, actual); assertEquals(expectedFile, actual); } // ========================================================================= public String fixActualText(String actual) { return resources.stripBaseDirectoryAndFixPath( FileTools.lineEndToUnix(actual)); } private void checkReferenceFile( File expectedFile, String actual) throws IOException { if (!expectedFile.exists()) { File create; if (putInitialRefFilesIntoRefFileDir) { String dir = expectedFile.getParentFile().getAbsolutePath(); // We always operate with UNIX separator '/': FileTools.fileSeparatorToUnix(dir); if (inputPathToRefPathSearch == null) inputPathToRefPathSearch = Pattern.compile( "(.*?)" + Pattern.quote("/target/test-classes/")); if (!inputPathToRefPathSearch.matcher(dir).find()) Assert.fail( "Reference file did not exist! " + "FAILED TO WRITE REFERENCE FILE!"); if (inputPathToRefPathReplaceWith == null) inputPathToRefPathReplaceWith = "$1" + Pattern.quote("/src/test/resources/"); dir = inputPathToRefPathSearch.matcher(dir).replaceAll(inputPathToRefPathReplaceWith); create = new File(dir); } else { create = new File("").getAbsoluteFile(); } if (randomRefName) { create = File.createTempFile(expectedFile.getName() + "-", "", create); } else { create = new File(create, expectedFile.getName()); } org.apache.commons.io.FileUtils.writeStringToFile(create, actual, "UTF8"); Assert.fail( "Reference file did not exist! " + "Wrote initial reference file to: " + create.getAbsolutePath()); } } public void assertEquals(File expectedFile, String actual) throws IOException { FileContent reftext = new FileContent(expectedFile); String trimmed = reftext.getContent().trim(); int i = trimmed.indexOf('\n'); int j = trimmed.indexOf('\r'); if ((i == -1) || (j != -1 && j < i)) i = j; if (i != -1) trimmed = trimmed.substring(0, i); if (trimmed.equals(IGNORE_TEST)) return; // We always operate with UNIX line end '\n': String reference = FileTools.lineEndToUnix(reftext.getContent()); /* UGLY DANGEROUS INTERMEDIATE EVIL HACK* if (!reference.equals(actual)) FileUtils.writeStringToFile(expectedFile, actual); /**/ Assert.assertEquals(reference, actual); } } FileContent.java000066400000000000000000000040371315622671000343200ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils-testing/src/main/java/de/fau/cs/osr/utils/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.utils; import java.io.File; import java.io.IOException; public class FileContent { private File file; private String content; // ========================================================================= public FileContent(File file) throws IOException { loadFile(file, "UTF-8"); } public FileContent(File file, String encoding) throws IOException { loadFile(file, encoding); } // ========================================================================= protected void loadFile(File file, String encoding) throws IOException { if (encoding == null) throw new FmtIllegalArgumentException( "Argument `encoding' must not be null"); if (file == null) throw new FmtIllegalArgumentException( "Argument `file' must not be null"); if (!file.exists()) throw new FmtFileNotFoundException( "File not found: `%s'", file.getAbsolutePath()); this.file = file; String fileContent = org.apache.commons.io.FileUtils.readFileToString(file, encoding); this.content = de.fau.cs.osr.utils.FileTools.lineEndToUnix(fileContent); } // ========================================================================= public File getFile() { return file; } public void setFile(File file) { this.file = file; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } } NamedParametrized.java000066400000000000000000000104761315622671000355060ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils-testing/src/main/java/de/fau/cs/osr/utils/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.utils; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.junit.runner.Runner; import org.junit.runner.notification.RunNotifier; import org.junit.runners.BlockJUnit4ClassRunner; import org.junit.runners.Parameterized.Parameters; import org.junit.runners.Suite; import org.junit.runners.model.FrameworkMethod; import org.junit.runners.model.InitializationError; import org.junit.runners.model.Statement; import org.junit.runners.model.TestClass; public class NamedParametrized extends Suite { private final ArrayList runners = new ArrayList(); // ========================================================================= public NamedParametrized(Class clazz) throws Throwable { super(clazz, Collections. emptyList()); int i = 0; for (Object[] parameters : getParametersList(getTestClass())) runners.add(new TestClassRunner( getTestClass().getJavaClass(), parameters, i++)); } @Override protected List getChildren() { return runners; } @SuppressWarnings("unchecked") private List getParametersList(TestClass clazz) throws Throwable { return (List) getParametersMethod(clazz).invokeExplosively(null); } private FrameworkMethod getParametersMethod(TestClass testClass) throws Exception { List methods = testClass.getAnnotatedMethods(Parameters.class); FrameworkMethod found = null; for (FrameworkMethod method : methods) { int modifiers = method.getMethod().getModifiers(); if (Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers)) { if (found != null) throw new Exception("Multiple public static methods are annotated with @Parameters in " + testClass.getName()); found = method; } } if (found == null) throw new Exception("Cannot find public static method annotated with @Parameters in " + testClass.getName()); return found; } // ========================================================================= private static class TestClassRunner extends BlockJUnit4ClassRunner { private final int parameterSet; private final Object[] parameters; private final String parameterSetName; TestClassRunner(Class type, Object[] parameters, int parameterSet) throws InitializationError { super(type); this.parameters = parameters; this.parameterSet = parameterSet; parameterSetName = getParameterSetName(parameters); } private static String getParameterSetName(Object[] parameters) { Object object = parameters[0]; if (object instanceof String) return String.format("\"%s\"", (String) object); else return ""; } @Override public Object createTest() throws Exception { return getTestClass().getOnlyConstructor().newInstance(parameters); } @Override protected String getName() { return String.format( "[%d]: %s", parameterSet, parameterSetName); } @Override protected String testName(final FrameworkMethod method) { TestNameAnnotation nameAnnotation = method.getAnnotation(TestNameAnnotation.class); if (nameAnnotation == null) { return String.format( "%s with { %s, ... }", method.getName(), parameterSetName); } else { return String.format( "%s with { %s, ... }; %s", method.getName(), parameterSetName, nameAnnotation.annotation()); } } @Override protected void validateConstructor(List errors) { validateOnlyOneConstructor(errors); } @Override protected Statement classBlock(RunNotifier notifier) { return childrenInvoker(notifier); } } } NamedParametrizedSuites.java000066400000000000000000000140551315622671000367000ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils-testing/src/main/java/de/fau/cs/osr/utils/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.utils; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.junit.runner.Runner; import org.junit.runner.notification.RunNotifier; import org.junit.runners.BlockJUnit4ClassRunner; import org.junit.runners.Suite; import org.junit.runners.model.FrameworkMethod; import org.junit.runners.model.InitializationError; import org.junit.runners.model.Statement; import org.junit.runners.model.TestClass; public class NamedParametrizedSuites extends Suite { @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public static @interface Suites { } // ========================================================================= public static final class NamedParametrizedSuite implements Comparable { private final String suiteName; private final String suiteDescription; private final List testCases; public NamedParametrizedSuite( String suiteName, String suiteDescription, List testCases) { super(); this.suiteName = suiteName; this.suiteDescription = suiteDescription; this.testCases = testCases; } public String getSuiteName() { return suiteName; } public String getSuiteDescription() { return suiteDescription; } public List getTestCases() { return testCases; } @Override public int compareTo(NamedParametrizedSuite o) { return suiteName.compareTo(o.getSuiteName()); } } // ========================================================================= private final ArrayList runners = new ArrayList(); // ========================================================================= public NamedParametrizedSuites(Class clazz) throws Throwable { super(clazz, Collections. emptyList()); int i = 0; for (NamedParametrizedSuite suite : getSuiteList(getTestClass())) runners.add(new TestSuiteRunner( clazz, suite, i++)); } @Override protected List getChildren() { return runners; } @SuppressWarnings("unchecked") private List getSuiteList(TestClass clazz) throws Throwable { return (List) getSuitesMethod(clazz).invokeExplosively(null); } private FrameworkMethod getSuitesMethod(TestClass testClass) throws Exception { List methods = testClass.getAnnotatedMethods(Suites.class); FrameworkMethod found = null; for (FrameworkMethod method : methods) { int modifiers = method.getMethod().getModifiers(); if (Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers)) { if (found != null) throw new Exception("Multiple public static methods are annotated with @Suites in " + testClass.getName()); found = method; } } if (found == null) throw new Exception("Cannot find public static method annotated with @Suites in " + testClass.getName()); return found; } // ========================================================================= private static class TestSuiteRunner extends Suite { private final ArrayList runners = new ArrayList(); private final String name; @SuppressWarnings("unused") private final String description; TestSuiteRunner( Class clazz, NamedParametrizedSuite suiteDesc, int parameterSet) throws InitializationError { super(clazz, Collections. emptyList()); this.name = suiteDesc.getSuiteName(); this.description = suiteDesc.getSuiteDescription(); int i = 0; for (Object[] parameters : suiteDesc.getTestCases()) runners.add(new TestClassRunner( getTestClass().getJavaClass(), parameters, i++)); } @Override protected List getChildren() { return runners; } @Override protected String getName() { return name; } } // ========================================================================= private static class TestClassRunner extends BlockJUnit4ClassRunner { private final int parameterSet; private final Object[] parameters; private final String parameterSetName; TestClassRunner(Class type, Object[] parameters, int parameterSet) throws InitializationError { super(type); this.parameters = parameters; this.parameterSet = parameterSet; parameterSetName = getParameterSetName(parameters); } private static String getParameterSetName(Object[] parameters) { Object object = parameters[0]; if (object instanceof String) return String.format("\"%s\"", (String) object); else return ""; } @Override public Object createTest() throws Exception { return getTestClass().getOnlyConstructor().newInstance(parameters); } @Override protected String getName() { return String.format( "[%d]: %s", parameterSet, parameterSetName); } @Override protected String testName(final FrameworkMethod method) { return String.format( "%s with { %s, ... }", method.getName(), parameterSetName); } @Override protected void validateConstructor(List errors) { validateOnlyOneConstructor(errors); } @Override protected Statement classBlock(RunNotifier notifier) { return childrenInvoker(notifier); } } } TestNameAnnotation.java000066400000000000000000000017321315622671000356600ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils-testing/src/main/java/de/fau/cs/osr/utils/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.utils; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface TestNameAnnotation { String annotation(); } TestResourcesFixture.java000066400000000000000000000270351315622671000362720ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils-testing/src/main/java/de/fau/cs/osr/utils/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.utils; import java.io.File; import java.io.FileNotFoundException; import java.io.FilenameFilter; import java.net.URL; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.io.FilenameUtils; public class TestResourcesFixture { private final File baseDirectory; // ========================================================================= /** * @param baseDirectory * Path to a directory in which the resources will be gathered. * * @throws FileNotFoundException * Thrown if the given path doesn't exist or doesn't point to a * directory. */ public TestResourcesFixture(File baseDirectory) throws FileNotFoundException { if (baseDirectory != null) { if (!baseDirectory.exists()) throw new FileNotFoundException(String.format( "Given base directory `%s' does not exist", baseDirectory)); if (!baseDirectory.isDirectory()) throw new FileNotFoundException(String.format( "Given base directory `%s' is not a directory", baseDirectory)); this.baseDirectory = baseDirectory; } else { this.baseDirectory = null; } } /** * @param classLoader * A class loader used to locate the index file. * @param pathToIndex * Resource path to a directory in which the resources will be * gathered. The directory must contain an index file (the * content of the file doesn't matter). * * @throws FileNotFoundException * Thrown if the index file cannot be found in the directory * pointed to by pathToIndex. */ public TestResourcesFixture(ClassLoader classLoader, String pathToIndex) throws FileNotFoundException { this.baseDirectory = findBaseDirectory(classLoader, pathToIndex); } private static File findBaseDirectory(ClassLoader cl, String pathToIndex) throws FileNotFoundException { URL url = cl.getResource(String.format("%s/index", pathToIndex)); if (url == null) throw new FileNotFoundException(String.format( "Cannot find index file in resource path: `%s'", pathToIndex)); String path = StringTools.decodeUsingDefaultCharset(url.getFile()); return new File(path).getParentFile(); } // ========================================================================= public File getBaseDirectory() { return baseDirectory; } // ========================================================================= /** * Get a list of resources that can be directly returned from a method * annotated with \@Parameters. The list consists of tuples of file name (no * path), this TestResourcesFixture object and the file itself. The * \@Parameters annotation will use the file name as title for the test. * * Important: Always use the UNIX file separator '/'. * * @param inputSubDir * Where to find the resources. * @param filterRx * Only resources whose filenames match this regular expression * will be gathered. * @param recursive * Whether to recurse in sub directories. * @return The list of gathered resources. */ public List gatherAsParameters( String inputSubDir, String filterRx, boolean recursive) { LinkedList inputs = new LinkedList(); for (File file : gather(inputSubDir, filterRx, recursive)) inputs.add(new Object[] { file.getName(), this, file }); return inputs; } /** * Recursively gather files which match a certain pattern. * * @param subDirectory * A sub-directory inside baseDirectory. The directory must * exist. * @param pattern * Only file names that match this pattern will be returned. * @param recursive * Look in sub-directories for matches. * @return A list of files that match the criteria. * @throws IllegalArgumentException * Thrown if one of the given directory paths doesn't exist or * does not point to a directory. */ public List gather( String subDirectory, String pattern, final boolean recursive) { List files = new LinkedList(); final Pattern p = Pattern.compile(pattern); FilenameFilter filter = new FilenameFilter() { public boolean accept(File dir, String name) { Matcher matcher = p.matcher(name); if (matcher.matches()) return true; else if (recursive) return new File(dir, name).isDirectory(); else return false; } }; File dir = new File(this.baseDirectory, subDirectory); if (!dir.exists()) throw new FmtIllegalArgumentException( "Given directory `%s' does not exist", dir.getAbsolutePath()); if (!dir.isDirectory()) throw new FmtIllegalArgumentException( "Given directory `%s' is not a directory", dir.getAbsolutePath()); gatherRecursive(dir, filter, files); Collections.sort(files); return files; } private static void gatherRecursive( File directory, FilenameFilter filter, List gathered) { String[] files = directory.list(filter); if (files != null) { for (String fileName : files) { File file = new File(directory, fileName); if (file.isDirectory()) { gatherRecursive(file, filter, gathered); } else { gathered.add(file); } } } } // ========================================================================= /** * Fix paths found inside a text. * * Some tests produce texts which then are compared to reference text files * to make sure the output is correct. However, sometimes these texts * contain file system paths in the format * /some/path:line:message that are specific to the execution * environment. Given the specific part of such paths this method removes * the specific part and turns any OS dependent path separator into a unix * separator. * * @param text * The original text. * @return The fixed text. */ public String stripBaseDirectoryAndFixPath(String text) { String p = Pattern.quote(this.baseDirectory.getAbsolutePath()); Pattern rx = Pattern.compile(p + "(.*?:)"); StringBuilder b = new StringBuilder(); Matcher m = rx.matcher(text); int begin = 0; while (m.find(begin)) { b.append(text.substring(begin, m.start())); b.append(m.group(1).replace(File.separatorChar, '/')); begin = m.end(); } if (begin < text.length()) b.append(text.substring(begin, text.length())); return b.toString(); } // ========================================================================= /** * Change a path so that the filename it points to is located in a different * directory. * * Important: Always use the UNIX file separator '/'. * * @param file * The file whose filename will be moved to a different directory * and whose extension will be altered. * @param base * The part of the original path that will be changed. * @param rebase * The part of a path which will replace base. */ public static File rebase(File file, String base, String rebase) { String unixPath = FileTools.fileSeparatorToUnix(file.getAbsolutePath()); File rebasedFile = new File(unixPath.replace(base, rebase)); if (!rebasedFile.exists()) throw new FmtIllegalArgumentException( "Rebased file `%s' does not exist", rebasedFile.getAbsolutePath()); return rebasedFile; } /** * Change a path so that the filename it points to is located in a different * directory. Also change the extension of the filename. * * Important: Always use the UNIX file separator '/'. * * @param file * The file whose filename will be moved to a different directory * and whose extension will be altered. * @param base * The part of the original path that will be changed. * @param rebase * The part of a path which will replace base. * @param ext * The new extension of the file. * @return The rebased path. * @throws IllegalArgumentException * Thrown if the rebased path doesn't exist. */ public static File rebase(File file, String base, String rebase, String ext) { return rebase(file, base, rebase, ext, false); } /** * Change a path so that the filename it points to is located in a different * directory. Also change the extension of the filename. * * Important: Always use the UNIX file separator '/'. * * @param file * The file whose filename will be moved to a different directory * and whose extension will be altered. * @param base * The part of the original path that will be changed. * @param rebase * The part of a path which will replace base. * @param ext * The new extension of the file. * @param noThrow * If true this method will not throw an exception if the rebased * file doesn't exist. * @return The rebased path. * @throws IllegalArgumentException * Thrown if the rebased path doesn't exist and noThrow is * false. */ public static File rebase( File file, String base, String rebase, String ext, boolean noThrow) { String unixPath = FileTools.fileSeparatorToUnix(file.getAbsolutePath()); String rebased = unixPath.replace(base, rebase); int i = rebased.lastIndexOf('.'); // Fixed bug: only remove extension if dot occurs in last path segment int j = rebased.lastIndexOf('/'); if ((j != -1) && (i < j)) i = -1; rebased = i < 0 ? rebased + "." + ext : rebased.substring(0, i + 1) + ext; File rebasedFile = new File(rebased); if (rebasedFile.exists() || noThrow) return rebasedFile; throw new FmtIllegalArgumentException( "Rebased file `%s' does not exist", rebasedFile.getAbsolutePath()); } // ========================================================================= /** * Appends "index" to the given path and tries to locate the resulting * resource. It the returns the directory which contains the "index" file. * * @param clazz * Class instance used to locate the resource. */ public static File getResourceIndexDirectory(Class clazz, String basePath) { File index = resourceNameToFile(clazz, basePath + "/index"); return index.getParentFile(); } /** * Return a File object which points to the resource specified in testFile. * * @param clazz * Class instance used to locate the resource. */ public static File resourceNameToFile(Class clazz, String testFile) { URL wmUrl = clazz.getResource(testFile); if (wmUrl != null) return new File(StringTools.decodeUsingDefaultCharset(wmUrl.getFile())); return null; } /** * @deprecated */ public static String fnameToTitle(File inputFile) { return FilenameUtils.getBaseName(inputFile.getName()); } } osr-common-osr-common-3.0.8/utils-parent/utils/000077500000000000000000000000001315622671000214745ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils/pom.xml000066400000000000000000000047001315622671000230120ustar00rootroot00000000000000 4.0.0 de.fau.cs.osr.utils utils-parent 3.0.8 utils jar Utils 2009 A couple of utility classes in one comprehensive package. ../../tooling/ org.apache.commons commons-lang3 commons-codec commons-codec junit junit test osr-common-osr-common-3.0.8/utils-parent/utils/src/000077500000000000000000000000001315622671000222635ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils/src/main/000077500000000000000000000000001315622671000232075ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils/src/main/java/000077500000000000000000000000001315622671000241305ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils/src/main/java/de/000077500000000000000000000000001315622671000245205ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils/src/main/java/de/fau/000077500000000000000000000000001315622671000252735ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils/src/main/java/de/fau/cs/000077500000000000000000000000001315622671000257005ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils/src/main/java/de/fau/cs/osr/000077500000000000000000000000001315622671000265035ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils/src/main/java/de/fau/cs/osr/utils/000077500000000000000000000000001315622671000276435ustar00rootroot00000000000000AccumulatingRingBufferDouble.java000066400000000000000000000075011315622671000361530ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils/src/main/java/de/fau/cs/osr/utils/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.utils; import java.math.BigDecimal; import java.util.Iterator; import java.util.NoSuchElementException; public class AccumulatingRingBufferDouble implements Iterable { private final double[] buffer; private int fill = 0; private int start = 0; private BigDecimal sum = BigDecimal.ZERO; // ========================================================================= public AccumulatingRingBufferDouble(int capacity) { this.buffer = new double[capacity]; } // ========================================================================= /** * Adds a new value to the ring buffer, overwriting the oldest value if the * ring buffer is already full. */ public void add(double value) { int i = indexOf(getN()); if (willAddOverwrite()) { removeValueFormSumAt(0); advance(1); } else { fill += 1; } buffer[i] = value; addToSum(value); } public void removeNewestN(int n) { if (getN() < n) throw new IllegalArgumentException(); for (int i = 0; i < n; ++i) removeValueFormSumAt(fill - i - 1); fill -= n; } public void removeOldestN(int n) { if (getN() < n) throw new IllegalArgumentException(); for (int i = 0; i < n; ++i) removeValueFormSumAt(i); advance(n); fill -= n; } public void clear() { start = 0; fill = 0; } /** * @return @{code true} if the next call to {@link #add(double)} will * overwrite the oldest value. */ public boolean willAddOverwrite() { return getN() == getCapacity(); } /** * @param index * The index of the value, where 0 refers to the newest (most * recent) value. */ public double get(int index) { if (getN() == 0) throw new NoSuchElementException(); return getAt(getN() - index - 1); } /** * @return The value added last (the most recent value). */ public double getNewest() { if (getN() == 0) throw new NoSuchElementException(); return getAt(getN() - 1); } public double getOldest() { if (getN() == 0) throw new NoSuchElementException(); return getAt(0); } public BigDecimal getSum() { return sum; } public int getN() { return fill; } public int getCapacity() { return buffer.length; } @Override public Iterator iterator() { return new Iterator() { private int i = 0; @Override public boolean hasNext() { return i < getN(); } @Override public Double next() { if (!hasNext()) throw new NoSuchElementException(); return getAt(i++); } @Override public void remove() { throw new UnsupportedOperationException(); } }; } // ========================================================================= private int advance(int n) { return start = (start + n) % getCapacity(); } /** * @param index * 0 is the oldest value. */ private int indexOf(int index) { return (start + index) % getCapacity(); } private double getAt(int index) { return buffer[indexOf(index)]; } private void addToSum(double value) { sum = sum.add(BigDecimal.valueOf(value)); } private void removeValueFormSumAt(int index) { sum = sum.subtract(BigDecimal.valueOf(getAt(index))); } } AccumulatingRingBufferLong.java000066400000000000000000000074431315622671000356450ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils/src/main/java/de/fau/cs/osr/utils/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.utils; import java.math.BigInteger; import java.util.Iterator; import java.util.NoSuchElementException; public class AccumulatingRingBufferLong implements Iterable { private final long[] buffer; private int fill = 0; private int start = 0; private BigInteger sum = BigInteger.ZERO; // ========================================================================= public AccumulatingRingBufferLong(int capacity) { this.buffer = new long[capacity]; } // ========================================================================= /** * Adds a new value to the ring buffer, overwriting the oldest value if the * ring buffer is already full. */ public void add(long value) { int i = indexOf(getN()); if (willAddOverwrite()) { removeValueFormSumAt(0); advance(1); } else { fill += 1; } buffer[i] = value; addToSum(value); } public void removeNewestN(int n) { if (getN() < n) throw new IllegalArgumentException(); for (int i = 0; i < n; ++i) removeValueFormSumAt(fill - i - 1); fill -= n; } public void removeOldestN(int n) { if (getN() < n) throw new IllegalArgumentException(); for (int i = 0; i < n; ++i) removeValueFormSumAt(i); advance(n); fill -= n; } public void clear() { start = 0; fill = 0; } /** * @return @{code true} if the next call to {@link #add(long)} will * overwrite the oldest value. */ public boolean willAddOverwrite() { return getN() == getCapacity(); } /** * @param index * The index of the value, where 0 refers to the newest (most * recent) value. */ public long get(int index) { if (getN() == 0) throw new NoSuchElementException(); return getAt(getN() - index - 1); } /** * @return The value added last (the most recent value). */ public long getNewest() { if (getN() == 0) throw new NoSuchElementException(); return getAt(getN() - 1); } public long getOldest() { if (getN() == 0) throw new NoSuchElementException(); return getAt(0); } public BigInteger getSum() { return sum; } public int getN() { return fill; } public int getCapacity() { return buffer.length; } @Override public Iterator iterator() { return new Iterator() { private int i = 0; @Override public boolean hasNext() { return i < getN(); } @Override public Long next() { if (!hasNext()) throw new NoSuchElementException(); return getAt(i++); } @Override public void remove() { throw new UnsupportedOperationException(); } }; } // ========================================================================= private int advance(int n) { return start = (start + n) % getCapacity(); } /** * @param index * 0 is the oldest value. */ private int indexOf(int index) { return (start + index) % getCapacity(); } private long getAt(int index) { return buffer[indexOf(index)]; } private void addToSum(long value) { sum = sum.add(BigInteger.valueOf(value)); } private void removeValueFormSumAt(int index) { sum = sum.subtract(BigInteger.valueOf(getAt(index))); } } osr-common-osr-common-3.0.8/utils-parent/utils/src/main/java/de/fau/cs/osr/utils/ArrayStack.java000066400000000000000000000032211315622671000325500ustar00rootroot00000000000000/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.utils; import java.util.Arrays; import java.util.EmptyStackException; public class ArrayStack { private Object[] stack; private final int capacityIncrease; private int size = 0; public ArrayStack() { this.stack = new Object[10]; this.capacityIncrease = 10; } public ArrayStack(int initialCapacity, int capacityIncrease) { if (initialCapacity < 0 || capacityIncrease < 1) throw new IllegalArgumentException(); this.stack = new Object[initialCapacity]; this.capacityIncrease = capacityIncrease; } public boolean isEmpty() { return size == 0; } @SuppressWarnings("unchecked") public T peek() { if (isEmpty()) throw new EmptyStackException(); return (T) stack[size - 1]; } public T pop() { T top = peek(); --size; return top; } public T push(T item) { if (size == stack.length) stack = Arrays.copyOf(stack, stack.length + capacityIncrease); stack[size++] = item; return item; } public void clear() { size = 0; } } osr-common-osr-common-3.0.8/utils-parent/utils/src/main/java/de/fau/cs/osr/utils/BinaryPrefix.java000066400000000000000000000031731315622671000331140ustar00rootroot00000000000000/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.utils; public class BinaryPrefix { private final long normValue; private final double doubleValue; private final String prefix; private final long factor; private final static String prefixes[] = new String[] { "", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei" }; public BinaryPrefix(long value) { int i; long factor = 1; for (i = 0; i < prefixes.length - 1; ++i) { if (value < factor * 1024) break; factor *= 1024; } this.factor = factor; this.normValue = value / factor; this.doubleValue = value / (double) factor; this.prefix = prefixes[i]; } public long getValue() { return normValue; } public double getDoubleValue() { return doubleValue; } public String getPrefix() { return prefix; } public long getFactor() { return factor; } public String makeUnit(String unit) { return prefix + unit; } public String makePaddedUnit(String unit) { return ((factor == 1) ? " " : "") + prefix + unit; } } ComparisonException.java000066400000000000000000000052101315622671000344160ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils/src/main/java/de/fau/cs/osr/utils/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.utils; import java.io.IOException; import java.io.StringWriter; import java.io.Writer; public class ComparisonException extends Exception { private static final long serialVersionUID = 1L; private final Object a; private final Object b; // ========================================================================= public ComparisonException() { this(null, null); } public ComparisonException(ComparisonException e) { this(e, null, null); } public ComparisonException( Object a, Object b) { this.a = a; this.b = b; } protected ComparisonException( ComparisonException e, Object a, Object b) { super(e); this.a = a; this.b = b; } // ========================================================================= public Object getA() { return a; } public Object getB() { return b; } // ========================================================================= protected String getObjectDesc(Object o) { return o.getClass().getName(); } // ========================================================================= protected Writer toString(Writer w) throws IOException { if ((getA() != null) != (getB() != null)) { if (getA() != null) { w.append(String.format( "Object A of type %s is not null while object B is null", getObjectDesc(getA()))); } else { w.append(String.format( "Object B of type %s is not null while object A is null", getObjectDesc(getB()))); } } else if (getA().getClass() != getB().getClass()) { w.append(String.format( "Two objects differ in type %s vs. %s", getA().getClass().getName(), getB().getClass().getName())); } else { w.append(String.format( "Two objects of type %s differ", getObjectDesc(getA()))); } return w; } @Override public String toString() { try { return toString(new StringWriter()).toString(); } catch (IOException e) { e.printStackTrace(); return null; } } } ConsoleProgressBar.java000066400000000000000000000111011315622671000341750ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils/src/main/java/de/fau/cs/osr/utils/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.utils; import java.io.PrintStream; public class ConsoleProgressBar { /** 0% */ private long from; /** 100% */ private long to; private long cur; private float progress; private int barLength; private int lineLength; private int indicatorStep; private String percentageFormatString; private PrintStream out; private int numRedraw = 0; private String[] indicator = new String[] { "-", "\\", "|", "/" }; // ========================================================================= public ConsoleProgressBar(long from, long to, int barLength) { this.lineLength = -1; setBounds(from, to, from); setBarLength(barLength); setIndicatorStep(1); setPercentageFormatString("%5.1f"); setOut(System.out); } // ========================================================================= public void setBounds(int from, int to) { checkBounds(from, to); this.from = from; this.to = to; update(); } public void setBounds(long from, long to, long cur) { checkBounds(from, to); this.from = from; this.to = to; this.cur = cur; update(); } public long getFrom() { return from; } public void setFrom(long from) { checkBounds(from, this.to); this.from = from; update(); } public long getTo() { return to; } public void setTo(long to) { checkBounds(this.from, to); this.to = to; update(); } public long getCur() { return cur; } public void setCur(long cur) { this.cur = cur; update(); } protected void checkBounds(long from, long to) { if (to <= from) throw new FmtIllegalArgumentException("Illegal bounds!"); } public PrintStream getOut() { return out; } public void setOut(PrintStream out) { this.out = out; } public float getProgress() { return progress; } // ========================================================================= public int getBarLength() { return barLength; } public void setBarLength(int barLength) { invalidate(); this.barLength = barLength; } public int getIndicatorStep() { return indicatorStep; } public void setIndicatorStep(int indicatorStep) { invalidate(); this.indicatorStep = indicatorStep; } public String getPercentageFormatString() { return percentageFormatString; } public void setPercentageFormatString(String percentageFormatString) { invalidate(); this.percentageFormatString = percentageFormatString; } private void invalidate() { this.numRedraw = 0; } // ========================================================================= public void advance() { advance(1); } public void advance(long step) { goTo(this.cur + step); } public void goTo(long cur) { setCur(cur); internalRedraw(); } private void internalRedraw() { if (this.numRedraw % this.indicatorStep == 0) redraw(); ++this.numRedraw; } // ========================================================================= public void update() { this.progress = (this.cur - this.from) / (float) (this.to - this.from); } public void redraw() { String bar; String done; String space; if (this.progress <= 0.f) { done = ""; space = StringTools.strrep(' ', this.barLength); } else if (this.progress >= 1.f) { done = StringTools.strrep('=', this.barLength); space = ""; } else { int numDone = (int) (this.barLength * this.progress); done = StringTools.strrep('=', numDone); space = StringTools.strrep(' ', this.barLength - numDone); } int indPos = (this.numRedraw / this.indicatorStep) % this.indicator.length; bar = String.format( "|%s%s|%s " + this.percentageFormatString, done, space, this.indicator[indPos], this.progress * 100.f); int len = bar.length(); if (len < this.lineLength) bar += StringTools.strrep(' ', this.lineLength - len); this.lineLength = len; this.out.print(bar + '\r'); } public void clear() { out.print(StringTools.strrep(' ', this.lineLength) + '\r'); } } osr-common-osr-common-3.0.8/utils-parent/utils/src/main/java/de/fau/cs/osr/utils/DeepComparer.java000066400000000000000000000136311315622671000330600ustar00rootroot00000000000000/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.utils; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; public class DeepComparer { private static final MapComparerDelegate MAP_DELEGATE = new MapComparerDelegate(); private static final CollectionComparerDelegate COLLECTION_DELEGATE = new CollectionComparerDelegate(); private static final ArrayComparerDelegate ARRAY_DELEGATE = new ArrayComparerDelegate(); private final ArrayList delegates = new ArrayList(); // ========================================================================= /** * Compare two objects for equality. * * @param rootA * First object. * @param rootB * Second object. * @throws ComparisonException * Thrown if the two trees differ. */ public static void compareAndThrow(Object rootA, Object rootB) throws ComparisonException { new DeepComparer().compare(rootA, rootB); } public static boolean compareNoThrow(Object rootA, Object rootB) { try { new DeepComparer().compare(rootA, rootB); return true; } catch (ComparisonException e) { return false; } } // ========================================================================= public DeepComparer() { addDefaultCollectionComparer(); addDefaultMapComparer(); addDefaultArrayComparer(); } public DeepComparer( DeepComparerDelegate comparer0, DeepComparerDelegate... comparersN) { this(); delegates.add(comparer0); for (DeepComparerDelegate c : comparersN) delegates.add(c); } // ========================================================================= public void dropAllComparers() { delegates.clear(); } public void addComparer(DeepComparerDelegate comparer) { delegates.add(0, comparer); } public void addDefaultMapComparer() { addComparer(MAP_DELEGATE); } public void addDefaultCollectionComparer() { addComparer(COLLECTION_DELEGATE); } public void addDefaultArrayComparer() { addComparer(ARRAY_DELEGATE); } // ========================================================================= public void compare(Object a, Object b) throws ComparisonException { if (a == b) return; if ((a == null) != (b == null)) throw new ComparisonException(a, b); int size = delegates.size(); for (int i = 0; i < size; ++i) { DeepComparerDelegate delegate = delegates.get(i); if (delegate.compare(a, b, this)) return; } if (!a.equals(b)) { a.equals(b); throw new ComparisonException(a, b); } } // ========================================================================= public static class ArrayComparerDelegate implements DeepComparerDelegate { @Override public boolean compare(Object a, Object b, DeepComparer comparer) throws ComparisonException { if (!(a.getClass().isArray() && b.getClass().isArray())) return false; Class clazz = a.getClass(); if (!clazz.getComponentType().isPrimitive()) { Object[] aObjA = (Object[]) a; Object[] aObjB = (Object[]) b; int length = aObjA.length; if (aObjB.length != length) throw new ComparisonException(a, b); for (int i = 0; i < length; i++) { Object ac = aObjA[i]; Object bc = aObjB[i]; comparer.compare(ac, bc); } } else { boolean eq; try { Method cmp = Arrays.class.getMethod("equals", clazz, clazz); eq = (Boolean) cmp.invoke(null, a, b); } catch (Exception e) { // This should never happen... throw new RuntimeException("Internal error!", e); } if (!eq) throw new ComparisonException(a, b); } return true; } } public static class CollectionComparerDelegate implements DeepComparerDelegate { @Override public boolean compare(Object _a, Object _b, DeepComparer comparer) throws ComparisonException { if (!((_a instanceof Collection) && (_b instanceof Collection))) return false; Collection a = (Collection) _a; Collection b = (Collection) _b; Iterator e1 = a.iterator(); Iterator e2 = b.iterator(); while (e1.hasNext() && e2.hasNext()) { Object o1 = e1.next(); Object o2 = e2.next(); if ((o1 == null) != (o2 == null)) throw new ComparisonException(a, b); comparer.compare(o1, o2); } if (e1.hasNext() || e2.hasNext()) throw new ComparisonException(a, b); return true; } } public static class MapComparerDelegate implements DeepComparerDelegate { @Override public boolean compare(Object _a, Object _b, DeepComparer comparer) throws ComparisonException { if (!((_a instanceof Map) && (_b instanceof Map))) return false; Map a = (Map) _a; Map b = (Map) _b; if (b.size() != a.size()) throw new ComparisonException(a, b); Iterator i = a.entrySet().iterator(); while (i.hasNext()) { Entry e = (Entry) i.next(); Object key = e.getKey(); Object value = e.getValue(); if (value == null) { if (!(b.get(key) == null && b.containsKey(key))) throw new ComparisonException(a, b); } else { comparer.compare(value, b.get(key)); } } return true; } } } DeepComparerDelegate.java000066400000000000000000000023001315622671000344230ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils/src/main/java/de/fau/cs/osr/utils/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.utils; public interface DeepComparerDelegate { /** * @return Returns false if the two objects cannot be compared by this * delegate. Returns true if the two objects were compared and * turned out to be equal. Otherwise an exception is thrown. * @throws ComparisonException * Thrown if the two objects could be compared by this delegate * and turned out to be different. */ public boolean compare(Object a, Object b, DeepComparer comparer) throws ComparisonException; } DualHashBidiMap.java000066400000000000000000000027561315622671000333600ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils/src/main/java/de/fau/cs/osr/utils/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.utils; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; public class DualHashBidiMap { private final HashMap normal; private final HashMap reverse; public DualHashBidiMap() { this.normal = new HashMap(); this.reverse = new HashMap(); } public DualHashBidiMap(DualHashBidiMap other) { this(); putAll(other.normal); } public void put(Object key, Object value) { this.normal.put(key, value); this.reverse.put(value, key); } private void putAll(Map items) { for (Entry e : items.entrySet()) put(e.getKey(), e.getValue()); } public Object get(Object key) { return this.normal.get(key); } public Object getKey(Object value) { return this.reverse.get(value); } } osr-common-osr-common-3.0.8/utils-parent/utils/src/main/java/de/fau/cs/osr/utils/FileTools.java000066400000000000000000000034571315622671000324170ustar00rootroot00000000000000/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.utils; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; /** * We call the class *Tools to avoid conflicts with Apache Commons. */ public final class FileTools { public static File fillTempFile(String result, String filePrefix) throws IOException { File resultFile = File.createTempFile(filePrefix + "---", ".txt"); resultFile.deleteOnExit(); BufferedWriter out = new BufferedWriter(new FileWriter(resultFile)); out.write(result); out.close(); return resultFile; } /** * Convert non-UNIX line endings into UNIX line endings '\n'. */ public static String lineEndToUnix(String result) { result = result.replace("\r\n", "\n"); result = result.replace("\r", "\n"); return result; } /** * Convert non-UNIX file separators to UNIX file separators '/'. */ public static String fileSeparatorToUnix(String path) { if (File.separatorChar != '/') { if (path.indexOf('/') != -1) throw new IllegalArgumentException("Test code doesn't work properly if path conatins a '/'."); path = path.replace(File.separatorChar, '/'); } return path; } } FmtFileNotFoundException.java000066400000000000000000000020401315622671000353050ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils/src/main/java/de/fau/cs/osr/utils/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.utils; import java.io.FileNotFoundException; public class FmtFileNotFoundException extends FileNotFoundException { private static final long serialVersionUID = -838535884389837008L; public FmtFileNotFoundException() { super(); } public FmtFileNotFoundException(String message, Object... arguments) { super(String.format(message, arguments)); } } FmtIllegalArgumentException.java000066400000000000000000000023601315622671000360320ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils/src/main/java/de/fau/cs/osr/utils/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.utils; public class FmtIllegalArgumentException extends IllegalArgumentException { private static final long serialVersionUID = -3527691839598455338L; public FmtIllegalArgumentException() { super(); } public FmtIllegalArgumentException( Throwable cause, String message, Object... arguments) { super(String.format(message, arguments), cause); } public FmtIllegalArgumentException(String message, Object... arguments) { super(String.format(message, arguments)); } public FmtIllegalArgumentException(Throwable cause) { super(cause); } } FmtInternalLogicError.java000066400000000000000000000022771315622671000346520ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils/src/main/java/de/fau/cs/osr/utils/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.utils; public class FmtInternalLogicError extends Error { private static final long serialVersionUID = -6495020862608442225L; public FmtInternalLogicError() { super(); } public FmtInternalLogicError( Throwable cause, String message, Object... arguments) { super(String.format(message, arguments), cause); } public FmtInternalLogicError(String message, Object... arguments) { super(String.format(message, arguments)); } public FmtInternalLogicError(Throwable cause) { super(cause); } } FmtNotYetImplementedError.java000066400000000000000000000017551315622671000355260ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils/src/main/java/de/fau/cs/osr/utils/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.utils; public class FmtNotYetImplementedError extends Error { private static final long serialVersionUID = -6495020862608442225L; public FmtNotYetImplementedError() { super(); } public FmtNotYetImplementedError(String message, Object... arguments) { super(String.format(message, arguments)); } } FmtRuntimeException.java000066400000000000000000000023101315622671000343740ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils/src/main/java/de/fau/cs/osr/utils/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.utils; public class FmtRuntimeException extends java.lang.RuntimeException { private static final long serialVersionUID = 647896008546620823L; public FmtRuntimeException() { super(); } public FmtRuntimeException( Throwable cause, String message, Object... arguments) { super(String.format(message, arguments), cause); } public FmtRuntimeException(String message, Object... arguments) { super(String.format(message, arguments)); } public FmtRuntimeException(Throwable cause) { super(cause); } } GitRepositoryState.java000066400000000000000000000125721315622671000342620ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils/src/main/java/de/fau/cs/osr/utils/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.utils; import java.io.IOException; import java.io.InputStream; import java.util.Properties; public class GitRepositoryState { public static GitRepositoryState getGitRepositoryState(String resourceName) throws IOException { InputStream resourceAsStream = GitRepositoryState.class.getClassLoader() .getResourceAsStream(resourceName); if (resourceAsStream == null) throw new IOException("Resource not found: " + resourceName); return getGitRepositoryState(resourceAsStream); } private static GitRepositoryState getGitRepositoryState(InputStream resource) throws IOException { if (resource == null) throw new NullPointerException(); Properties properties = new Properties(); properties.load(resource); return new GitRepositoryState(properties); } // ========================================================================= public final String tags; public final String branch; public final String dirty; public final String remoteOriginUrl; public final String commitId; public final String commitIdAbbrev; public final String describe; public final String describeShort; public final String commitUserName; public final String commitUserEmail; public final String commitMessageFull; public final String commitMessageShort; public final String commitTime; public final String closestTagName; public final String closestTagCommitCount; public final String buildUserName; public final String buildUserEmail; public final String buildTime; public final String buildHost; public final String buildVersion; // ========================================================================= public GitRepositoryState(Properties properties) { this.tags = valueToString(properties.get("git.tags")); this.branch = valueToString(properties.get("git.branch")); this.dirty = valueToString(properties.get("git.dirty")); this.remoteOriginUrl = valueToString(properties.get("git.remote.origin.url")); String commitId = valueToString(properties.get("git.commit.id.full")); if (commitId == null) commitId = valueToString(properties.get("git.commit.id")); this.commitId = commitId; this.commitIdAbbrev = valueToString(properties.get("git.commit.id.abbrev")); this.describe = valueToString(properties.get("git.commit.id.describe")); this.describeShort = valueToString(properties.get("git.commit.id.describe-short")); this.commitUserName = valueToString(properties.get("git.commit.user.name")); this.commitUserEmail = valueToString(properties.get("git.commit.user.email")); this.commitMessageFull = valueToString(properties.get("git.commit.message.full")); this.commitMessageShort = valueToString(properties.get("git.commit.message.short")); this.commitTime = valueToString(properties.get("git.commit.time")); this.closestTagName = valueToString(properties.get("git.closest.tag.name")); this.closestTagCommitCount = valueToString(properties.get("git.closest.tag.commit.count")); this.buildUserName = valueToString(properties.get("git.build.user.name")); this.buildUserEmail = valueToString(properties.get("git.build.user.email")); this.buildTime = valueToString(properties.get("git.build.time")); this.buildHost = valueToString(properties.get("git.build.host")); this.buildVersion = valueToString(properties.get("git.build.version")); } private static String valueToString(Object object) { if (object == null) return null; return String.valueOf(object); } // ========================================================================= public String getTags() { return tags; } public String getBranch() { return branch; } public String getDirty() { return dirty; } public String getRemoteOriginUrl() { return remoteOriginUrl; } public String getCommitId() { return commitId; } public String getCommitIdAbbrev() { return commitIdAbbrev; } public String getDescribe() { return describe; } public String getDescribeShort() { return describeShort; } public String getCommitUserName() { return commitUserName; } public String getCommitUserEmail() { return commitUserEmail; } public String getCommitMessageFull() { return commitMessageFull; } public String getCommitMessageShort() { return commitMessageShort; } public String getCommitTime() { return commitTime; } public String getClosestTagName() { return closestTagName; } public String getClosestTagCommitCount() { return closestTagCommitCount; } public String getBuildUserName() { return buildUserName; } public String getBuildUserEmail() { return buildUserEmail; } public String getBuildTime() { return buildTime; } public String getBuildHost() { return buildHost; } public String getBuildVersion() { return buildVersion; } } osr-common-osr-common-3.0.8/utils-parent/utils/src/main/java/de/fau/cs/osr/utils/MovingAverage.java000066400000000000000000000073771315622671000332560ustar00rootroot00000000000000/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.utils; public class MovingAverage { private int movingAvgBucketSizeMs; private boolean firstUpdateValid = false; private long firstUpdate = 0; private int firstBucket = 0; private long currentBucketSum = 0; private long currentBucketCount = 0; private final RingBuffer buffer; private double bufferSum = 0; private long bufferCount = 0; // ========================================================================= public MovingAverage(int movingAvgWindowMs, int movingAvgBucketSizeMs) { this.movingAvgBucketSizeMs = movingAvgBucketSizeMs; this.buffer = new RingBuffer(movingAvgWindowMs / movingAvgBucketSizeMs); } // ========================================================================= // For time measurement only public static long startTimeNs() { return System.nanoTime(); } public void stopTime(long startTimeNs) { long now = System.nanoTime(); update(now, delta(startTimeNs, now)); } /** * @return Delta in milliseconds times factor. */ public double stopTime(long startTimeNs, double factor) { long now = System.nanoTime(); double delta = delta(startTimeNs, now) * factor; update(now, (long) delta); return delta / (1000. * 1000.); } public double getAverageInSec() { // nano -> micro -> milli -> si return getAverage() / (1000. * 1000. * 1000.); } // ========================================================================= // For measurement in general public synchronized double getAverage() { long count = bufferCount; double sum = bufferSum; if (currentBucketCount > 0) { sum += currentBucketSum / (double) currentBucketCount; count++; } if (count == 0) return 0; return sum / (double) count; } public synchronized void update(long nowNs, long value) { if (firstUpdateValid) { long sinceFirstUpdate = delta(firstUpdate, nowNs) / (1000L * 1000); int bucket = (int) (sinceFirstUpdate / movingAvgBucketSizeMs); int advance = bucket - firstBucket; if (advance > buffer.getCapacity()) { reset(); } else if (advance > 0) { firstBucket += advance; if (currentBucketCount > 0) { nextBucket(currentBucketSum / (double) currentBucketCount); advance -= 1; currentBucketSum = 0; currentBucketCount = 0; } for (int i = 0; i < advance; ++i) nextBucket(null); } } else { firstUpdate = nowNs; firstUpdateValid = true; } currentBucketSum += value; currentBucketCount++; } public synchronized void reset() { buffer.clear(); bufferSum = 0; bufferCount = 0; currentBucketSum = 0; currentBucketCount = 0; firstUpdateValid = false; firstBucket = 0; } // ========================================================================= private void nextBucket(Double average) { Double oldest = null; if (buffer.willOverwrite()) oldest = buffer.getOldest(); buffer.add(average); if (average != null) { bufferSum += average; bufferCount++; } if (oldest != null) { bufferSum -= oldest; bufferCount--; } } private long delta(long startTime, long now) { return now - startTime; } } osr-common-osr-common-3.0.8/utils-parent/utils/src/main/java/de/fau/cs/osr/utils/MultiWriter.java000066400000000000000000000023361315622671000330010ustar00rootroot00000000000000/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.utils; import java.io.IOException; import java.io.Writer; public class MultiWriter extends Writer { private final Writer[] writers; public MultiWriter(Writer... writers) { this.writers = writers; } @Override public void write(char[] cbuf, int off, int len) throws IOException { for (Writer w : writers) w.write(cbuf, off, len); } @Override public void flush() throws IOException { for (Writer w : writers) w.flush(); } @Override public void close() throws IOException { for (Writer w : writers) w.close(); } } osr-common-osr-common-3.0.8/utils-parent/utils/src/main/java/de/fau/cs/osr/utils/PrinterBase.java000066400000000000000000000237101315622671000327270ustar00rootroot00000000000000/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.utils; import java.io.PrintWriter; import java.io.StringWriter; import java.io.Writer; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Stack; public class PrinterBase { public PrinterBase(Writer writer) { this.out = new PrintWriter(writer); } // ========================================================================= private final Stack stateStack = new Stack(); private static final class State { public PrintWriter out; public int indent; public int hadNewlines; public int needNewlines; public int eatNewlines; public State( PrintWriter out, int indent, int hadNewlines, int needNewlines, int eatNewlines) { this.out = out; this.indent = indent; this.hadNewlines = hadNewlines; this.needNewlines = needNewlines; this.eatNewlines = eatNewlines; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + eatNewlines; result = prime * result + hadNewlines; result = prime * result + indent; result = prime * result + needNewlines; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; State other = (State) obj; if (eatNewlines != other.eatNewlines) return false; if (hadNewlines != other.hadNewlines) return false; if (indent != other.indent) return false; if (needNewlines != other.needNewlines) return false; return true; } } public State push() { State state = getState(); stateStack.push(state); return state; } public State pop() { return stateStack.pop(); } public State restore() { State state = stateStack.pop(); setState(state); return state; } private State getState() { return new State(out, indent, hadNewlines, needNewlines, eatNewlines); } public void setState(State state) { this.out = state.out; this.indent = state.indent; this.hadNewlines = state.hadNewlines; this.needNewlines = state.needNewlines; this.eatNewlines = state.eatNewlines; } public void setStateNotOut(State state) { this.indent = state.indent; this.hadNewlines = state.hadNewlines; this.needNewlines = state.needNewlines; this.eatNewlines = state.eatNewlines; } // ========================================================================= public final class OutputBuffer { private StringWriter w = new StringWriter(); private State stateOnStart; private State stateOnStop; public OutputBuffer() { stateOnStart = push(); out = new PrintWriter(w); } public void stop() { if (isStopped()) throw new UnsupportedOperationException("Already stopped!"); stateOnStop = getState(); restore(); } public boolean isStopped() { return stateOnStop != null; } public String getBuffer() { return w.toString(); } public void flush() { if (!isStopped()) stop(); setStateNotOut(stateOnStop); out.append(getBuffer()); } public State getStateOnStart() { return stateOnStart; } public State getStateOnStop() { return stateOnStop; } } public OutputBuffer outputBufferStart() { return new OutputBuffer(); } // ========================================================================= private final ArrayList indentStrings = new ArrayList(Arrays.asList("")); private PrintWriter out; private String indentString = "\t"; private int indent = 0; private int hadNewlines = 1; private int needNewlines = 0; private int eatNewlines = 0; // ========================================================================= public void incIndent() { ++indent; while (indentStrings.size() <= indent) indentStrings.add(indentStrings.get(indentStrings.size() - 1) + indentString); } public void decIndent() { assert indent > 0; --indent; } public void indent() { if (eatNewlines > 0) { --eatNewlines; } else { needNewlines(1); if (indent > 0) print(indentStrings.get(indent)); } } public void indent(String text) { indent(); print(text); } public void indent(char ch) { indent(); print(ch); } public void indentln(char ch) { indent(); println(ch); } public void indentln(String text) { indent(); println(text); } public void indentAtBol() { if (atBol()) indent(); } public void indentAtBol(String text) { indentAtBol(); print(text); } public void indentAtBol(char ch) { indentAtBol(); print(ch); } public void indentlnAtBol(char ch) { indentAtBol(); println(ch); } public void indentlnAtBol(String text) { indentAtBol(); println(text); } /** * Don't print already requested newlines. */ public void ignoreNewlines() { needNewlines = 0; } /** * Ignore the next upcoming newline or indent. */ public void eatNewlinesAndIndents(int i) { eatNewlines += i; } public void clearEatNewlinesAndIndents() { eatNewlines = 0; } public void print(char ch) { if (ch == '\n') { println(); } else { flush(); out.print(ch); hadNewlines = 0; eatNewlines = 0; } } public void print(String text) { int from = 0; int length = text.length(); while (from < length) { boolean hadNewline = false; // Find the newline int to = from; int lineSepLength = 1; for (; to < length; ++to) { char ch = text.charAt(to); if (ch == '\r') // Mac { hadNewline = true; if (to + 1 < length && text.charAt(to) == '\n') // Windows lineSepLength = 2; break; } else if (ch == '\n') // Unix { hadNewline = true; break; } } if (to > from) { flush(); out.print(text.substring(from, to)); hadNewlines = 0; eatNewlines = 0; } if (hadNewline) println(); from = to + lineSepLength; } } public void verbatim(String text) { flush(); out.print(text); hadNewlines = (text.isEmpty() || text.charAt(text.length() - 1) != '\n') ? 0 : 1; } public void println() { needNewlines(1); } public void println(char ch) { print(ch); needNewlines(1); } public void println(String text) { print(text); needNewlines(1); } public void println(Object o) { print(o.toString()); needNewlines(1); } public void needNewlines(int i) { if (i > needNewlines) needNewlines = i; } public void capNewlines(int min, int max) { needNewlines = Math.max(min, Math.min(max, needNewlines)); } /** * Are we at the "Beginning Of a Line". */ public boolean atBol() { return needNewlines > eatNewlines || hadNewlines > 0; } public void forceln() { int newlines = needNewlines - hadNewlines; while (newlines-- > 0) { if (eatNewlines > 0) { --eatNewlines; } else { out.println(); ++hadNewlines; } } needNewlines = 0; } public void flush() { forceln(); } // ========================================================================= private final HashMap cache = new HashMap(); private int reuse = 0; private boolean memoize = true; // ========================================================================= public void setMemoize(boolean memoize) { this.memoize = memoize; } public boolean isMemoize() { return memoize; } // ========================================================================= public Memoize memoizeStart(Object node) { if (!memoize) { return new Memoize((Object) null, (State) null); } else { Memoize m = cache.get(new Memoize(node, getState())); if (m == null) { return new Memoize(node, outputBufferStart()); } else { ++reuse; m.getOutputBuffer().flush(); return null; } } } public void memoizeStop(Memoize m) { if (memoize) { m.getOutputBuffer().flush(); cache.put(m, m); } } public void printMemoizationStats() { System.out.format( "% 6d / % 6d / %2.2f\n", cache.size(), reuse, (float) reuse / (float) cache.size()); } // ========================================================================= public static final class Memoize { private final Object o; private final State state; private final OutputBuffer outputBuffer; public Memoize(Object node, State state) { this.o = node; this.state = state; this.outputBuffer = null; } public Memoize(Object node, OutputBuffer outputBuffer) { this.o = node; this.state = outputBuffer.getStateOnStart(); this.outputBuffer = outputBuffer; } public OutputBuffer getOutputBuffer() { return outputBuffer; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((o == null) ? 0 : o.hashCode()); result = prime * result + ((state == null) ? 0 : state.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Memoize other = (Memoize) obj; if (o == null) { if (other.o != null) return false; } else if (o != other.o) return false; if (state == null) { if (other.state != null) return false; } else if (!state.equals(other.state)) return false; return true; } } } ReflectionUtils.java000066400000000000000000000155451315622671000335540ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils/src/main/java/de/fau/cs/osr/utils/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.utils; import java.lang.reflect.Array; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; public class ReflectionUtils { private static final Map, Class> lcToUcTypeMap = new HashMap, Class>(); private static final Map, Class> ucToLcTypeMap = new HashMap, Class>(); private static final Map, String> typeToAbbrev = new HashMap, String>(); private static final Map> abbrevToType = new HashMap>(); // ========================================================================= static { lcToUcTypeMap.put(byte.class, Byte.class); lcToUcTypeMap.put(short.class, Short.class); lcToUcTypeMap.put(int.class, Integer.class); lcToUcTypeMap.put(long.class, Long.class); lcToUcTypeMap.put(float.class, Float.class); lcToUcTypeMap.put(double.class, Double.class); lcToUcTypeMap.put(boolean.class, Boolean.class); lcToUcTypeMap.put(char.class, Character.class); for (Entry, Class> e : lcToUcTypeMap.entrySet()) ucToLcTypeMap.put(e.getValue(), e.getKey()); typeToAbbrev.put(byte.class, "byte"); typeToAbbrev.put(short.class, "short"); typeToAbbrev.put(int.class, "int"); typeToAbbrev.put(long.class, "long"); typeToAbbrev.put(float.class, "float"); typeToAbbrev.put(double.class, "double"); typeToAbbrev.put(boolean.class, "boolean"); typeToAbbrev.put(char.class, "char"); typeToAbbrev.put(Byte.class, "Byte"); typeToAbbrev.put(Short.class, "Short"); typeToAbbrev.put(Integer.class, "Integer"); typeToAbbrev.put(Long.class, "Long"); typeToAbbrev.put(Float.class, "Float"); typeToAbbrev.put(Double.class, "Double"); typeToAbbrev.put(Boolean.class, "Boolean"); typeToAbbrev.put(Character.class, "Character"); typeToAbbrev.put(String.class, "String"); for (Entry, String> e : typeToAbbrev.entrySet()) abbrevToType.put(e.getValue(), e.getKey()); } // ========================================================================= /** * Class.forName() cannot instantiate Class objects for primitive data types * like `int'. This method considers these cases too. * * @param className * The name of the class or the name of a primitive data type. * @return The Class object for the given name. * @throws ClassNotFoundException * If no class for the given name could be found. */ public static Class classForName(String className) throws ClassNotFoundException { if (className.equals("byte")) { return byte.class; } else if (className.equals("short")) { return short.class; } else if (className.equals("int")) { return int.class; } else if (className.equals("long")) { return long.class; } else if (className.equals("float")) { return float.class; } else if (className.equals("double")) { return double.class; } else if (className.equals("boolean")) { return boolean.class; } else if (className.equals("char")) { return char.class; } else if (className.equals("void")) { return void.class; } else { return Class.forName(className); } } /** * Class.isPrimitive only works for the built-in Java types (eg. int, * boolean). This method only works for the "uppercase" variants of Java's * primitive types (eg. Integer, Boolean, ...). * * @param clazz * The class of the type to query. * @return True if it's a "real" primitive data type of one of the * "uppercase" variants, false otherwise. */ public static boolean isExtPrimitive(Class clazz) { return ucToLcTypeMap.containsKey(clazz); } /** * Tells whether a data type is a primitive an "ext" primitive (see * isExtPrimitive) or a String. * * @param clazz * The class of the type to query. * @return True if it's a primitive an "ext" primitive or a String, false * otherwise. */ public static boolean isBasicDataType(Class clazz) { return (clazz.isPrimitive() || isExtPrimitive(clazz) || clazz == String.class); } public static boolean isBasicDataType(String name) { return abbrevToType.containsKey(name); } public static Class mapPrimitiveToUcType(Class clazz) { Class ucType = lcToUcTypeMap.get(clazz); if (ucType == null) throw new IllegalArgumentException("Not a primitive data type!"); return ucType; } public static String abbreviateBasicDataTypeName(Class clazz) { String abbrev = typeToAbbrev.get(clazz); if (abbrev == null) throw new IllegalArgumentException("Not a basic data type!"); return abbrev; } public static Class getTypeFromAbbreviation(String abbrev) { Class type = abbrevToType.get(abbrev); if (type == null) throw new IllegalArgumentException("Not the abbreviation of a basic data type!"); return type; } /** * Creates an array type for the given component type with the given * dimension. * * @param clazz * The component type of the array. * @param dim * The dimension of the array. * @return The Class object describing the array type. */ public static Class arrayClassFor(Class clazz, int dim) { if (dim <= 0) throw new IllegalArgumentException("Invalid dimension"); Class arrayClass = clazz; for (int i = 1; i <= dim; ++i) arrayClass = Array.newInstance(arrayClass, 0).getClass(); return arrayClass; } /** * Get the dimension and element type of an array type. * * @param clazz * The array type. * @return The dimension and element type of the represented array. If the * specified type is not an arry type, the dimension is 0 and the * element type is the specified type itself. */ public static ArrayInfo arrayDimension(Class clazz) { int dim = 0; Class cClass = clazz; while (cClass.isArray()) { cClass = cClass.getComponentType(); ++dim; } return new ArrayInfo(cClass, dim); } // ========================================================================= public static final class ArrayInfo { public final Class elementClass; public final int dim; public ArrayInfo(Class elementClass, int dim) { super(); this.elementClass = elementClass; this.dim = dim; } } } osr-common-osr-common-3.0.8/utils-parent/utils/src/main/java/de/fau/cs/osr/utils/RingBuffer.java000066400000000000000000000036511315622671000325440ustar00rootroot00000000000000/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.utils; import java.util.Iterator; import java.util.NoSuchElementException; public class RingBuffer implements Iterable { private final T[] buffer; private int fill = 0; private int start = 0; @SuppressWarnings("unchecked") public RingBuffer(int capacity) { this.buffer = (T[]) new Object[capacity]; } public void add(T x) { buffer[(start + fill) % buffer.length] = x; if (willOverwrite()) { ++start; start %= buffer.length; } else { ++fill; } } public boolean willOverwrite() { return fill == buffer.length; } public T getOldest() { if (fill == 0) throw new UnsupportedOperationException(); return buffer[start]; } @Override public Iterator iterator() { return new Iterator() { private int i = 0; @Override public boolean hasNext() { return i < fill; } @Override public T next() { if (!hasNext()) throw new NoSuchElementException(); return (T) buffer[(start + i++) % buffer.length]; } @Override public void remove() { throw new UnsupportedOperationException(); } }; } public int size() { return fill; } public int getCapacity() { return buffer.length; } public void clear() { start = 0; fill = 0; } } SimpleConsoleOutput.java000066400000000000000000000047121315622671000344300ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils/src/main/java/de/fau/cs/osr/utils/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.utils; public class SimpleConsoleOutput { private boolean quiet; // ========================================================================= public boolean isQuiet() { return quiet; } public void setQuiet(boolean quiet) { this.quiet = quiet; } // ========================================================================= // Print information to console // ========================================================================= public void echoQuoted(String x) { if (!quiet) printQuoted(x); } public static void printQuoted(String x) { System.out.print("\"\"\""); System.out.print(x); System.out.println("\"\"\""); } public void echoSep(String title) { if (!quiet) printSep(title); } public static void printSep(String title) { System.out.println(formatSepLine(0, title)); } public void echoSep(int indent, String title) { if (!quiet) printSep(indent, title); } public static void printSep(int indent, String title) { System.out.println(formatSepLine(indent, title)); } public void echoBigSep(String title) { if (!quiet) printBigSep(title); } public static void printBigSep(String title) { System.out.println(); String eq80 = StringTools.strrep("=", 80); String sp76 = StringTools.strrep(" ", 76); String spX = StringTools.strrep(" ", Math.max(75 - title.length(), 1)); System.out.println(eq80); System.out.println("==" + sp76 + "=="); System.out.println("== " + title + spX + "=="); System.out.println("==" + sp76 + "=="); System.out.println(eq80); System.out.println(); } public static String formatSepLine(int indent, String title) { String sep = StringTools.strrep(' ', indent) + "--[ " + title + " ]"; String line = sep + StringTools.strrep("-", Math.max(80 - sep.length(), 2)); return line; } } osr-common-osr-common-3.0.8/utils-parent/utils/src/main/java/de/fau/cs/osr/utils/SpeedMeter.java000066400000000000000000000052031315622671000325430ustar00rootroot00000000000000/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.utils; public class SpeedMeter { private static final int MAX_BUFFER_SIZE = 1 << 16; private final double windowSizeInSeconds; private final AccumulatingRingBufferLong measurements; private final AccumulatingRingBufferLong timestamps; // ========================================================================= public SpeedMeter( double windowSizeInSeconds, double expectedMeasurementsPerSecond) { this(windowSizeInSeconds, (int) (windowSizeInSeconds * expectedMeasurementsPerSecond)); } public SpeedMeter( double windowSizeInSeconds, int bufferSize) { if (bufferSize <= 0) throw new IllegalArgumentException(); if (bufferSize > MAX_BUFFER_SIZE) throw new IllegalArgumentException(); this.windowSizeInSeconds = windowSizeInSeconds; this.measurements = new AccumulatingRingBufferLong(bufferSize); this.timestamps = new AccumulatingRingBufferLong(bufferSize); } // ========================================================================= public void addValue(long value) { addValue(value, System.nanoTime()); } public void addValue(long value, long nanoTime) { while (timestamps.getN() > 0) { double age = (nanoTime - timestamps.getOldest()) / 1.e9; if (age < windowSizeInSeconds) break; timestamps.removeOldestN(1); measurements.removeOldestN(1); } timestamps.add(nanoTime); measurements.add(value); } public void addValueIfNew(long value, long nowNano) { if ((measurements.getN() == 0) || (measurements.getNewest() != value)) addValue(value, nowNano); } public double speed() { return speed(timestamps.getNewest()); } public double speed(long nowNanos) { long deltaX = measurements.getNewest() - measurements.getOldest(); long deltaT = nowNanos - timestamps.getOldest(); return deltaX / (deltaT / 1.e9); } public double average() { return measurements.getSum().doubleValue() / measurements.getN(); } public boolean hasMeasurements() { return measurements.getN() > 0; } } osr-common-osr-common-3.0.8/utils-parent/utils/src/main/java/de/fau/cs/osr/utils/StopWatch.java000066400000000000000000000034061315622671000324250ustar00rootroot00000000000000/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.utils; /** * A class to help benchmark code. It simulates a stop watch. */ public class StopWatch { private long startTime = -1; private long stopTime = -1; private boolean running = false; // ========================================================================= public StopWatch start() { if (!running) { startTime = System.currentTimeMillis(); running = true; } return this; } public StopWatch restart() { startTime = System.currentTimeMillis(); running = true; return this; } public StopWatch stop() { if (running) { stopTime = System.currentTimeMillis(); running = false; } return this; } /** * Returns elapsed time in milliseconds or 0 if the watch has never been * started. */ public long getElapsedTime() { if (startTime == -1) { return 0; } if (running) { return System.currentTimeMillis() - startTime; } else { return stopTime - startTime; } } public boolean isRunning() { return running; } public StopWatch reset() { startTime = -1; stopTime = -1; running = false; return this; } } osr-common-osr-common-3.0.8/utils-parent/utils/src/main/java/de/fau/cs/osr/utils/StopWatch2.java000066400000000000000000000032111315622671000325010ustar00rootroot00000000000000/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.utils; public class StopWatch2 { public static StopWatch2 buildAndStart() { StopWatch2 sw = new StopWatch2(); sw.start(); return sw; } // ========================================================================= private long startNanos; private boolean running; // ========================================================================= public StopWatch2() { running = false; } // ========================================================================= public long start() { if (running) throw new IllegalStateException(); startNanos = System.nanoTime(); running = true; return startNanos; } public long stop() { if (!running) throw new IllegalStateException(); long start = startNanos; long stop = System.nanoTime(); startNanos = stop; running = false; return stop - start; } public long stopAndRestart() { long delta = stop(); running = true; return delta; } public void reset() { running = false; } } osr-common-osr-common-3.0.8/utils-parent/utils/src/main/java/de/fau/cs/osr/utils/StringTools.java000066400000000000000000000321071315622671000330000ustar00rootroot00000000000000/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.utils; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.nio.charset.Charset; import java.util.Collection; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.lang3.StringEscapeUtils; import org.apache.commons.lang3.StringUtils; /** * We call the class *Tools to avoid conflicts with Apache Commons. */ public final class StringTools { public static String escHtml(String text) { return escHtml(text, true); } public static String escHtml(String text, boolean forAttribute) { // StringEscapeUtils.escapeHtml(in) does not escape '\'' but a lot of // other stuff that doesn't need escaping. if (text == null) return ""; int n = text.length(); StringBuilder sb = new StringBuilder(n * 4 / 3); for (int i = 0; i < n; i++) { char ch = text.charAt(i); switch (ch) { case ' ': case '\n': case '\t': sb.append(ch); break; case '<': sb.append("<"); break; case '>': sb.append(forAttribute ? ">" : ">"); break; case '&': sb.append("&"); break; case '\'': // ' cannot safely be used, see wikipedia sb.append("'"); break; case '"': sb.append(forAttribute ? """ : "\""); break; default: if ((ch >= 0 && ch < 0x20) || (ch == 0xFE)) { hexCharRef(sb, ch); break; } else if (Character.isHighSurrogate(ch)) { ++i; if (i < n) { char ch2 = text.charAt(i); if (Character.isLowSurrogate(ch2)) { int codePoint = Character.toCodePoint(ch, ch2); switch (Character.getType(codePoint)) { case Character.CONTROL: case Character.PRIVATE_USE: case Character.UNASSIGNED: hexCharRef(sb, codePoint); break; default: sb.append(ch); sb.append(ch2); break; } continue; } } } else if (!Character.isLowSurrogate(ch)) { sb.append(ch); continue; } // No low surrogate followed or only low surrogate throw new IllegalArgumentException("String contains isolated surrogates!"); } } return sb.toString(); } // ========================================================================= public static String escJava(String text) { return StringEscapeUtils.escapeJava(text); } // ========================================================================= public static String hexCharRef(int codePoint) { return String.format("&#x%X;", codePoint); } public static void hexCharRef(StringBuilder sb, int codePoint) { sb.append("&#x"); sb.append(Integer.toHexString(codePoint)); sb.append(';'); } public static String entityRef(String name) { return String.format("&%s;", name); } public static void entityRef(StringBuilder sb, String name) { sb.append('&'); sb.append(name); sb.append(';'); } // ========================================================================= public static String join(Collection c) { StringBuilder b = new StringBuilder(); for (Object o : c) b.append(o.toString()); return b.toString(); } // ========================================================================= public static String strrep(char c, int times) { return StringUtils.repeat( Character.toString(c), times); } public static String strrep(String str, int times) { return StringUtils.repeat(str, times); } // ========================================================================= public static String crop(String str, int length) { return StringUtils.abbreviate(str, length); } // ========================================================================= /** * Indents a text block using the given indent string. * * @param text * The text to indent, may be null. * @param indent * The string to put before the start of each line. * @return The indented text. */ public static String indent(String text, String indent) { if (text == null) return ""; int n = text.length(); StringBuilder result = new StringBuilder(n * 2); result.append(indent); for (int i = 0; i < n; ++i) { char ch = text.charAt(i); result.append(ch); switch (ch) { case '\n': result.append(indent); break; case '\r': if (i + 1 < n && text.charAt(i + 1) == '\n') { result.append('\n'); ++i; } result.append(indent); break; } } return result.toString(); } /** * Indents all but the first line using the given indent string. * * @param text * The text to indent, may be null. * @param indent * The string to put before the start of each but the first line. * @return The indented text. */ public static String indent2(String text, String indent) { if (text == null) return ""; int n = text.length(); StringBuilder result = new StringBuilder(n * 2); for (int i = 0; i < n; ++i) { char ch = text.charAt(i); result.append(ch); switch (ch) { case '\n': result.append(indent); break; case '\r': if (i + 1 < n && text.charAt(i + 1) == '\n') { result.append('\n'); ++i; } result.append(indent); break; } } return result.toString(); } // ========================================================================= /** * Converts a name that's given in camel-case into upper-case, inserting * underscores before upper-case letters. * * @param camelCase * Name in camel-case notation. * @return Name in upper-case notation. */ public static String camelcaseToUppercase(String camelCase) { int n = camelCase.length(); StringBuilder upperCase = new StringBuilder(n * 4 / 3); for (int i = 0; i < n; ++i) { char ch = camelCase.charAt(i); if (Character.isUpperCase(ch)) { upperCase.append('_'); upperCase.append(ch); } else { upperCase.append(Character.toUpperCase(ch)); } } return upperCase.toString(); } public static String startWithUppercase(String name) { if (name == null) throw new NullPointerException(); if (name.isEmpty()) return name; return name.substring(0, 1).toUpperCase() + name.substring(1); } // ========================================================================= public static boolean hasIsolatedSurrogates(String text) { final int length = text.length(); for (int i = 0; i < length; ++i) { char ch = text.charAt(i); if (Character.isHighSurrogate(ch)) { ++i; if (i < length) { char ch2 = text.charAt(i); if (!Character.isLowSurrogate(ch2)) return true; } else return true; } else if (Character.isLowSurrogate(ch)) return true; } return false; } // ========================================================================= public static boolean hasParagraphSeparators(String text) { final int length = text.length(); for (int i = 0; i < length; ++i) { char ch = text.charAt(i); if (ch == '\n') { outer: for (++i; i < length; ++i) { char ch2 = text.charAt(i); switch (ch2) { case ' ': case '\t': break; case '\n': return true; default: break outer; } } } } return false; } // ========================================================================= public static String trim(String text) { int from = 0; int length = text.length(); while ((from < length) && (Character.isWhitespace(text.charAt(from)))) ++from; while ((from < length) && (Character.isWhitespace(text.charAt(length - 1)))) --length; if (from > 0 || length < text.length()) { return text.substring(from, length); } else { return text; } } public static String trimUnderscores(String text) { int from = 0; int length = text.length(); while ((from < length) && (text.charAt(from) == '_')) ++from; while ((from < length) && (text.charAt(length - 1) == '_')) --length; if (from > 0 || length < text.length()) { return text.substring(from, length); } else { return text; } } public static String trimLeft(String text) { int from = 0; int length = text.length(); while ((from < length) && (Character.isWhitespace(text.charAt(from)))) ++from; if (from > 0) { return text.substring(from, length); } else { return text; } } public static String trimRight(String text) { int length = text.length(); while ((0 < length) && (Character.isWhitespace(text.charAt(length - 1)))) --length; if (length < text.length()) { return text.substring(0, length); } else { return text; } } // ========================================================================= public static boolean isWhitespace(String text) { if (text == null) throw new NullPointerException(); return StringUtils.isWhitespace(text); } /** * Collapses a sequence of multiple whitespace characters into a single * space. Does NOT trim the string. */ public static String collapseWhitespace(String trim) { if (trim.isEmpty()) return trim; StringBuilder b = new StringBuilder(trim.length()); for (int i = 0; i < trim.length(); ++i) { char ch = trim.charAt(i); if (Character.isWhitespace(ch)) { b.append(' '); int j = i + 1; while (j < trim.length() && Character.isWhitespace(trim.charAt(j))) ++j; i = j - 1; } else b.append(ch); } return b.toString(); } // ========================================================================= public static String urlDecode(String text) { StringBuilder b = new StringBuilder(); for (int i = 0; i < text.length(); ++i) { char ch = text.charAt(i); if (ch == '%' && i + 2 < text.length()) { String num = text.substring(i + 1, i + 3); try { int val = Integer.valueOf(num, 16); if (val >= 0x20 && val < 0x7F) { ch = (char) val; i += 2; } } catch (NumberFormatException e) { } } else if (ch == '+') { ch = ' '; } b.append(ch); } return b.toString(); } public static String xmlDecode(String text, XmlEntityResolver resolver) { Pattern rx = XmlGrammar.xmlReference(); int start = 0; StringBuilder b = new StringBuilder(); while (true) { Matcher m = rx.matcher(text); if (m.find(start)) { b.append(text.substring(start, m.start())); String resolved = null; if (m.group(1) != null) { resolved = resolver.resolveXmlEntity(m.group(1)); } else { try { boolean decimal = m.group(2) != null; String num = decimal ? m.group(2) : m.group(3); int val = Integer.valueOf(num, decimal ? 10 : 16); if (val >= 0x20 && val != 0x7F) resolved = String.valueOf((char) val); } catch (NumberFormatException e) { } } if (resolved != null) b.append(resolved); else b.append(text.substring(m.start(), m.end())); start = m.end(); } else { if (start < text.length()) b.append(text.substring(start)); break; } } return b.toString(); } public static String safeFilename(String fileTitle) { final int MAX_LENGTH = 128; final int ABBREV_LENGTH = MAX_LENGTH - 32; Charset utf8 = Charset.forName("UTF8"); String abbrev = null; StringBuilder b = new StringBuilder(); for (int i = 0; i < fileTitle.length(); ++i) { char ch = fileTitle.charAt(i); switch (ch) { case ' ': case '_': b.append(ch); break; default: if ((ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z')) { b.append(ch); } else { byte[] bytes; bytes = fileTitle.substring(i, i + 1).getBytes(utf8); if (b.length() > ABBREV_LENGTH - 3 * bytes.length && abbrev == null) abbrev = b.toString(); for (byte unit : bytes) b.append(String.format("%%%02X", unit)); } } if (b.length() >= ABBREV_LENGTH && abbrev == null) abbrev = b.toString(); } String safe = b.toString(); if (abbrev != null && safe.length() > MAX_LENGTH) safe = abbrev + "-" + DigestUtils.md5Hex(fileTitle); return safe; } public static String decodeUsingDefaultCharset(String url) { try { return URLDecoder.decode(url, Charset.defaultCharset().name()); } catch (UnsupportedEncodingException e) { throw new WrappedException(e); } } } ThreadedStreamReader.java000066400000000000000000000031031315622671000344430ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils/src/main/java/de/fau/cs/osr/utils/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.utils; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.StringWriter; public class ThreadedStreamReader extends Thread { private final InputStream is; private final String type; private final StringWriter sink; // ========================================================================= public ThreadedStreamReader(InputStream is, String type, StringWriter sink) { this.is = is; this.type = type; this.sink = sink; start(); } // ========================================================================= @Override public void run() { try { InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line = null; while ((line = br.readLine()) != null) sink.write(type + "> " + line + "\n"); } catch (IOException e) { } } } osr-common-osr-common-3.0.8/utils-parent/utils/src/main/java/de/fau/cs/osr/utils/TimeoutProcess.java000066400000000000000000000034061315622671000334760ustar00rootroot00000000000000/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.utils; import java.util.concurrent.TimeoutException; public class TimeoutProcess extends Thread { private final Process process; private Integer exit; // ========================================================================= protected TimeoutProcess(Process process) { this.process = process; } // ========================================================================= public static int waitFor(Process process, int millis) throws TimeoutException, InterruptedException { TimeoutProcess waiter = new TimeoutProcess(process); waiter.start(); try { waiter.join(millis); if (waiter.exit == null) throw new TimeoutException(); return waiter.exit; } catch (InterruptedException e) { waiter.interrupt(); Thread.currentThread().interrupt(); throw e; } finally { process.destroy(); } } // ========================================================================= public void run() { try { exit = process.waitFor(); } catch (InterruptedException e) { // Ignore } } public Integer getExit() { return exit; } } osr-common-osr-common-3.0.8/utils-parent/utils/src/main/java/de/fau/cs/osr/utils/Tuple.java000066400000000000000000000016711315622671000316040ustar00rootroot00000000000000/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.utils; public final class Tuple { public static Tuple2 from(T1 _1, T2 _2) { return new Tuple2(_1, _2); } public static Tuple3 from(T1 _1, T2 _2, T3 _3) { return new Tuple3(_1, _2, _3); } } osr-common-osr-common-3.0.8/utils-parent/utils/src/main/java/de/fau/cs/osr/utils/Tuple2.java000066400000000000000000000033431315622671000316640ustar00rootroot00000000000000/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.utils; import java.io.Serializable; @SuppressWarnings("serial") public final class Tuple2 implements Cloneable, Serializable { public T1 _1; public T2 _2; Tuple2(T1 _1, T2 _2) { this._1 = _1; this._2 = _2; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((_1 == null) ? 0 : _1.hashCode()); result = prime * result + ((_2 == null) ? 0 : _2.hashCode()); return result; } @SuppressWarnings("unchecked") @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Tuple2 other = (Tuple2) obj; if (_1 == null) { if (other._1 != null) return false; } else if (!_1.equals(other._1)) return false; if (_2 == null) { if (other._2 != null) return false; } else if (!_2.equals(other._2)) return false; return true; } @Override public String toString() { return "(" + _1 + ", " + _2 + ")"; } } osr-common-osr-common-3.0.8/utils-parent/utils/src/main/java/de/fau/cs/osr/utils/Tuple3.java000066400000000000000000000037651315622671000316750ustar00rootroot00000000000000/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.utils; import java.io.Serializable; @SuppressWarnings("serial") public final class Tuple3 implements Cloneable, Serializable { public T1 _1; public T2 _2; public T3 _3; Tuple3(T1 _1, T2 _2, T3 _3) { this._1 = _1; this._2 = _2; this._3 = _3; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((_1 == null) ? 0 : _1.hashCode()); result = prime * result + ((_2 == null) ? 0 : _2.hashCode()); result = prime * result + ((_3 == null) ? 0 : _3.hashCode()); return result; } @SuppressWarnings("unchecked") @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Tuple3 other = (Tuple3) obj; if (_1 == null) { if (other._1 != null) return false; } else if (!_1.equals(other._1)) return false; if (_2 == null) { if (other._2 != null) return false; } else if (!_2.equals(other._2)) return false; if (_3 == null) { if (other._3 != null) return false; } else if (!_3.equals(other._3)) return false; return true; } @Override public String toString() { return "Tuple3 [_1=" + _1 + ", _2=" + _2 + ", _3=" + _3 + "]"; } } osr-common-osr-common-3.0.8/utils-parent/utils/src/main/java/de/fau/cs/osr/utils/Utils.java000066400000000000000000000042151315622671000316100ustar00rootroot00000000000000/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.utils; public final class Utils { public static D getInstance(Class clazz) { try { return clazz.newInstance(); } catch (InstantiationException e) { throw new FmtRuntimeException( e, "The given class `%s' is either a class which cannot be " + "instantiated this way (abstract class, " + "interface, array class, primitive type, void), " + "or the class has no nullary constructor. The " + "instantiation could also have failed for " + "another reason.", clazz.getName()); } catch (IllegalAccessException e) { throw new FmtRuntimeException( e, "The specified class `%s' is not accessible or its " + "nullary constructor is not accessible.", clazz.getName()); } } // ========================================================================= public static boolean isOneOf(T[] textAlignExpected, T value) { for (T v : textAlignExpected) { if (value.equals(v)) return true; } return false; } public static > T fromString(Class clazz, String name) { try { return Enum.valueOf(clazz, name); } catch (IllegalArgumentException e) { return null; } } @SuppressWarnings({ "rawtypes", "unchecked" }) public static boolean hasConstant( Class> enumClazz, String name) { try { Enum.valueOf((Class) enumClazz, name); return true; } catch (IllegalArgumentException e) { return false; } } } WrappedException.java000066400000000000000000000020661315622671000337140ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils/src/main/java/de/fau/cs/osr/utils/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.utils; public class WrappedException extends RuntimeException { private static final long serialVersionUID = 1L; public WrappedException() { super(); } public WrappedException(String message, Throwable cause) { super(message, cause); } public WrappedException(String message) { super(message); } public WrappedException(Throwable cause) { super(cause); } } XmlEntityResolver.java000066400000000000000000000022711315622671000341100ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils/src/main/java/de/fau/cs/osr/utils/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.utils; public interface XmlEntityResolver { /** * Resolve an XML entity reference like &amp;. The * implementation must recursivly fully resolve the given entity. * * @param name * The name of the XML entity reference to resolve. For * &amp; this would be amp. * @return A string containing the resolved text of the entity or * null if the entity name is unknown. */ String resolveXmlEntity(String name); } osr-common-osr-common-3.0.8/utils-parent/utils/src/main/java/de/fau/cs/osr/utils/XmlGrammar.java000066400000000000000000000117731315622671000325660ustar00rootroot00000000000000/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.utils; import java.util.regex.Pattern; public class XmlGrammar { public final static String RE_XML_NAME_START_CHAR = "(?:" + ":" + "|[A-Z]" + "|_" + "|[a-z]" + "|[\\u00C0-\\u00D6]" + "|[\\u00D8-\\u00F6]" + "|[\\u00F8-\\u02FF]" + "|[\\u0370-\\u037D]" + "|[\\u037F-\\u1FFF]" + "|[\\u200C-\\u200D]" + "|[\\u2070-\\u218F]" + "|[\\u2C00-\\u2FEF]" + "|[\\u3001-\\uD7FF]" + "|[\\uF900-\\uFDCF]" + "|[\\uFDF0-\\uFFFD]" + "|[\uD800\\uDC00-\uDB7F\uDFFF]" + // #x10000-#xEFFFF ")"; public final static String RE_XML_NAME_CHAR = "(?:" + RE_XML_NAME_START_CHAR + "|-" + "|\\." + "|[0-9]" + "|\\u00B7" + "|[\\u0300-\\u036F]" + "|[\\u203F-\\u2040]" + ")"; public final static String RE_XML_NAME = "(" + RE_XML_NAME_START_CHAR + RE_XML_NAME_CHAR + "*)"; public final static String RE_XML_ENTITY_REF = "(?:&" + RE_XML_NAME + ";)"; public final static String RE_XML_CHAR_REF = "(?:&#([0-9]+);|&#x([0-9a-fA-F]+);)"; public final static String RE_XML_REFERENCE = "(?:" + RE_XML_ENTITY_REF + "|" + RE_XML_CHAR_REF + ")"; public final static String RE_XML_CHAR = "(?:" + "[\\u0009\\u000A\\u000D\\u0020-\\uD7FF]" + "|[\\uE000-\\uFFFD]" + "|[\uD800\uDC00-\uDBFF\uDFFF]" + // #x10000-#x10FFFF ")"; private static final String RE_XML_COMMENT_TEXT = "((?:" + "(?!-)" + RE_XML_CHAR + "|-(?!-)" + RE_XML_CHAR + ")*)"; // ========================================================================= private static Pattern xmlName = null; private static Pattern xmlReference = null; private static Pattern xmlCommentText = null; // ========================================================================= public static Pattern xmlName() { if (xmlName == null) synchronized (XmlGrammar.class) { if (xmlName == null) xmlName = Pattern.compile(RE_XML_NAME); } return xmlName; } /** * Matches an XML reference. * * If group(1) is non-empty an XML entity reference was matched. * * If group(2) is non-empty a decimal XML character reference was matched. * * If group(3) is non-empty a sedecimal XML character reference was matched. * * The name of the XML entity or the decimal or sedecimal character index * are stored in the respective group. */ public static Pattern xmlReference() { if (xmlReference == null) synchronized (XmlGrammar.class) { if (xmlReference == null) xmlReference = Pattern.compile(RE_XML_REFERENCE); } return xmlReference; } /** * Matches and captures the comment text inside an XML comment. */ public static Pattern xmlCommentText() { if (xmlCommentText == null) synchronized (XmlGrammar.class) { if (xmlCommentText == null) xmlCommentText = Pattern.compile(RE_XML_COMMENT_TEXT); } return xmlCommentText; } // ========================================================================= public static boolean isChar(int codePoint) { return codePoint == 0x9 || codePoint == 0xA || codePoint == 0xD || (codePoint >= 0x20 && codePoint <= 0xD7FF) || (codePoint >= 0xE000 && codePoint >= 0xFFFD) || (codePoint >= 0x10000 && codePoint <= 0x10FFFF); } public static boolean isNameStartChar(int codePoint) { return codePoint == ':' || codePoint == '_' || (codePoint >= 'A' && codePoint <= 'Z') || (codePoint >= 'a' && codePoint <= 'z') || (codePoint >= 0x00C0 && codePoint <= 0x00D6) || (codePoint >= 0x00D8 && codePoint <= 0x00F6) || (codePoint >= 0x00F8 && codePoint <= 0x02FF) || (codePoint >= 0x0370 && codePoint <= 0x037D) || (codePoint >= 0x037F && codePoint <= 0x1FFF) || (codePoint >= 0x200C && codePoint <= 0x200D) || (codePoint >= 0x2070 && codePoint <= 0x218F) || (codePoint >= 0x2C00 && codePoint <= 0x2FEF) || (codePoint >= 0x3001 && codePoint <= 0xD7FF) || (codePoint >= 0xF900 && codePoint <= 0xFDCF) || (codePoint >= 0xFDF0 && codePoint <= 0xFFFD) || (codePoint >= 0x10000 && codePoint <= 0xEFFFF); } public static boolean isNameChar(int codePoint) { return isNameStartChar(codePoint) || codePoint == '-' || codePoint == '.' || (codePoint >= '0' && codePoint <= '9') || codePoint == 0x00B7 || (codePoint >= 0x0300 && codePoint <= 0x036F) || (codePoint >= 0x203F && codePoint <= 0x2040); } } osr-common-osr-common-3.0.8/utils-parent/utils/src/main/java/de/fau/cs/osr/utils/visitor/000077500000000000000000000000001315622671000313425ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils/src/main/java/de/fau/cs/osr/utils/visitor/Baton.java000066400000000000000000000161021315622671000332500ustar00rootroot00000000000000/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.utils.visitor; /** * All of this object's public API methods must be called as the very last * statement of a {@code visit} method, best as part of the return statement. */ public final class Baton { static final int CODE_QUERIED = -2; static final int JUST_CREATED = -1; /** A value greater than this value indicates that a code has been set. */ static final int CODE_SET_THRESHOLD = 0; static final int REDISPATCH = 1; static final int CONTINUE_SAME_TYPE_OR_REDISPATCH = 2; static final int CONTINUE_ASSIGNABLE_TYPE_OR_REDISPATCH = 3; static final int CONTINUE_SAME_REF = 4; static final int CONTINUE_SAME_TYPE = 5; static final int CONTINUE_ASSIGNABLE_TYPE = 6; static final int SKIP = 7; // ========================================================================= private int code = JUST_CREATED; // ========================================================================= Baton() { } // ========================================================================= /** * The code must be set once before it can be queries again! */ final int queryAndResetCode() { checkCodeSet(); int code = this.code; this.code = CODE_QUERIED; return code; } protected final void checkCodeSet() { if (code <= CODE_SET_THRESHOLD) throw new IllegalStateException("No code set: " + code); } // ========================================================================= public final T redispatch(T returnValue) { setCode(REDISPATCH); return returnValue; } /** * Tell the controller to continue processing of the current object if the * following constraints are satisfied: If the returned object has * the exact same type as the object that was passed to the * {@code visit} method it will be passed on to the next * {@code visit} method in the chain of visitors applicable to this object * type. If the returned object does not fulfill this constraint but * is not {@code null} it will be re-dispatched. If the returned * object is {@code null} the object passed to the {@code visit} method will * not be further processed. */ public final T continueIfSameTypeOrRedispatch(T returnValue) { setCode(CONTINUE_SAME_TYPE_OR_REDISPATCH); return returnValue; } /** * Tell the controller to continue processing of the current object if the * following constraints are satisfied: If the returned object is * assignable to the type of the object that was passed to the * {@code visit} method it will be passed on to the next * {@code visit} method in the chain of visitors applicable to this object * type. If the returned object does not fulfill this constraint but * is not {@code null} it will be re-dispatched. If the returned * object is {@code null} the object passed to the {@code visit} method will * not be further processed. * * Attention: If the return value is assignable but is not * of the same type as the object passed to the {@code visit} method, the * {@code visit} method to which the return value is passed on may * not be the most specific visit method available. This is the * case if another, later visitor offers a more specific method for the * returned object's type. Since no re-dispatch takes place, the controller * keeps using the visit chain for the original object's type. */ public final T continueIfAssignableTypeOrRedispatch(T returnValue) { setCode(CONTINUE_ASSIGNABLE_TYPE_OR_REDISPATCH); return returnValue; } /** * Tell the controller to continue processing of the current object if the * following constraints are satisfied: If the returned object is * the same object (by reference) that was passed to the {@code visit} * method it will be passed on to the next {@code visit} method in * the chain of visitors applicable to this object type. If the * returned object does not fulfill this constraint or is {@code null} * the object passed to the {@code visit} method will not be * further processed. */ public final T continueIfSameRef(T returnValue) { setCode(CONTINUE_SAME_REF); return returnValue; } /** * Tell the controller to continue processing of the current object if the * following constraints are satisfied: If the returned object has * the exact same type as the object that was passed to the * {@code visit} method it will be passed on to the next * {@code visit} method in the chain of visitors applicable to this object * type. If the returned object does not fulfill this constraint or * is {@code null} the object passed to the {@code visit} method * will not be further processed. */ public final T continueIfSameType(T returnValue) { setCode(CONTINUE_SAME_TYPE); return returnValue; } /** * Tell the controller to continue processing of the current object if the * following constraints are satisfied: If the returned object is * assignable to the type of the object that was passed to the * {@code visit} method it will be passed on to the next * {@code visit} method in the chain of visitors applicable to this object * type. If the returned object does not fulfill this constraint or * is {@code null} the object passed to the {@code visit} method * will not be further processed. * * Attention: If the return value is assignable but is not * of the same type as the object passed to the {@code visit} method, the * {@code visit} method to which the return value is passed on may * not be the most specific visit method available. This is the * case if another, later visitor offers a more specific method for the * returned object's type. Since no re-dispatch takes place, the controller * keeps using the visit chain for the original object's type. */ public final T continueIfAssignableType(T returnValue) { setCode(CONTINUE_ASSIGNABLE_TYPE); return returnValue; } /** * Skip further processing of the object passed to this visit method and * just return the specified return value. */ public final T skip(T returnValue) { setCode(SKIP); return returnValue; } protected final void setCode(int setCode) { if (this.code >= CODE_SET_THRESHOLD) throw new IllegalStateException("No code set: " + this.code); this.code = setCode; } } IncompatibleVisitorStackDefinition.java000066400000000000000000000021711315622671000411140ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils/src/main/java/de/fau/cs/osr/utils/visitor/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.utils.visitor; @SuppressWarnings("serial") public class IncompatibleVisitorStackDefinition extends Exception { public IncompatibleVisitorStackDefinition() { super(); } public IncompatibleVisitorStackDefinition(String message, Throwable cause) { super(message, cause); } public IncompatibleVisitorStackDefinition(String message) { super(message); } public IncompatibleVisitorStackDefinition(Throwable cause) { super(cause); } } MultipleVisitMethodsMatchException.java000066400000000000000000000030071315622671000411200ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils/src/main/java/de/fau/cs/osr/utils/visitor/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.utils.visitor; public class MultipleVisitMethodsMatchException extends RuntimeException { private static final long serialVersionUID = 1L; private final Class vClass; private final Class nClass; private final Class arg0; private final Class arg1; public MultipleVisitMethodsMatchException( Class vClass, Class nClass, Class arg0, Class arg1) { this.vClass = vClass; this.nClass = nClass; this.arg0 = arg0; this.arg1 = arg1; } public Class getArg0() { return arg0; } public Class getArg1() { return arg1; } @Override public String toString() { return String.format("" + "vClass: %s\n" + "nClass: %s\n" + "Candidate 1: visit(%s)\n" + "Candidate 2: visit(%s)\n", vClass.getName(), nClass.getName(), arg0.getName(), arg1.getName()); } } StackedVisitorInterface.java000066400000000000000000000030611315622671000367050ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils/src/main/java/de/fau/cs/osr/utils/visitor/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.utils.visitor; public abstract class StackedVisitorInterface { /** * Called before the visitation starts. * * @param node * The node at which the visitation will start. * @return Always returns the node. If an overridden version of this method * returns null the visitation will be aborted. */ protected T before(T node) { return node; } /** * Called after the visitation has finished. This method will not be called * if before() returned false. * * @param node * The node at which the visitation started. * @param result * The result of the visitation. If the visit() method for the * given node doesn't return a value, null is * returned. * @return Returns the result parameter. */ protected Object after(T node, Object result) { return result; } } VisitNotFoundException.java000066400000000000000000000030471315622671000365640ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils/src/main/java/de/fau/cs/osr/utils/visitor/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.utils.visitor; /** * Thrown if a suitable visit() method could not be found for a given node. */ public class VisitNotFoundException extends RuntimeException { private static final long serialVersionUID = 1L; private final Object node; private final VisitorBase visitor; public VisitNotFoundException(VisitorBase visitorBase, Object node2) { super(makeMessage(visitorBase, node2)); this.visitor = visitorBase; this.node = node2; } public Object getNode() { return node; } public VisitorBase getVisitor() { return visitor; } private static String makeMessage(VisitorBase visitorBase, Object node) { final String nodeName = node.getClass().getName(); final String visitorName = visitorBase.getClass().getName(); return "Unable to find visit() method for node of type `" + nodeName + "' in visitor `" + visitorName + "'"; } } VisitingException.java000066400000000000000000000031501315622671000356000ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils/src/main/java/de/fau/cs/osr/utils/visitor/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.utils.visitor; /** * An exception that is thrown by a visitor if a visit() method threw an * exception. It can also be thrown from within a visit() method to wrap an * exception that would have to be caught and handled otherwise. If thrown from * within a visit() method, the visitor will intercept and re-throw the * exception. */ public class VisitingException extends RuntimeException { private static final long serialVersionUID = 1L; private final Object node; public VisitingException(Throwable cause) { super(cause); this.node = null; } public VisitingException(String message, Throwable cause) { super(message, cause); this.node = null; } public VisitingException(Object node, Throwable cause) { super(cause); this.node = node; } public VisitingException(Object node, String message, Throwable cause) { super(message, cause); this.node = node; } public Object getNode() { return node; } } VisitorBase.java000066400000000000000000000063031315622671000343620ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils/src/main/java/de/fau/cs/osr/utils/visitor/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.utils.visitor; public abstract class VisitorBase extends VisitorInterface { private final VisitorLogic logic; // ========================================================================= public VisitorBase() { this.logic = new VisitorLogic(this); } public VisitorBase(VisitorLogic logic) { this.logic = logic; } // ========================================================================= @Override protected abstract Object dispatch(T node); /** * Called before the visitation starts. * * @param node * The node at which the visitation will start. * @return Always returns true. If an overridden version of * this method returns false the visitation will be * aborted. */ @Override protected T before(T node) { return node; } /** * Called after the visitation has finished. This method will not be called * if before() returned null. * * @param node * The node at which the visitation started. * @param result * The result of the visitation. If the visit() method for the * given node doesn't return a value, null is * returned. * @return Returns the result parameter. */ @Override protected Object after(T node, Object result) { return result; } /** * This method is called if no suitable visit() method could be found. If * not overridden, this method will throw an UnvisitableException. * * @param node * The node that should have been visited. * @return The result of the visitation. */ @Override protected Object visitNotFound(T node) { throw new VisitNotFoundException(this, node); } @Override protected Object handleVisitingException(T node, Throwable cause) { throw new VisitingException(node, cause); } // ========================================================================= /** * Start visitation at the given node. * * @param node * The node at which the visitation will start. * @return The result of the visitation. If the visit() method for the given * node doesn't return a value, null is returned. */ public Object go(T node) { T startNode = before(node); if (startNode == null) return null; Object result = dispatch(startNode); return after(node, result); } // ========================================================================= protected final Object resolveAndVisit(T node) { return logic.resolveAndVisit(node); } } VisitorException.java000066400000000000000000000021031315622671000354400ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils/src/main/java/de/fau/cs/osr/utils/visitor/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.utils.visitor; /** * Thrown when an exception occurs during visitation but not inside a visit() * method. */ public class VisitorException extends RuntimeException { private static final long serialVersionUID = 1L; private final Object node; public VisitorException(Object node, Throwable cause) { super(cause); this.node = node; } public Object getNode() { return node; } } VisitorInterface.java000066400000000000000000000045201315622671000354070ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils/src/main/java/de/fau/cs/osr/utils/visitor/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.utils.visitor; public abstract class VisitorInterface { protected abstract Object dispatch(T node); /** * Called before the visitation starts. * * @param node * The node at which the visitation will start. * @return Always returns the node. If an overridden version of this method * returns null the visitation will be aborted. */ protected abstract T before(T node); /** * Called after the visitation has finished. This method will not be called * if before() returned null. * * @param node * The node at which the visitation started. * @param result * The result of the visitation. If the visit() method for the * given node doesn't return a value, null is * returned. * @return Returns the result parameter. */ protected abstract Object after(T node, Object result); /** * This method is called if no suitable visit() method could be found. If * not overridden, this method will throw an UnvisitableException. * * @param node * The node that should have been visited. * @return The result of the visitation. */ protected abstract Object visitNotFound(T node); /** * This method is called if a visit() method throws an exception. If not * overriden, this method will wrap the thrown exception in tot a * VisitingException. * * @param node * The node that was visited when the exception was thrown. * @param cause * The exception that was thrown. * @return The result of the visitation. */ protected abstract Object handleVisitingException(T node, Throwable cause); } VisitorLogic.java000066400000000000000000000202521315622671000345440ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils/src/main/java/de/fau/cs/osr/utils/visitor/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.utils.visitor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Enumeration; import java.util.List; import java.util.Queue; import java.util.concurrent.ConcurrentHashMap; public class VisitorLogic { private static final int LOWER_CAPACITY = 256; private static final int UPPER_CAPACITY = 384; private static final float LOAD_FACTOR = .6f; private static final ConcurrentHashMap CACHE = new ConcurrentHashMap( LOWER_CAPACITY, LOAD_FACTOR); private VisitorInterface visitorImpl; // ========================================================================= public VisitorLogic(VisitorInterface visitorImpl) { this.visitorImpl = visitorImpl; } // ========================================================================= /** * Start visitation at the given node. * * @param node * The node at which the visitation will start. * @return The result of the visitation. If the visit() method for the given * node doesn't return a value, null is returned. */ public final Object go(T node) { T startNode = visitorImpl.before(node); if (startNode == null) return null; Object result = visitorImpl.dispatch(startNode); return visitorImpl.after(node, result); } public void setImpl(VisitorInterface visitorImpl) { this.visitorImpl = visitorImpl; } public VisitorInterface getImpl() { return this.visitorImpl; } public static Object dispatchTo(VisitorInterface modeImpl, T n) { return resolveAndVisit(modeImpl, n); } // ========================================================================= protected final Object resolveAndVisit(T node) { return resolveAndVisit(visitorImpl, node); } protected static Object resolveAndVisit( VisitorInterface visitorImpl, T node) { Class vClass = visitorImpl.getClass(); Class nClass = node.getClass(); Target key = new Target(vClass, nClass); Target cached = CACHE.get(key); try { if (cached == null) cached = findVisit(key); if (cached.getMethod() == null) return visitorImpl.visitNotFound(node); return cached.invoke(visitorImpl, node); } catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof VisitingException) throw (VisitingException) cause; return visitorImpl.handleVisitingException(node, cause); } catch (VisitingException e) { throw e; } catch (VisitNotFoundException e) { throw e; } catch (Exception e) { throw new VisitorException(node, e); } } private static Target findVisit(Target key) throws SecurityException, NoSuchMethodException { Method method = null; final Class vClass = key.getVClass(); final Class nClass = key.getNClass(); List> candidates = new ArrayList>(); // Do a breadth first search in the hierarchy Queue> work = new ArrayDeque>(); work.add(nClass); while (!work.isEmpty()) { Class workItem = work.remove(); try { method = vClass.getMethod("visit", workItem); candidates.add(workItem); } catch (NoSuchMethodException e) { // Consider non-interface classes first Class superclass = workItem.getSuperclass(); if (superclass != null) work.add(superclass); for (Class i : workItem.getInterfaces()) work.add(i); } } if (!candidates.isEmpty()) { Collections.sort(candidates, new Comparator>() { @Override public int compare(Class arg0, Class arg1) { if (arg0 == arg1) { return 0; } else if (arg0.isAssignableFrom(arg1)) { return +1; } else if (arg1.isAssignableFrom(arg0)) { return -1; } else { throw new MultipleVisitMethodsMatchException(vClass, nClass, arg0, arg1); } } }); method = vClass.getMethod("visit", candidates.get(0)); } Target target = new Target(key, method); Target cached = CACHE.putIfAbsent(target, target); if (cached != null) { return cached; } else { // Make sure the target is not swept from the cache ... target.touch(); if (CACHE.size() > UPPER_CAPACITY) sweepCache(); return target; } } private static synchronized void sweepCache() { if (CACHE.size() <= UPPER_CAPACITY) return; Target keys[] = new Target[CACHE.size()]; Enumeration keysEnum = CACHE.keys(); int i = 0; while (i < keys.length && keysEnum.hasMoreElements()) keys[i++] = keysEnum.nextElement(); int length = i; int to = length - LOWER_CAPACITY; quickSelect(keys, length, to); // All elements left of "to" are smaller than all the elements right of // "to". for (int j = 0; j < to; ++j) CACHE.remove(keys[j]); } private static void quickSelect(Target[] keys, int length, int to) { int left = 0; int right = length - 1; while (right >= left) { int pivot = left + (right - left) / 2; pivot = partition(keys, left, right, pivot); if (pivot == to) { break; } else if (pivot < to) { left = pivot + 1; } else { right = pivot - 1; } } } private static int partition(Target[] keys, int left, int right, int pivot) { long pivotValue = keys[pivot].lastUse; swap(keys, pivot, right); int storeIndex = left; for (int i = left; i < right; ++i) { if (keys[i].lastUse < pivotValue) { swap(keys, storeIndex, i); ++storeIndex; } } swap(keys, right, storeIndex); return storeIndex; } private static void swap(Target[] keys, int a, int b) { if (a != b) { Target tmp = keys[a]; keys[a] = keys[b]; keys[b] = tmp; } } // ========================================================================= protected static final class Target implements Comparable { private static long useCounter = 0; private long lastUse = -1; private final Class vClass; private final Class nClass; private final Method method; public Target(Class vClass, Class nClass) { this.vClass = vClass; this.nClass = nClass; this.method = null; } public Target(Target key, Method method) { this.vClass = key.vClass; this.nClass = key.nClass; this.method = method; } public Class getVClass() { return vClass; } public Class getNClass() { return nClass; } public Method getMethod() { return method; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + nClass.hashCode(); result = prime * result + vClass.hashCode(); return result; } @Override public boolean equals(Object obj) { Target other = (Target) obj; if (nClass != other.nClass) return false; if (vClass != other.vClass) return false; return true; } public void touch() { lastUse = ++useCounter; } public Object invoke(VisitorInterface visitor, Object node) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException { touch(); return method.invoke(visitor, node); } @Override public int compareTo(Target o) { // Equality is not possible! return (lastUse < o.lastUse) ? -1 : +1; } @Override public String toString() { return String.format( "Target [%d - %s; %s:%s]", lastUse, method != null ? "O" : "X", vClass.getSimpleName(), nClass.getSimpleName()); } } } VisitorStackController.java000066400000000000000000000406751315622671000366330ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils/src/main/java/de/fau/cs/osr/utils/visitor/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.utils.visitor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.concurrent.ConcurrentHashMap; import de.fau.cs.osr.utils.StringTools; public abstract class VisitorStackController { public static boolean DEBUG = false; private static final String VISIT_METHOD_NAME = "visit"; private static final Class BATON_CLASS = Baton.class; private static final Map CACHES = new HashMap(); // ========================================================================= public static Cache getOrRegisterCache( String name, List> visitorStack) throws IncompatibleVisitorStackDefinition { return getOrRegisterCache(name, visitorStack, .6f, 256, 384); } public static synchronized Cache getOrRegisterCache( String name, List> visitorStack, float loadFactor, int lowerCapacity, int upperCapacity) throws IncompatibleVisitorStackDefinition { Cache cache = CACHES.get(name); if (cache == null) { cache = new Cache(visitorStack, loadFactor, lowerCapacity, upperCapacity); CACHES.put(name, cache); } else { cache.verifyDefinition(visitorStack); } return cache; } public static synchronized boolean dropCache(String name) { return (CACHES.remove(name) != null); } // ========================================================================= private final Cache cache; private StackedVisitorInterface[] visitorStack; private StackedVisitorInterface[] enabledVisitors; private Baton baton; // ========================================================================= protected VisitorStackController( String cacheName, List> visitorStack) throws IncompatibleVisitorStackDefinition { this(getOrRegisterCache(cacheName, visitorStack), visitorStack); } protected VisitorStackController( Cache cache, List> visitorStack) throws IncompatibleVisitorStackDefinition { for (StackedVisitorInterface visitor : visitorStack) { if (visitor == null) throw new NullPointerException("Visitor stack contains s"); } @SuppressWarnings({ "unchecked", "rawtypes" }) int tmp = new HashSet(visitorStack).size(); if (tmp != visitorStack.size()) throw new IllegalArgumentException("Visitor stack contains duplicates!"); cache.verifyDefinition(visitorStack); @SuppressWarnings({ "unchecked" }) StackedVisitorInterface[] stackArray = new StackedVisitorInterface[visitorStack.size()]; this.cache = cache; this.visitorStack = visitorStack.toArray(stackArray); this.enabledVisitors = Arrays.copyOf(this.visitorStack, this.visitorStack.length); } // ========================================================================= public int indexOfVisitor(StackedVisitorInterface visitor) { for (int i = 0; i < visitorStack.length; ++i) { if (visitorStack[i] == visitor) return i; } return -1; } public void setVisitor(int i, StackedVisitorInterface visitor) { if (visitor == null) throw new NullPointerException(); if (cache.cacheDef.visitorStackDef[i] != visitor.getClass()) throw new IllegalArgumentException("Replacement visitor's class does not matched the replaced visitor's class"); visitorStack[i] = visitor; if (isVisitorEnabled(i)) enabledVisitors[i] = visitor; } public StackedVisitorInterface getVisitor(int i) { return visitorStack[i]; } public StackedVisitorInterface getEnabledVisitor(int i) { return enabledVisitors[i]; } public boolean isVisitorEnabled(int i) { return (getEnabledVisitor(i) != null); } public void disableVisitor(int i) { enabledVisitors[i] = null; } public void enableVisitor(int i) { enabledVisitors[i] = visitorStack[i]; } public void setVisitorEnabled(int i, boolean enable) { if (enable) enableVisitor(i); else disableVisitor(i); } // ========================================================================= /** * Start visitation at the given node. * * @param node * The node at which the visitation will start. * @return The result of the visitation. If the visit() method for the given * node doesn't return a value, null is returned. */ public Object go(T node) { T startNode = (T) before(node); this.baton = new Baton(); Object result = resolveAndVisit(startNode); return after(node, result); } protected T before(T node) { T transformed = node; for (int i = 0; i < visitorStack.length; ++i) { if (isVisitorEnabled(i)) { T result = getEnabledVisitor(i).before(transformed); if (result == null) { disableVisitor(i); } else { transformed = result; } } } return transformed; } protected Object after(T node, Object result) { for (int i = 0; i < visitorStack.length; ++i) { if (isVisitorEnabled(i)) result = getEnabledVisitor(i).after(node, result); } return result; } // ========================================================================= protected abstract Object visitNotFound(T node); protected Object handleVisitingException(T node, Throwable cause) { throw new VisitingException(node, cause); } // ========================================================================= protected Object resolveAndVisit(T node) { Class nClass = node.getClass(); VisitChain key = new VisitChain(nClass); VisitChain visiChain = cache.get(key); try { if (visiChain == null) { visiChain = buildVisitChain(key); cache.put(visiChain); } if (visiChain.isEmpty()) { return visitNotFound(node); } else { return visiChain.invokeChain(baton, this, node); } } catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof VisitingException) throw (VisitingException) cause; return handleVisitingException(node, cause); } catch (VisitingException e) { throw e; } catch (VisitNotFoundException e) { throw e; } catch (Exception e) { throw new VisitorException(node, e); } } private VisitChain buildVisitChain(VisitChain key) throws SecurityException, NoSuchMethodException { Class nClass = key.getNodeClass(); List chain = new ArrayList(); for (int i = 0; i < visitorStack.length; ++i) { Class vClass = visitorStack[i].getClass(); Method method = findVisit(vClass, nClass); if (method != null) chain.add(new Link(i, method)); } return new VisitChain(key, chain); } private static Method findVisit(final Class vClass, final Class nClass) throws NoSuchMethodException, SecurityException { Method method = null; List> candidates = new ArrayList>(); // Do a breadth first search in the hierarchy Queue> work = new ArrayDeque>(); work.add(nClass); while (!work.isEmpty()) { Class workItem = work.remove(); try { method = vClass.getMethod(VISIT_METHOD_NAME, BATON_CLASS, workItem); candidates.add(workItem); } catch (NoSuchMethodException e) { // Consider non-interface classes first Class superclass = workItem.getSuperclass(); if (superclass != null) work.add(superclass); for (Class i : workItem.getInterfaces()) work.add(i); } } if (!candidates.isEmpty()) { Collections.sort(candidates, new Comparator>() { @Override public int compare(Class arg0, Class arg1) { if (arg0 == arg1) { return 0; } else if (arg0.isAssignableFrom(arg1)) { return +1; } else if (arg1.isAssignableFrom(arg0)) { return -1; } else { throw new MultipleVisitMethodsMatchException(vClass, nClass, arg0, arg1); } } }); method = vClass.getMethod(VISIT_METHOD_NAME, BATON_CLASS, candidates.get(0)); } return method; } // ========================================================================= protected static final class VisitChain implements Comparable { private static long useCounter = 0; private long lastUse = -1; private final Class nodeClass; private final Link[] chain; public VisitChain(Class nClass) { this.nodeClass = nClass; this.chain = null; } public VisitChain(VisitChain chain, List links) { this.nodeClass = chain.nodeClass; this.chain = links.toArray(new Link[links.size()]); } public Class getNodeClass() { return nodeClass; } public boolean isEmpty() { return (chain.length == 0); } @SuppressWarnings({ "rawtypes" }) public Object invokeChain( Baton baton, VisitorStackController controller, Object node) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException { touch(); // this method must only be called on non-empty chains if (isEmpty()) throw new AssertionError(); Object visitNext = node; // If there are no enabled visitors just return the node itself Object result = node; StackedVisitorInterface[] enabledVisitors = controller.enabledVisitors; int i = 0; chainIter: while (true) { StackedVisitorInterface visitor = enabledVisitors[chain[i].visitorIndex]; if (visitor != null) { if (DEBUG) System.err.println(chain[i].method + ": " + StringTools.crop(visitNext.toString(), 32)); result = chain[i].method.invoke(visitor, baton, visitNext); // We must always query the code to reset it, even if result == null int batonCode = baton.queryAndResetCode(); if (result == null) break chainIter; switch (batonCode) { case Baton.REDISPATCH: // Re-dispatch if instance of nodeClass if (nodeClass.isInstance(result)) result = redispatch(controller, result); // Leave chain break chainIter; case Baton.CONTINUE_SAME_TYPE_OR_REDISPATCH: if (node.getClass() != result.getClass()) { // Re-dispatch if instance of nodeClass if (nodeClass.isInstance(result)) result = redispatch(controller, result); // Leave chain break chainIter; } else { // Continue to next visitor break; } case Baton.CONTINUE_ASSIGNABLE_TYPE_OR_REDISPATCH: if (!node.getClass().isInstance(result)) { // Re-dispatch if instance of nodeClass if (nodeClass.isInstance(result)) result = redispatch(controller, result); // Leave chain break chainIter; } else { // Continue to next visitor break; } case Baton.CONTINUE_SAME_REF: if (visitNext != result) { // Leave chain break chainIter; } else { // Continue to next visitor break; } case Baton.CONTINUE_SAME_TYPE: if (node.getClass() != result.getClass()) { // Leave chain break chainIter; } else { // Continue to next visitor break; } case Baton.CONTINUE_ASSIGNABLE_TYPE: if (!node.getClass().isInstance(result)) { // Leave chain break chainIter; } else { // Continue to next visitor break; } case Baton.SKIP: // Leave chain break chainIter; default: throw new AssertionError(batonCode); } ++i; if (i >= chain.length) break chainIter; visitNext = result; } else { ++i; if (i >= chain.length) break; } } return result; } @SuppressWarnings({ "rawtypes", "unchecked" }) private Object redispatch( VisitorStackController controller, Object visitNext) { if (DEBUG) System.err.println(StringTools.crop(visitNext.toString(), 32)); return controller.resolveAndVisit(visitNext); } public void touch() { lastUse = ++useCounter; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + nodeClass.hashCode(); return result; } @Override public boolean equals(Object obj) { VisitChain other = (VisitChain) obj; if (nodeClass != other.nodeClass) return false; return true; } @Override public int compareTo(VisitChain o) { // Equality is not possible! return (lastUse < o.lastUse) ? -1 : +1; } } // ========================================================================= private static final class Link { private final int visitorIndex; private final Method method; public Link(int visitorIndex, Method method) { this.visitorIndex = visitorIndex; this.method = method; } } // ========================================================================= public static final class Cache { private int lowerCapacity; private int upperCapacity; private final CacheDefinition cacheDef; private final ConcurrentHashMap cache; private Cache(List> visitorStack, float loadFactor, int lowerCapacity, int upperCapacity) { this.lowerCapacity = lowerCapacity; this.upperCapacity = upperCapacity; this.cacheDef = new CacheDefinition(visitorStack); this.cache = new ConcurrentHashMap(lowerCapacity, loadFactor); } private void verifyDefinition( List> visitorStack) throws IncompatibleVisitorStackDefinition { if (!new CacheDefinition(visitorStack).equals(cacheDef)) throw new IncompatibleVisitorStackDefinition("Incompatible visitor stack"); } private VisitChain get(VisitChain key) { return cache.get(key); } private synchronized VisitChain put(VisitChain chain) { VisitChain cached = cache.putIfAbsent(chain, chain); if (cached != null) { return cached; } else { // Make sure the target is not swept from the cache ... chain.touch(); if (cache.size() > upperCapacity) sweepCache(); return chain; } } private synchronized void sweepCache() { if (cache.size() <= upperCapacity) return; VisitChain keys[] = new VisitChain[cache.size()]; Enumeration keysEnum = cache.keys(); int i = 0; while (i < keys.length && keysEnum.hasMoreElements()) keys[i++] = keysEnum.nextElement(); int length = i; Arrays.sort(keys, 0, length); int to = length - lowerCapacity; for (int j = 0; j < to; ++j) cache.remove(keys[j]); } } // ========================================================================= private static final class CacheDefinition { private final int hash; private final Class[] visitorStackDef; public CacheDefinition( List> visitorStack) { @SuppressWarnings("rawtypes") Class[] visitorStackDef = new Class[visitorStack.size()]; int hash = 0; int i = 0; for (StackedVisitorInterface visitor : visitorStack) { visitorStackDef[i] = visitor.getClass(); hash = hash * 13 + visitorStackDef[i].hashCode() * 17; ++i; } this.hash = hash; this.visitorStackDef = visitorStackDef; } @Override public int hashCode() { return hash; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; CacheDefinition other = (CacheDefinition) obj; if (!Arrays.equals(visitorStackDef, other.visitorStackDef)) return false; return true; } } } osr-common-osr-common-3.0.8/utils-parent/utils/src/test/000077500000000000000000000000001315622671000232425ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils/src/test/java/000077500000000000000000000000001315622671000241635ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils/src/test/java/de/000077500000000000000000000000001315622671000245535ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils/src/test/java/de/fau/000077500000000000000000000000001315622671000253265ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils/src/test/java/de/fau/cs/000077500000000000000000000000001315622671000257335ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils/src/test/java/de/fau/cs/osr/000077500000000000000000000000001315622671000265365ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils/src/test/java/de/fau/cs/osr/utils/000077500000000000000000000000001315622671000276765ustar00rootroot00000000000000MovingAverageTest.java000066400000000000000000000023771315622671000340650ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils/src/test/java/de/fau/cs/osr/utils/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.utils; import static org.junit.Assert.assertEquals; import org.junit.Test; public class MovingAverageTest { @Test public void testName() throws Exception { long ms2ns = 1000 * 1000; MovingAverage ma = new MovingAverage(2 * 1000, 500); assertEquals(0., ma.getAverage(), 0.01); ma.update(0 * ms2ns, 10); assertEquals(10., ma.getAverage(), 0.01); ma.update(200 * ms2ns, 20); assertEquals(15., ma.getAverage(), 0.01); ma.update(750 * ms2ns, 45); assertEquals(30., ma.getAverage(), 0.01); ma.update(2600 * ms2ns, 5); assertEquals(25., ma.getAverage(), 0.01); } } TestStringTools.java000066400000000000000000000117221315622671000336140ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils/src/test/java/de/fau/cs/osr/utils/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.utils; import static org.junit.Assert.assertEquals; import org.junit.Assert; import org.junit.Test; public class TestStringTools { @Test public void testEscHtml() { Assert.assertEquals( StringTools.escHtml("<>&'\""), "<>&'""); } @Test public void testCamelcaseToUppercase() { Assert.assertEquals( StringTools.camelcaseToUppercase("camelCase"), "CAMEL_CASE"); } @Test public void testIndent() { String text = "text text text\n" + "text text text\r\n" + "text text text\r" + "text text text."; String indent = " "; Assert.assertEquals( text.replaceAll("(\r\n|\r|\n)", "$1" + indent), StringTools.indent2(text, " ")); } @Test public void testXmlDecode() { Assert.assertEquals("", StringTools.xmlDecode("", resolver)); Assert.assertEquals("ASDF", StringTools.xmlDecode("ASDF", resolver)); Assert.assertEquals("&", StringTools.xmlDecode("&", resolver)); // ---- Assert.assertEquals("&MUHAHA;", StringTools.xmlDecode("&MUHAHA;", resolver)); Assert.assertEquals("&...", StringTools.xmlDecode("&...", resolver)); Assert.assertEquals("...&", StringTools.xmlDecode("...&", resolver)); Assert.assertEquals("...&...", StringTools.xmlDecode("...&...", resolver)); Assert.assertEquals("...&...", StringTools.xmlDecode("...&amp;...", resolver)); // ---- Assert.assertEquals("&#--;", StringTools.xmlDecode("&#--;", resolver)); Assert.assertEquals("�", StringTools.xmlDecode("�", resolver)); Assert.assertEquals(" ...", StringTools.xmlDecode(" ...", resolver)); Assert.assertEquals("... ", StringTools.xmlDecode("... ", resolver)); Assert.assertEquals("... ...", StringTools.xmlDecode("... ...", resolver)); Assert.assertEquals("......", StringTools.xmlDecode("...0;...", resolver)); // ---- Assert.assertEquals("&#x--;", StringTools.xmlDecode("&#x--;", resolver)); Assert.assertEquals("�", StringTools.xmlDecode("�", resolver)); Assert.assertEquals(" ...", StringTools.xmlDecode(" ...", resolver)); Assert.assertEquals("... ", StringTools.xmlDecode("... ", resolver)); Assert.assertEquals("... ...", StringTools.xmlDecode("... ...", resolver)); Assert.assertEquals("... ...", StringTools.xmlDecode("...0;...", resolver)); } @Test public void testUrlDecode() { Assert.assertEquals("", StringTools.urlDecode("")); Assert.assertEquals("ASDF", StringTools.urlDecode("ASDF")); Assert.assertEquals("%", StringTools.urlDecode("%")); // --- Assert.assertEquals("%-", StringTools.urlDecode("%-")); Assert.assertEquals("%--", StringTools.urlDecode("%--")); Assert.assertEquals("%gg", StringTools.urlDecode("%gg")); Assert.assertEquals("%0", StringTools.urlDecode("%0")); Assert.assertEquals("%00", StringTools.urlDecode("%00")); Assert.assertEquals("A", StringTools.urlDecode("%41")); Assert.assertEquals("Aa", StringTools.urlDecode("%41a")); Assert.assertEquals("aA", StringTools.urlDecode("a%41")); Assert.assertEquals("aAa", StringTools.urlDecode("a%41a")); } // ========================================================================= private static final XmlEntityResolver resolver = new XmlEntityResolver() { public String resolveXmlEntity(String name) { if ("amp".equalsIgnoreCase(name)) { return "&"; } else if ("lt".equalsIgnoreCase(name)) { return "<"; } else if ("gt".equalsIgnoreCase(name)) { return ">"; } else if ("nbsp".equalsIgnoreCase(name)) { return "\u00A0"; } else if ("middot".equalsIgnoreCase(name)) { return "\u00B7"; } else if ("mdash".equalsIgnoreCase(name)) { return "\u2014"; } else if ("ndash".equalsIgnoreCase(name)) { return "\u2013"; } else if ("equiv".equalsIgnoreCase(name)) { return "\u2261"; } else { return null; } } }; @Test public void testTrimWithEmptyString() throws Exception { assertEquals("", StringTools.trim("")); } @Test public void testTrimUnderscoresWithEmptyString() throws Exception { assertEquals("", StringTools.trimUnderscores("")); } @Test public void testTrimUnderscoresWithOnlyUnderscores() throws Exception { assertEquals("", StringTools.trimUnderscores("_")); } } osr-common-osr-common-3.0.8/utils-parent/utils/src/test/java/de/fau/cs/osr/utils/TestXmlGrammar.java000066400000000000000000000034151315622671000334530ustar00rootroot00000000000000/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.utils; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.junit.Assert; import org.junit.Test; public class TestXmlGrammar { @Test public void testNonBmpChars() { Pattern p = Pattern.compile(XmlGrammar.RE_XML_NAME_START_CHAR); Matcher m = p.matcher("\uD800\uDC00"); Assert.assertTrue(m.matches()); } @Test public void testXmlName() { Assert.assertTrue(XmlGrammar.xmlName().matcher("a-z").matches()); Assert.assertFalse(XmlGrammar.xmlName().matcher("-z").matches()); Assert.assertTrue(XmlGrammar.xmlName().matcher("\uD800\uDC00-\uDB7F\uDFFE").matches()); Assert.assertFalse(XmlGrammar.xmlName().matcher(" caption").matches()); Assert.assertFalse(XmlGrammar.xmlName().matcher("caption ").matches()); } @Test public void testXmlReference() { Matcher m = XmlGrammar.xmlReference().matcher("0: & 1: & 2: &"); Assert.assertTrue(m.find(0)); Assert.assertEquals("amp", m.group(1)); Assert.assertTrue(m.find(m.end())); Assert.assertEquals("38", m.group(2)); Assert.assertTrue(m.find(m.end())); Assert.assertEquals("26", m.group(3)); } } osr-common-osr-common-3.0.8/utils-parent/utils/src/test/java/de/fau/cs/osr/utils/test1/000077500000000000000000000000001315622671000307365ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils/src/test/java/de/fau/cs/osr/utils/test1/ClassA.java000066400000000000000000000013311315622671000327450ustar00rootroot00000000000000/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.utils.test1; public class ClassA { } osr-common-osr-common-3.0.8/utils-parent/utils/src/test/java/de/fau/cs/osr/utils/test1/ClassB.java000066400000000000000000000013311315622671000327460ustar00rootroot00000000000000/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.utils.test1; public class ClassB { } osr-common-osr-common-3.0.8/utils-parent/utils/src/test/java/de/fau/cs/osr/utils/test2/000077500000000000000000000000001315622671000307375ustar00rootroot00000000000000osr-common-osr-common-3.0.8/utils-parent/utils/src/test/java/de/fau/cs/osr/utils/test2/ClassB.java000066400000000000000000000013311315622671000327470ustar00rootroot00000000000000/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.utils.test2; public class ClassB { } osr-common-osr-common-3.0.8/utils-parent/utils/src/test/java/de/fau/cs/osr/utils/test2/ClassC.java000066400000000000000000000013311315622671000327500ustar00rootroot00000000000000/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.utils.test2; public class ClassC { }