├── core-api-use-cases ├── src │ └── main │ │ ├── resources │ │ ├── headerTemplate.ftl │ │ └── simplelogger.properties │ │ └── java │ │ └── com │ │ └── cyc │ │ └── core │ │ └── examples │ │ ├── advanced │ │ ├── package-info.java │ │ ├── ProofViewMarshallerExample.java │ │ ├── QueryAnswerJustifying.java │ │ └── AdvancedQuerying.java │ │ ├── basics │ │ ├── package-info.java │ │ └── BasicWalkthrough.java │ │ └── impl │ │ ├── package-info.java │ │ └── KnowledgeManagementExample.java ├── lib │ ├── guava-18.0.jar │ ├── classindex-3.4.jar │ ├── commons-lang3-3.4.jar │ ├── jaxb-impl-2.2.6.jar │ ├── jericho-html-3.3.jar │ ├── slf4j-api-1.7.12.jar │ ├── xercesImpl-2.10.0.jar │ ├── xml-apis-1.4.01.jar │ ├── cyc-core-api-1.1.1.jar │ ├── slf4j-simple-1.7.12.jar │ ├── cyc-core-api-1.1.1-javadoc.jar │ ├── cyc-core-api-1.1.1-sources.jar │ ├── cyc-core-client-impl-1.1.1-standalone.jar │ └── cyc-core-client-impl-1.1.1-jar-with-dependencies.jar ├── .gitignore ├── build.xml ├── CHANGELOG.md ├── README.md ├── pom.xml └── LICENSE ├── .gitignore ├── README.md └── LICENSE /core-api-use-cases/src/main/resources/headerTemplate.ftl: -------------------------------------------------------------------------------- 1 | File: ${file.name} 2 | Project: ${projectName} 3 | -------------------------------------------------------------------------------- /core-api-use-cases/lib/guava-18.0.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cycorp/example-code/HEAD/core-api-use-cases/lib/guava-18.0.jar -------------------------------------------------------------------------------- /core-api-use-cases/lib/classindex-3.4.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cycorp/example-code/HEAD/core-api-use-cases/lib/classindex-3.4.jar -------------------------------------------------------------------------------- /core-api-use-cases/lib/commons-lang3-3.4.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cycorp/example-code/HEAD/core-api-use-cases/lib/commons-lang3-3.4.jar -------------------------------------------------------------------------------- /core-api-use-cases/lib/jaxb-impl-2.2.6.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cycorp/example-code/HEAD/core-api-use-cases/lib/jaxb-impl-2.2.6.jar -------------------------------------------------------------------------------- /core-api-use-cases/lib/jericho-html-3.3.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cycorp/example-code/HEAD/core-api-use-cases/lib/jericho-html-3.3.jar -------------------------------------------------------------------------------- /core-api-use-cases/lib/slf4j-api-1.7.12.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cycorp/example-code/HEAD/core-api-use-cases/lib/slf4j-api-1.7.12.jar -------------------------------------------------------------------------------- /core-api-use-cases/lib/xercesImpl-2.10.0.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cycorp/example-code/HEAD/core-api-use-cases/lib/xercesImpl-2.10.0.jar -------------------------------------------------------------------------------- /core-api-use-cases/lib/xml-apis-1.4.01.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cycorp/example-code/HEAD/core-api-use-cases/lib/xml-apis-1.4.01.jar -------------------------------------------------------------------------------- /core-api-use-cases/lib/cyc-core-api-1.1.1.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cycorp/example-code/HEAD/core-api-use-cases/lib/cyc-core-api-1.1.1.jar -------------------------------------------------------------------------------- /core-api-use-cases/lib/slf4j-simple-1.7.12.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cycorp/example-code/HEAD/core-api-use-cases/lib/slf4j-simple-1.7.12.jar -------------------------------------------------------------------------------- /core-api-use-cases/lib/cyc-core-api-1.1.1-javadoc.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cycorp/example-code/HEAD/core-api-use-cases/lib/cyc-core-api-1.1.1-javadoc.jar -------------------------------------------------------------------------------- /core-api-use-cases/lib/cyc-core-api-1.1.1-sources.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cycorp/example-code/HEAD/core-api-use-cases/lib/cyc-core-api-1.1.1-sources.jar -------------------------------------------------------------------------------- /core-api-use-cases/.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | pom.xml.tag 3 | pom.xml.releaseBackup 4 | pom.xml.versionsBackup 5 | pom.xml.next 6 | release.properties 7 | logs/ 8 | *~ 9 | 10 | -------------------------------------------------------------------------------- /core-api-use-cases/lib/cyc-core-client-impl-1.1.1-standalone.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cycorp/example-code/HEAD/core-api-use-cases/lib/cyc-core-client-impl-1.1.1-standalone.jar -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Ignore everything... 2 | /* 3 | /*/ 4 | 5 | # ... Except for these files: 6 | !LICENSE 7 | !*.md 8 | 9 | # ... And these directories: 10 | !/core-api-use-cases/ 11 | 12 | -------------------------------------------------------------------------------- /core-api-use-cases/lib/cyc-core-client-impl-1.1.1-jar-with-dependencies.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cycorp/example-code/HEAD/core-api-use-cases/lib/cyc-core-client-impl-1.1.1-jar-with-dependencies.jar -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Cyc API Examples 2 | ================ 3 | 4 | This repository provides examples of common usage of the Cyc APIs. 5 | 6 | It currently contains the [Core API Use Cases](./core-api-use-cases) project. 7 | 8 | 9 | Contact 10 | ------- 11 | 12 | For questions about these projects, or for issues with using them, please visit the 13 | [Cyc Dev Center issues page](http://dev.cyc.com/issues/). 14 | 15 | 16 | -------------------------------------------------------------------------------- /core-api-use-cases/src/main/java/com/cyc/core/examples/advanced/package-info.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Examples of advanced Core API usage. 3 | */ 4 | package com.cyc.core.examples.advanced; 5 | 6 | /* 7 | * #%L 8 | * File: package-info.java 9 | * Project: Cyc Core API Use Cases 10 | * %% 11 | * Copyright (C) 2015 - 2017 Cycorp, Inc 12 | * %% 13 | * Licensed under the Apache License, Version 2.0 (the "License"); 14 | * you may not use this file except in compliance with the License. 15 | * You may obtain a copy of the License at 16 | * 17 | * http://www.apache.org/licenses/LICENSE-2.0 18 | * 19 | * Unless required by applicable law or agreed to in writing, software 20 | * distributed under the License is distributed on an "AS IS" BASIS, 21 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 22 | * See the License for the specific language governing permissions and 23 | * limitations under the License. 24 | * #L% 25 | */ 26 | -------------------------------------------------------------------------------- /core-api-use-cases/src/main/java/com/cyc/core/examples/basics/package-info.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Examples of basic Core API usage, the type of functionality which is used in almost all 3 | * applications. 4 | */ 5 | package com.cyc.core.examples.basics; 6 | 7 | /* 8 | * #%L 9 | * File: package-info.java 10 | * Project: Cyc Core API Use Cases 11 | * %% 12 | * Copyright (C) 2015 - 2017 Cycorp, Inc 13 | * %% 14 | * Licensed under the Apache License, Version 2.0 (the "License"); 15 | * you may not use this file except in compliance with the License. 16 | * You may obtain a copy of the License at 17 | * 18 | * http://www.apache.org/licenses/LICENSE-2.0 19 | * 20 | * Unless required by applicable law or agreed to in writing, software 21 | * distributed under the License is distributed on an "AS IS" BASIS, 22 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 23 | * See the License for the specific language governing permissions and 24 | * limitations under the License. 25 | * #L% 26 | */ 27 | -------------------------------------------------------------------------------- /core-api-use-cases/src/main/java/com/cyc/core/examples/impl/package-info.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Examples of advanced implementation-specific functionality from the Core Client. 3 | * Features which are useful enough for production but whose API is not yet sufficiently polished to 4 | * be promoted to the Core API (or higher-level APIs) are sometimes added to the Core Client 5 | * (typically to the KB or Query Client modules). These features can be called from the Core Client 6 | * when necessary, but direct calls to the Core Client implementation (or any implementation) should 7 | * be avoided whenever possible. 8 | */ 9 | package com.cyc.core.examples.impl; 10 | 11 | /* 12 | * #%L 13 | * File: package-info.java 14 | * Project: Cyc Core API Use Cases 15 | * %% 16 | * Copyright (C) 2015 - 2017 Cycorp, Inc 17 | * %% 18 | * Licensed under the Apache License, Version 2.0 (the "License"); 19 | * you may not use this file except in compliance with the License. 20 | * You may obtain a copy of the License at 21 | * 22 | * http://www.apache.org/licenses/LICENSE-2.0 23 | * 24 | * Unless required by applicable law or agreed to in writing, software 25 | * distributed under the License is distributed on an "AS IS" BASIS, 26 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 27 | * See the License for the specific language governing permissions and 28 | * limitations under the License. 29 | * #L% 30 | */ 31 | -------------------------------------------------------------------------------- /core-api-use-cases/src/main/resources/simplelogger.properties: -------------------------------------------------------------------------------- 1 | # Copyright 2017 Cycorp, Inc. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | ##| Default logging detail level for all instances of SimpleLogger. 16 | #| Must be one of ("trace", "debug", "info", "warn", or "error"). 17 | #| If not specified, defaults to "info". 18 | org.slf4j.simpleLogger.defaultLogLevel=WARN 19 | 20 | ##| Logging detail level for a SimpleLogger instance named "com.cyc.kb.CONTENT.CHANGES.ASSERTED". 21 | #| Must be one of ("trace", "debug", "info", "warn", or "error"). 22 | #| If not specified, the default logging detail level is used. 23 | org.slf4j.simpleLogger.log.com.cyc.kb.CONTENT.CHANGES.ASSERTED=WARN 24 | 25 | ##| Set to true if you want the current date and time to be included in output messages. 26 | #| Default is false, and will output the number of milliseconds elapsed since startup. 27 | #org.slf4j.simpleLogger.showDateTime=false 28 | 29 | ##| The date and time format to be used in the output messages. 30 | #| The pattern describing the date and time format is the same that is used in java.text.SimpleDateFormat. 31 | #| If the format is not specified or is invalid, the default format is used. 32 | #| The default format is yyyy-MM-dd HH:mm:ss:SSS Z. 33 | #org.slf4j.simpleLogger.dateTimeFormat=yyyy-MM-dd HH:mm:ss:SSS Z 34 | 35 | ##| Set to true if you want to output the current thread name. 36 | #| Defaults to true. 37 | org.slf4j.simpleLogger.showThreadName=false 38 | 39 | ##| Set to true if you want the Logger instance name to be included in output messages. 40 | #| Defaults to true. 41 | #org.slf4j.simpleLogger.showLogName=true 42 | 43 | ##| Set to true if you want the last component of the name to be included in output messages. 44 | #| Defaults to false. 45 | org.slf4j.simpleLogger.showShortLogName=true 46 | -------------------------------------------------------------------------------- /core-api-use-cases/build.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | ${line.separator} 63 | ${line.separator} 64 | Running ${exampleClass} against Cyc server at ${cyc.session.server}... 65 | ${line.separator} 66 | ${line.separator} 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | -------------------------------------------------------------------------------- /core-api-use-cases/CHANGELOG.md: -------------------------------------------------------------------------------- 1 | Core API Use Cases CHANGELOG 2 | ============================ 3 | 4 | For more information, visit the [Cyc Developer Center](http://dev.cyc.com/). 5 | 6 | 7 | 1.1.1 - 2018-01-15 8 | ------------------ 9 | 10 | Project can now be built and run in Apache Ant as well as Apache Maven. 11 | 12 | Examples updated to work against 13 | [Cyc Core API v1.1.1](https://github.com/cycorp/api-suite/releases/tag/core-api-spec-1.1.1). 14 | 15 | 16 | 1.1.0 - 2017-12-21 17 | ------------------ 18 | 19 | Examples updated to work against 20 | [Cyc Core API v1.1.0](https://github.com/cycorp/api-suite/releases/tag/core-api-spec-1.1.0). 21 | 22 | 23 | 1.0.0 - 2017-12-13 24 | ------------------ 25 | 26 | Examples updated to work against 27 | [Cyc Core API v1.0.0](https://github.com/cycorp/api-suite/releases/tag/core-api-spec-1.0.0). 28 | 29 | Note that 1.0.0 is _not backwards-compatible_ with earlier releases. However, future 1.x releases 30 | will be backwards-compatible with 1.0.0, per the [Semantic Versioning 2.0.0](https://semver.org/) 31 | specification. 32 | 33 | 34 | 1.0.0-rc9.0 - 2017-12-12 35 | ------------------------ 36 | 37 | Examples updated to work against Cyc Core API Suite 1.0.0-rc9.0. 38 | Note that 1.0.0-rc9.0 is _not backwards-compatible_ with earlier releases. 39 | 40 | 41 | 1.0.0-rc8.0 - 2017-12-11 42 | ------------------------ 43 | 44 | Examples updated to work against Cyc Core API Suite 1.0.0-rc8. 45 | Note that 1.0.0-rc8 is _not backwards-compatible_ with earlier releases. 46 | 47 | 48 | 1.0.0-rc7.0 - 2017-07-28 49 | ------------------------ 50 | 51 | Examples updated to work against Cyc Core API Suite 1.0.0-rc7.0. 52 | Note that 1.0.0-rc7.0 is _not backwards-compatible_ with earlier releases. 53 | 54 | 55 | 1.0.0-rc6 - 2017-07-19 56 | ---------------------- 57 | 58 | Examples updated to work against Cyc Core API Suite 1.0.0-rc6. 59 | Note that 1.0.0-rc6 is _not backwards-compatible_ with earlier releases. 60 | 61 | 62 | 1.0.0-rc5 - 2015-12-18 63 | ---------------------- 64 | 65 | Examples updated to work against Cyc Core API Suite 1.0.0-rc5. 66 | Note that 1.0.0-rc5 is _not backwards-compatible_ with earlier releases. 67 | 68 | 69 | 1.0.0-rc4 - 2015-10-29 70 | ---------------------- 71 | 72 | Examples updated to work against Cyc Core API Suite 1.0.0-rc4. 73 | Note that 1.0.0-rc4 is _not backwards-compatible_ with earlier releases. 74 | 75 | 76 | 1.0.0-rc3 - 2015-08-14 77 | ---------------------- 78 | 79 | Examples updated to work against Cyc Core API Suite 1.0.0-rc3. 80 | Note that 1.0.0-rc3 is _not backwards-compatible_ with earlier releases. 81 | 82 | 83 | 1.0.0-rc2 - 2015-04-07 84 | ---------------------- 85 | 86 | Examples updated to work against Cyc Core API Suite 1.0.0-rc2. 87 | Note that 1.0.0-rc2 is _not backwards-compatible_ with earlier releases. 88 | 89 | 90 | 1.0.0-rc1 - 2015-03-06 91 | ---------------------- 92 | 93 | Examples are designed to work against Cyc Core API Suite 1.0.0-rc1. 94 | -------------------------------------------------------------------------------- /core-api-use-cases/README.md: -------------------------------------------------------------------------------- 1 | Cyc Core API Use Cases 2 | ====================== 3 | 4 | This project provides examples of common usage of the 5 | [Cyc Core API Suite](https://github.com/cycorp/api-suite). 6 | 7 | Examples are grouped into three difference packages: 8 | 9 | * `com.cyc.core.examples.basics` - Basic usage of common features. 10 | * `com.cyc.core.examples.advanced` - Advanced features. 11 | * `com.cyc.core.examples.impl` - Some features currently only in the Core Client implementation. 12 | 13 | 14 | Requirements 15 | ------------ 16 | 17 | * `JDK 1.8` or greater. 18 | * A suitable Cyc server. 19 | * One of the following: 20 | * [Apache Maven](http://maven.apache.org/), version `3.2` or higher. If you are new to Maven, 21 | you may wish to view the [quick start](http://maven.apache.org/run-maven/index.html). 22 | * [Apache Ant](http://ant.apache.org/), version `1.9` or higher 23 | 24 | 25 | Getting Started 26 | --------------- 27 | 28 | This project is intended to demonstrate common usages of the Cyc APIs. It can be run as either a 29 | Maven project or an Ant project, and it should be straightforward to open the project and view, 30 | modify, and run the examples from any common Java IDE (IntelliJ, NetBeans, Eclipse, etc.) 31 | 32 | Running any code that requires a Cyc server will pop up a GUI panel asking for a Cyc server address. 33 | You may instead specify a Cyc server by setting the Java System property `cyc.session.server` to 34 | your server's location, in the format `[HOST_NAME]:[BASE_PORT]`; e.g., 35 | `cyc.session.server=localhost:3600`. See your IDE's documentation for details. 36 | 37 | Warnings and error messages from the Cyc APIs are logged to the console via SLF4J's SimpleLogger. 38 | If you wish to modify the logging configuration for the Cyc APIs, you can change the settings in 39 | `src/main/resources/simplelogger.properties`. 40 | 41 | **Note:** Running these examples will alter a Cyc server's KB contents. These code samples should 42 | not be run against a production system. 43 | 44 | 45 | ### Maven 46 | 47 | To build the project via Maven: 48 | 49 | mvn clean compile 50 | 51 | You can then run a particular class from the command line. For example, if you wanted to run the 52 | `BasicWalkthrough` class against a Cyc server at `localhost:3600`, you would issue the following 53 | command: 54 | 55 | mvn exec:java -Dexec.mainClass="com.cyc.core.examples.basics.BasicWalkthrough" -Dcyc.session.server=localhost:3600 56 | 57 | 58 | ### Ant 59 | 60 | To build the project and run `com.cyc.core.examples.basics.BasicWalkthrough` against a Cyc server 61 | running at `localhost:3600`, you can simply invoke ant: 62 | 63 | ant 64 | 65 | To run an existing build of the project: 66 | 67 | ant run 68 | 69 | The example class may be overridden with the `exampleClass` property, and the Cyc server location 70 | may be overridden with the `cyc.session.server` property. For example: 71 | 72 | ant run -DexampleClass=com.cyc.core.examples.impl.KnowledgeManagementExample -Dcyc.session.server=someremotehost:3680 73 | 74 | 75 | Knowledge Editing and Ontology Development 76 | ------------------------------------------ 77 | 78 | A Cyc application is only as good as the knowledge in Cyc's KB. Read up on 79 | [ontology development](http://dev.cyc.com/ontology-development/). 80 | 81 | 82 | Further Documentation 83 | --------------------- 84 | 85 | Further API documentation, including Javadocs, is available at 86 | [Cyc Developer Center](http://dev.cyc.com/api/). 87 | 88 | 89 | Contact 90 | ------- 91 | 92 | For questions about the APIs or issues with using them, please visit the 93 | [Cyc Dev Center issues page](http://dev.cyc.com/issues/). 94 | -------------------------------------------------------------------------------- /core-api-use-cases/src/main/java/com/cyc/core/examples/advanced/ProofViewMarshallerExample.java: -------------------------------------------------------------------------------- 1 | package com.cyc.core.examples.advanced; 2 | 3 | /* 4 | * #%L 5 | * File: ProofViewMarshallerExample.java 6 | * Project: Cyc Core API Use Cases 7 | * %% 8 | * Copyright (C) 2013 - 2015 Cycorp, Inc. 9 | * %% 10 | * Licensed under the Apache License, Version 2.0 (the "License"); 11 | * you may not use this file except in compliance with the License. 12 | * You may obtain a copy of the License at 13 | * 14 | * http://www.apache.org/licenses/LICENSE-2.0 15 | * 16 | * Unless required by applicable law or agreed to in writing, software 17 | * distributed under the License is distributed on an "AS IS" BASIS, 18 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 19 | * See the License for the specific language governing permissions and 20 | * limitations under the License. 21 | * #L% 22 | */ 23 | 24 | import com.cyc.kb.Sentence; 25 | import com.cyc.kb.exception.CreateException; 26 | import com.cyc.kb.exception.KbTypeException; 27 | import com.cyc.query.ProofViewGenerator; 28 | import com.cyc.query.ProofViewSpecification; 29 | import com.cyc.query.Query; 30 | import com.cyc.query.QueryAnswer; 31 | import com.cyc.query.exception.ProofViewException; 32 | import com.cyc.query.exception.QueryConstructionException; 33 | import com.cyc.session.SessionManager; 34 | import com.cyc.session.exception.SessionCommunicationException; 35 | import java.io.IOException; 36 | import java.io.OutputStream; 37 | 38 | import static com.cyc.Cyc.Constants.INFERENCE_PSC; 39 | 40 | /** 41 | * A bare-bones, self-contained example of running a query and returning proofview XML. 42 | * 43 | * @author nwinant 44 | */ 45 | public class ProofViewMarshallerExample { 46 | 47 | public static void main(String args[]) { 48 | final String exampleName = ProofViewMarshallerExample.class.getSimpleName(); 49 | try (SessionManager sessionMgr = SessionManager.getInstance()) { 50 | System.out.println("Running " + exampleName + "..."); 51 | ProofViewMarshallerExample example = new ProofViewMarshallerExample(); 52 | example.runExample(); 53 | } catch (Exception ex) { 54 | ex.printStackTrace(System.err); 55 | System.exit(1); 56 | } finally { 57 | System.out.println("... " + exampleName + " concluded."); 58 | System.exit(0); 59 | } 60 | } 61 | 62 | /** 63 | * Create and run a query, keeping the inference around for just long enough afterward that we can 64 | * generate and marshal a proofview to XML. In this example we're just proving a fully-bound 65 | * sentence (note that we can construct a query directly from a Sentence object). 66 | *

67 | * Incidentally, this is a useful technique to create proofviews for old answers (even for 68 | * inferences that were run days or weeks ago): for a given answer, substitute the bindings back 69 | * into the original query that generated it, and then run a new query from the fully-bound query 70 | * sentence. Cyc only needs to prove a single answer, and it can often do so in much less time 71 | * than it originally took to find the answer. Just be aware that it may not be the same 72 | * proof that Cyc arrived at the first time. 73 | *

74 | * Note that we're creating the query in a try-with-resources block: it's important to close the 75 | * inference, otherwise its problem store won't be destroyed and you'll have a memory leak. 76 | * 77 | * @throws KbTypeException 78 | * @throws CreateException 79 | */ 80 | public void runExample() throws KbTypeException, CreateException { 81 | try (Query query = Sentence.get("(genls Emu Bird)").toQuery(INFERENCE_PSC)) { 82 | // Make sure to keep the inference around after it has concluded. Because we're doing this, 83 | // we need to make sure that we clean up after it, which we've done here with a 84 | // try-with-resources block. It's important to close the inference, otherwise its problem 85 | // store won't be destroyed and we'll have a memory leak in Cyc. 86 | query.retainInference(); 87 | 88 | // Get a proof view generator for the first (and in this case, only) answer. 89 | final ProofViewGenerator proofGen 90 | = ProofViewGenerator.get(query.getAnswer(0), ProofViewSpecification.get()); 91 | 92 | // Marshall the proof view to XML; we can use any OutputStream or Writer. 93 | // This will cause the generator to create the proofview if it has not done so already. 94 | proofGen.getMarshaller().marshal(OUT); 95 | } catch (ProofViewException | QueryConstructionException | SessionCommunicationException ex) { 96 | ex.printStackTrace(System.err); 97 | } 98 | } 99 | 100 | private static final OutputStream OUT = new OutputStream() { 101 | @Override 102 | public void write(int b) throws IOException { 103 | System.out.write(b); 104 | } 105 | }; 106 | 107 | } 108 | -------------------------------------------------------------------------------- /core-api-use-cases/src/main/java/com/cyc/core/examples/advanced/QueryAnswerJustifying.java: -------------------------------------------------------------------------------- 1 | package com.cyc.core.examples.advanced; 2 | 3 | /* 4 | * #%L 5 | * File: QueryAnswerJustifying.java 6 | * Project: Cyc Core API Use Cases 7 | * %% 8 | * Copyright (C) 1995 - 2014 Cycorp, Inc 9 | * %% 10 | * Licensed under the Apache License, Version 2.0 (the "License"); 11 | * you may not use this file except in compliance with the License. 12 | * You may obtain a copy of the License at 13 | * 14 | * http://www.apache.org/licenses/LICENSE-2.0 15 | * 16 | * Unless required by applicable law or agreed to in writing, software 17 | * distributed under the License is distributed on an "AS IS" BASIS, 18 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 19 | * See the License for the specific language governing permissions and 20 | * limitations under the License. 21 | * #L% 22 | */ 23 | 24 | import com.cyc.query.ProofView; 25 | import com.cyc.query.ProofViewNode; 26 | import com.cyc.query.ProofViewSpecification; 27 | import com.cyc.query.Query; 28 | import com.cyc.session.SessionManager; 29 | import com.cyc.session.exception.SessionCommunicationException; 30 | import java.io.IOException; 31 | import java.util.Iterator; 32 | import net.htmlparser.jericho.Source; 33 | import net.htmlparser.jericho.TextExtractor; 34 | 35 | /** 36 | * This example runs a simple query, and then computes and displays the justification for the first 37 | * answer that comes back from Cyc. 38 | */ 39 | public class QueryAnswerJustifying { 40 | 41 | public static void main(String[] args) { 42 | final String exampleName = QueryAnswerJustifying.class.getSimpleName(); 43 | try (SessionManager sessionMgr = SessionManager.getInstance()) { 44 | System.out.println("Running " + exampleName + "..."); 45 | Query combinedQuery = Query.get("(and (isa ?X PubliclyHeldCorporation) (stockTickerSymbol ?X ?Y))", "InferencePSC"); 46 | //In order to justify an answer, the inference itself needs to still be present on the Cyc server." 47 | combinedQuery.retainInference(); 48 | 49 | displayAnswerJustification(combinedQuery); 50 | 51 | /* Closing isn't strictly necessary in this case, since we're about to exit the program, 52 | but it's still good form to clean up inferences as soon as you can. 53 | */ 54 | combinedQuery.close(); 55 | } catch (Exception ex) { 56 | ex.printStackTrace(System.err); 57 | System.exit(1); 58 | } finally { 59 | System.out.println("... " + exampleName + " concluded."); 60 | System.exit(0); 61 | } 62 | } 63 | 64 | public static void displayAnswerJustification(final Query query) 65 | throws IOException, SessionCommunicationException { 66 | /* This is the place to set other parameters on the justification that would then be obeyed when 67 | it is populated. Populating the justification fills in all the structures, and makes sure they 68 | have both the detailed structure, and also the relevant natural language strings. 69 | */ 70 | ProofViewSpecification proofViewSpec = ProofViewSpecification.get(); 71 | /* Get the justification for a particular answer. In this case, we get the very first answer 72 | that came back. */ 73 | ProofView proofView = ProofView.getProofView(query.getAnswer(0), proofViewSpec); 74 | displayJustification(proofView); 75 | } 76 | 77 | /* The next two methods show how to traverse a justification. In a real application, you'd probably 78 | want to do something more complicated than this with each of the nodes. */ 79 | public static void displayJustification(final ProofView proofView) 80 | throws IOException { 81 | System.out.println("\n============= Justification ================"); 82 | final Iterator iter = proofView.toDepthFirstIterator(); 83 | while (iter.hasNext()) { 84 | displayJustificationNode(iter.next()); 85 | } 86 | } 87 | 88 | public static void displayJustificationNode(final ProofViewNode node) throws IOException { 89 | final StringBuilder renderer = new StringBuilder(); 90 | // Indent according to node's depth: 91 | for (int i = 0; i < node.getDepth(); i++) { 92 | renderer.append(' '); 93 | } 94 | // Render initially hidden nodes with parens: 95 | final boolean expandInitially = node.isExpandInitially(); 96 | if (!expandInitially) { 97 | renderer.append('('); 98 | } 99 | // Render the node's HTML, or the label: 100 | final String html = node.getHTML(); 101 | if (html == null || html.isEmpty()) { 102 | final String label = node.getLabel(); 103 | if (label != null) { 104 | renderer.append(label); 105 | } 106 | } else { 107 | // Render HTML as text: 108 | new TextExtractor(new Source(html)).appendTo(renderer); 109 | } 110 | if (!expandInitially) { 111 | renderer.append(')'); 112 | } 113 | System.out.println(renderer); 114 | } 115 | 116 | 117 | } 118 | -------------------------------------------------------------------------------- /core-api-use-cases/src/main/java/com/cyc/core/examples/impl/KnowledgeManagementExample.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 Cycorp, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.cyc.core.examples.impl; 18 | 19 | /* 20 | * #%L 21 | * File: KnowledgeManagementExample.java 22 | * Project: Cyc Core API Use Cases 23 | * %% 24 | * Copyright (C) 2013 - 2018 Cycorp, Inc. 25 | * %% 26 | * Licensed under the Apache License, Version 2.0 (the "License"); 27 | * you may not use this file except in compliance with the License. 28 | * You may obtain a copy of the License at 29 | * 30 | * http://www.apache.org/licenses/LICENSE-2.0 31 | * 32 | * Unless required by applicable law or agreed to in writing, software 33 | * distributed under the License is distributed on an "AS IS" BASIS, 34 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 35 | * See the License for the specific language governing permissions and 36 | * limitations under the License. 37 | * #L% 38 | */ 39 | 40 | import com.cyc.kb.Assertion; 41 | import com.cyc.kb.Context; 42 | import com.cyc.kb.client.services.AssertionServiceImpl; 43 | import com.cyc.kb.exception.CreateException; 44 | import com.cyc.kb.exception.KbException; 45 | import com.cyc.kb.exception.KbTypeException; 46 | import com.cyc.session.SessionManager; 47 | import java.io.IOException; 48 | import java.util.List; 49 | 50 | import static com.cyc.Cyc.Constants.UV_MT; 51 | 52 | /** 53 | * This class provides an example of knowledge management (KM) functionality. Note that much 54 | * KM-specific functionality is included not in the Core API, but in other APIs (such as the 55 | * Knowledge Management API) which sit atop it. This is because, while knowledge management is a 56 | * cross-cutting concern at the project level, many applications are domain-focused and 57 | * typically don't provide or require high-level general KM functionality. 58 | * 59 | * @author nwinant 60 | */ 61 | public class KnowledgeManagementExample { 62 | 63 | public static void main(String[] args) { 64 | final String exampleName = KnowledgeManagementExample.class.getSimpleName(); 65 | try (SessionManager sessionMgr = SessionManager.getInstance()) { 66 | System.out.println("Running " + exampleName + "..."); 67 | KnowledgeManagementExample example = new KnowledgeManagementExample(); 68 | example.viewMicrotheoryContents(); 69 | System.out.println(); 70 | } catch (KbException | RuntimeException kbe) { 71 | kbe.printStackTrace(System.err); 72 | System.exit(1); 73 | } catch (IOException ioe) { 74 | System.err.println("Error closing SessionManager"); 75 | ioe.printStackTrace(System.err); 76 | System.exit(1); 77 | } finally { 78 | System.out.println("... " + exampleName + " concluded."); 79 | System.exit(0); 80 | } 81 | } 82 | 83 | /** 84 | * Find all of the assertions that are directly asserted within an Mt (and not those which are 85 | * merely visible from the Mt). 86 | *

87 | * In practice, this is rarely done. There are cases where this method is useful, such as in 88 | * general-purpose knowledge editing applications for the Cyc KB, but it should be used with 89 | * caution. This method is currently not included in the official KB API for two reasons: 90 | *

    91 | *
  1. In practice, it's rarely used: most applications never need to use it, and it would 92 | * in fact be the wrong approach. 93 | * What is much more commonly useful is retrieving relevant answers to a specific question 94 | * (typically as KbTerms from a query) in which case what matters is an assertion's 95 | * visibility from an Mt. 96 | * When applications directly interact with assertions, it is typically by retrieving the 97 | * predicate extent for some relevant KbPredicate, or to create or delete specific 98 | * assertions whose Mt is either already known or easily retrievable.
  2. 99 | *
  3. It's potentially very expensive. Retrieving the contents of a small, application-focused 100 | * Mt is relatively quick, but retrieving the contents of a broad Mt like 101 | * {@code #$UniversalVocabularyMt} may take upwards of an hour or possibly even longer. Even 102 | * some Mts like {@code #$CurrentWorldDataCollectorMt-NonHomocentric} may contain ~10,000 103 | * assertions.
  4. 104 | *
105 | * 106 | * @throws KbTypeException 107 | * @throws CreateException 108 | * @throws IllegalArgumentException if given an expensive Context when not allowed 109 | */ 110 | protected void viewMicrotheoryContents() 111 | throws KbTypeException, CreateException, IllegalArgumentException { 112 | final AssertionServiceImpl assertionSvc = new AssertionServiceImpl(); 113 | final Context ctx = Context.get("CurrentWorldDataCollectorMt-NonHomocentric"); 114 | 115 | final List assertions = assertionSvc.getAllAssertedInContext(ctx); 116 | System.out.println("Assertions in " + ctx + ": "); 117 | assertions 118 | .forEach(assertion -> System.out.println("- " + assertion)); 119 | 120 | final int numAssertions = assertionSvc.getCountOfAllAssertedInContext(ctx); 121 | System.out.println("Number of assertions in " + ctx + ": " + numAssertions); 122 | 123 | try { 124 | final List wayTooManyAssertions = assertionSvc.getAllAssertedInContext(UV_MT); 125 | System.out.println("Assertions in " + UV_MT + ": "); 126 | wayTooManyAssertions 127 | .forEach(assertion -> System.out.println("- " + assertion)); 128 | } catch (IllegalArgumentException ex) { 129 | System.out.println( 130 | "An IllegalArgumentException was thrown when we tried to retrieve all of the" 131 | + " assertions in " + UV_MT + "." 132 | + " We could attempt to force the issue, but it would be unwise to do so."); 133 | } 134 | } 135 | 136 | } 137 | -------------------------------------------------------------------------------- /core-api-use-cases/src/main/java/com/cyc/core/examples/advanced/AdvancedQuerying.java: -------------------------------------------------------------------------------- 1 | package com.cyc.core.examples.advanced; 2 | 3 | /* 4 | * #%L 5 | * File: AdvancedQuerying.java 6 | * Project: Cyc Core API Use Cases 7 | * %% 8 | * Copyright (C) 1995 - 2014 Cycorp, Inc 9 | * %% 10 | * Licensed under the Apache License, Version 2.0 (the "License"); 11 | * you may not use this file except in compliance with the License. 12 | * You may obtain a copy of the License at 13 | * 14 | * http://www.apache.org/licenses/LICENSE-2.0 15 | * 16 | * Unless required by applicable law or agreed to in writing, software 17 | * distributed under the License is distributed on an "AS IS" BASIS, 18 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 19 | * See the License for the specific language governing permissions and 20 | * limitations under the License. 21 | * #L% 22 | */ 23 | import com.cyc.kb.KbCollection; 24 | import com.cyc.kb.KbObject; 25 | import com.cyc.kb.Sentence; 26 | import com.cyc.kb.Variable; 27 | import com.cyc.kb.exception.CreateException; 28 | import com.cyc.kb.exception.KbException; 29 | import com.cyc.kb.exception.KbTypeException; 30 | import com.cyc.query.InferenceStatus; 31 | import com.cyc.query.InferenceSuspendReason; 32 | import com.cyc.query.Query; 33 | import com.cyc.query.QueryAnswer; 34 | import com.cyc.query.QueryAnswers; 35 | import com.cyc.query.QueryListener; 36 | import com.cyc.query.exception.QueryConstructionException; 37 | import com.cyc.query.exception.QueryRuntimeException; 38 | import com.cyc.session.SessionManager; 39 | import com.cyc.session.exception.SessionCommunicationException; 40 | import java.util.Arrays; 41 | import java.util.Collection; 42 | import java.util.HashMap; 43 | import java.util.List; 44 | import java.util.Map; 45 | 46 | import static com.cyc.Cyc.Constants.INFERENCE_PSC; 47 | 48 | public class AdvancedQuerying { 49 | 50 | public static void main(String[] args) { 51 | final String exampleName = AdvancedQuerying.class.getSimpleName(); 52 | try (SessionManager sessionMgr = SessionManager.getInstance()) { 53 | System.out.println("Running " + exampleName + "..."); 54 | demonstrateIncrementalResultsQuery(); 55 | try (Query q = Query.get("(and (genls HomoSapiens ?TYPE) (scientificName ?TYPE ?NAME))", "InferencePSC")) { 56 | if (q.getAnswerCount() > 25) { 57 | System.out.print("First 25 "); 58 | } 59 | System.out.println("Combined query answers:\n "); 60 | displayQueryBindings(q, 25); 61 | } 62 | demonstrateTermSubstitution(); 63 | } catch (Exception ex) { 64 | System.out.println("Problem building or running demo query."); 65 | ex.printStackTrace(System.err); 66 | System.exit(1); 67 | } finally { 68 | System.out.println("... " + exampleName + " concluded."); 69 | System.exit(0); 70 | } 71 | } 72 | 73 | /** 74 | * Demonstrate how terms can be substituted in a Query before it is run. 75 | */ 76 | public static void demonstrateTermSubstitution() { 77 | final Map substitutions = new HashMap<>(); 78 | final KbCollection theSpecies; 79 | try { 80 | theSpecies = KbCollection.findOrCreate("(TheFn BiologicalSpecies)"); 81 | } catch (CreateException | KbTypeException ex) { 82 | throw new RuntimeException("Problem finding or creating indexical.", ex); 83 | } 84 | final List sampleSpecies = Arrays.asList("PlainsZebra", "Ostrich", "HumpbackWhale"); 85 | for (final String species : sampleSpecies) { 86 | try { 87 | final KbCollection kbSpecies = KbCollection.get(species); 88 | if (!kbSpecies.isInstanceOf(KbCollection.get("BiologicalSpecies"))) { 89 | throw new RuntimeException(kbSpecies + " is not known to be a species."); 90 | } else { 91 | final Sentence querySentence = Sentence.get("(and (genls (TheFn BiologicalSpecies) ?TYPE) (scientificName ?TYPE ?NAME))"); 92 | try (Query indexicalQuery = querySentence.toQuery(INFERENCE_PSC)) { 93 | substitutions.put(theSpecies, kbSpecies); 94 | indexicalQuery.setSubstitutions(substitutions); 95 | System.out.println("\nResults for " + species + ": "); 96 | displayQueryBindings(indexicalQuery, 5); 97 | } catch (QueryConstructionException ex) { 98 | throw new RuntimeException(ex); 99 | } 100 | } 101 | } catch (CreateException | KbTypeException | RuntimeException ex) { 102 | System.out.println("Trouble testing " + species + ": " + ex.getLocalizedMessage()); 103 | } 104 | } 105 | } 106 | 107 | /** 108 | * A simple method to traverse and display the bindings for a query. 109 | */ 110 | public static void displayQueryBindings(final Query query, final Integer maxToDisplay) { 111 | final Collection queryVars; 112 | try { 113 | queryVars = query.getQueryVariables(); 114 | } catch (KbException ex) { 115 | throw new RuntimeException("Couldn't get query variables.", ex); 116 | } 117 | System.out.format("%-16s", "Variables:"); 118 | queryVars 119 | .forEach(var -> System.out.format("%-24s", var)); 120 | System.out.println(); 121 | int i = 0; 122 | final QueryAnswers answers; 123 | try { 124 | answers = query.getAnswers(); 125 | } catch (SessionCommunicationException ex) { 126 | throw new RuntimeException("Couldn't get query answers.", ex); 127 | } 128 | for (final QueryAnswer answer : answers) { 129 | final Map bindings = answer.getBindings(); 130 | System.out.format("%-16s", "Answer " + i + ":"); 131 | queryVars 132 | .forEach(var -> System.out.format("%-24s", bindings.get(var))); 133 | System.out.println(); 134 | if (++i >= maxToDisplay) { 135 | break; 136 | } 137 | } 138 | } 139 | 140 | /** 141 | * Sometimes you don't expect all the answers to a query to be returned quickly, and you want to 142 | * be able to do something with them as they come in. Who knows, you might even have some other 143 | * reason for handling the asynchronously. This example shows how to attach a listeners to a query 144 | * for all the major query events. Typically the most interesting ones are changes in the 145 | * inference status (i.e. whether it's running, suspended, etc.) and arrival of new answers. 146 | */ 147 | private static void demonstrateIncrementalResultsQuery() { 148 | // A query that should get lots of results, not all at once: 149 | final Query query; 150 | try { 151 | query = Query.get("(#$and \n" 152 | + "(#$integerBetween 1 ?N 10000) \n" 153 | + "(#$isa ?N #$PrimeNumber))"); 154 | } catch (QueryConstructionException ex) { 155 | throw new RuntimeException("Exception constructing query.", ex); 156 | } 157 | query.setMaxTime(30); 158 | query.setMaxAnswerCount(500); 159 | query.retainInference(); 160 | // Add a listener that will handle important inference events: 161 | query.addListener(new QueryListener() { 162 | @Override 163 | public void notifyInferenceCreated(Query query) { 164 | System.out.println("Created " + query); 165 | } 166 | 167 | @Override 168 | public void notifyInferenceStatusChanged(InferenceStatus oldStatus, 169 | InferenceStatus newStatus, 170 | InferenceSuspendReason suspendReason, 171 | Query query) { 172 | System.out.println("Inference status changed from " + oldStatus + " to " + newStatus); 173 | if (InferenceStatus.SUSPENDED.equals(newStatus)) { 174 | System.out.println("Suspend reason: " + suspendReason); 175 | } 176 | } 177 | 178 | @Override 179 | public void notifyInferenceAnswersAvailable(Query query, List newAnswers) { 180 | int answerCount = query.getAnswerCount(); 181 | System.out.println("New answers! Query now has " + answerCount + " answers."); 182 | try {//Do stuff with an answer: 183 | final QueryAnswer answer = newAnswers.get(newAnswers.size() - 1); 184 | System.out.println("Here is " + answer.getId()); 185 | for (final Variable var : query.getQueryVariables()) { 186 | System.out.println(var + " -> " + answer.getBinding(var)); 187 | } 188 | } catch (KbException ex) { 189 | 190 | } 191 | if (answerCount >= 1000) { 192 | System.out.println("Got enough answers. Terminating query."); 193 | query.stop(null); 194 | } 195 | } 196 | 197 | @Override 198 | public void notifyInferenceTerminated(Query query, Exception e) { 199 | System.out.println("Query terminated."); 200 | } 201 | }); 202 | try { 203 | // Start the inference. This won't return until the inference terminates: 204 | query.performInference(); 205 | } catch (QueryRuntimeException ex) { 206 | throw new RuntimeException("Exception performing inference.", ex); 207 | } 208 | query.close(); 209 | } 210 | 211 | } 212 | -------------------------------------------------------------------------------- /core-api-use-cases/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | com.cyc 8 | cyc-core-api-use-cases 9 | 1.1.1 10 | jar 11 | 12 | Cyc Core API Use Cases 13 | 14 | Examples of common usage of the Cyc Core API Suite. 15 | 16 | 17 | 18 | http://dev.cyc.com/api/samples 19 | 20 | 21 | scm:git:git@github.com:cycorp/example-code.git 22 | scm:git:git@github.com:cycorp/example-code.git 23 | https://github.com/cycorp/example-code 24 | 25 | 26 | 27 | http://dev.cyc.com/issues/ 28 | GitHub Issues 29 | 30 | 31 | 2013 32 | 33 | 34 | 35 | The Apache License, Version 2.0 36 | http://www.apache.org/licenses/LICENSE-2.0.txt 37 | 38 | 39 | 40 | 41 | Cycorp, Inc. 42 | http://www.cyc.com 43 | 44 | 45 | 46 | 47 | Cycorp API Team 48 | dev-team@cyc.com 49 | Cycorp, Inc. 50 | http://www.cyc.com 51 | 52 | 53 | 54 | 55 | 56 | 57 | UTF-8 58 | 1.8 59 | 1.8 60 | ${project.basedir}/lib 61 | 62 | 63 | 68 | 69 | 70 | 71 | 72 | standard 73 | 74 | true 75 | 76 | 77 | 78 | 79 | com.cyc 80 | cyc-core-api 81 | 1.1.1 82 | 83 | 84 | 85 | com.cyc 86 | cyc-core-client-impl 87 | 1.1.1 88 | 89 | 90 | 96 | org.slf4j 97 | slf4j-api 98 | 1.7.12 99 | 100 | 101 | org.slf4j 102 | slf4j-simple 103 | 1.7.12 104 | 105 | 106 | 107 | net.htmlparser.jericho 108 | jericho-html 109 | 3.3 110 | 111 | 112 | 113 | 114 | 115 | standalone 116 | 117 | false 118 | 119 | 120 | 121 | com.cyc 122 | cyc-core-api 123 | 1.1.1 124 | system 125 | ${lib.directory}/cyc-core-api-1.1.1.jar 126 | 127 | 128 | com.cyc 129 | cyc-core-client-impl 130 | 1.1.1 131 | standalone 132 | system 133 | ${lib.directory}/cyc-core-client-impl-1.1.1-standalone.jar 134 | 135 | 136 | org.slf4j 137 | slf4j-api 138 | 1.7.12 139 | system 140 | ${lib.directory}/slf4j-api-1.7.12.jar 141 | 142 | 143 | org.slf4j 144 | slf4j-simple 145 | 1.7.12 146 | system 147 | ${lib.directory}/slf4j-simple-1.7.12.jar 148 | 149 | 150 | net.htmlparser.jericho 151 | jericho-html 152 | 3.3 153 | system 154 | ${lib.directory}/jericho-html-3.3.jar 155 | 156 | 157 | org.atteo.classindex 158 | classindex 159 | classindex.version 160 | system 161 | ${lib.directory}/classindex-3.4.jar 162 | 163 | 164 | org.apache.commons 165 | commons-lang3 166 | 3.4 167 | system 168 | ${lib.directory}/commons-lang3-3.4.jar 169 | 170 | 171 | com.google.guava 172 | guava 173 | 18.0 174 | system 175 | ${lib.directory}/guava-18.0.jar 176 | 177 | 178 | com.sun.xml.bind 179 | jaxb-impl 180 | 2.2.6 181 | system 182 | ${lib.directory}/jaxb-impl-2.2.6.jar 183 | 184 | 185 | xerces 186 | xercesImpl 187 | 2.10.0 188 | system 189 | ${lib.directory}/xercesImpl-2.10.0.jar 190 | 191 | 192 | xml-apis 193 | xml-apis 194 | 1.4.01 195 | system 196 | ${lib.directory}/xml-apis-1.4.01.jar 197 | 198 | 199 | 200 | 201 | 202 | 203 | 204 | 205 | 206 | 207 | 208 | org.apache.maven.plugins 209 | maven-compiler-plugin 210 | 3.1 211 | 212 | ${maven.compiler.source} 213 | ${maven.compiler.target} 214 | 215 | 216 | 217 | 218 | 219 | 220 | org.codehaus.mojo 221 | license-maven-plugin 222 | 1.7 223 | 224 | false 225 | false 226 | true 227 | ${basedir}/src/main/resources/headerTemplate.ftl 228 | 229 | 230 | 231 | first 232 | 233 | update-file-header 234 | 235 | process-sources 236 | 237 | apache_v2 238 | 239 | src/main/java 240 | src/test 241 | 242 | 243 | 244 | 245 | 246 | 247 | org.apache.maven.plugins 248 | maven-source-plugin 249 | 2.3 250 | 251 | 252 | bundle-sources 253 | package 254 | 255 | 256 | jar-no-fork 257 | 258 | 259 | 260 | 261 | 262 | 263 | 264 | 265 | -------------------------------------------------------------------------------- /core-api-use-cases/LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "{}" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright {yyyy} {name of copyright owner} 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | 204 | -------------------------------------------------------------------------------- /core-api-use-cases/src/main/java/com/cyc/core/examples/basics/BasicWalkthrough.java: -------------------------------------------------------------------------------- 1 | package com.cyc.core.examples.basics; 2 | 3 | import com.cyc.Cyc; 4 | import com.cyc.kb.BinaryPredicate; 5 | import com.cyc.kb.Context; 6 | import com.cyc.kb.Fact; 7 | import com.cyc.kb.KbCollection; 8 | import com.cyc.kb.KbIndividual; 9 | import com.cyc.kb.KbPredicate; 10 | import com.cyc.kb.KbTerm; 11 | import com.cyc.kb.Sentence; 12 | import com.cyc.kb.Variable; 13 | import com.cyc.kb.exception.CreateException; 14 | import com.cyc.kb.exception.DeleteException; 15 | import com.cyc.kb.exception.KbException; 16 | import com.cyc.kb.exception.KbObjectNotFoundException; 17 | import com.cyc.kb.exception.KbTypeException; 18 | import com.cyc.query.InferenceStatus; 19 | import com.cyc.query.InferenceSuspendReason; 20 | import com.cyc.query.Query; 21 | import com.cyc.query.QueryAnswer; 22 | import com.cyc.query.QueryListener; 23 | import com.cyc.query.QueryResultSet; 24 | import com.cyc.query.exception.QueryConstructionException; 25 | import com.cyc.query.exception.QueryException; 26 | import com.cyc.session.CycServerInfo; 27 | import com.cyc.session.CycSession; 28 | import com.cyc.session.SessionManager; 29 | import com.cyc.session.SessionOptions; 30 | import com.cyc.session.exception.SessionCommandException; 31 | import com.cyc.session.exception.SessionCommunicationException; 32 | import com.cyc.session.exception.SessionConfigurationException; 33 | import com.cyc.session.exception.SessionException; 34 | import com.cyc.session.exception.SessionInitializationException; 35 | import java.io.IOException; 36 | import java.util.Collection; 37 | import java.util.List; 38 | import org.slf4j.Logger; 39 | import org.slf4j.LoggerFactory; 40 | 41 | /* 42 | * #%L 43 | * File: BasicWalkthrough.java 44 | * Project: Cyc Core API Use Cases 45 | * %% 46 | * Copyright (C) 1995 - 2014 Cycorp, Inc 47 | * %% 48 | * Licensed under the Apache License, Version 2.0 (the "License"); 49 | * you may not use this file except in compliance with the License. 50 | * You may obtain a copy of the License at 51 | * 52 | * http://www.apache.org/licenses/LICENSE-2.0 53 | * 54 | * Unless required by applicable law or agreed to in writing, software 55 | * distributed under the License is distributed on an "AS IS" BASIS, 56 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 57 | * See the License for the specific language governing permissions and 58 | * limitations under the License. 59 | * #L% 60 | */ 61 | 62 | 63 | /** 64 | * This class provides a simple example of working with the Cyc KB through the Cyc Core API. It 65 | * includes new term creation, term retrieval, asserting and deleting facts about terms, and 66 | * querying the Cyc KB. 67 | *

68 | * The purpose of this class is to illustrate the basics of the Cyc Core API, so it is structured to 69 | * be read in linear order, from top to bottom, with methods that build upon the examples in 70 | * previous methods. Thus, while this file demonstrates best practices for Core API usage, it does 71 | * not represent the ideal structure for an actual application class. 72 | *

73 | * All of the example code in this class should work with all Cyc server releases supported by 74 | * the Cyc Core API. 75 | * 76 | * @note There are multiple ways of interacting with Cyc (through and independent of the Core API). 77 | * The illustrations here are some of the more popular techniques. 78 | */ 79 | public class BasicWalkthrough { 80 | 81 | // Cyc APIs log through the SLF4J API: 82 | 83 | private static final Logger LOGGER = LoggerFactory.getLogger(BasicWalkthrough.class); 84 | 85 | 86 | // Fields 87 | 88 | private Context peopleDataMt; 89 | private Context massMediaDataMt; 90 | private KbCollection actorInMovies; 91 | private KbCollection restrictedRating; 92 | private KbIndividual nicholson; 93 | private KbIndividual kingOfMarvinGardens; 94 | private BinaryPredicate movieActors; 95 | private BinaryPredicate movieActorsWithStarringRole; 96 | private BinaryPredicate movieAdvisoryRating; 97 | 98 | 99 | // Main 100 | 101 | public static void main(String[] args) { 102 | /* 103 | Wrapping the current SessionManager instance in a try-with-resources statement in the main 104 | method ensures that ALL CycSessions created by the SessionManager are closed, along with all of 105 | their Cyc server connections, before the program ends: 106 | */ 107 | try (SessionManager sessionMgr = SessionManager.getInstance()) { 108 | System.out.println("Running walkthrough..."); 109 | BasicWalkthrough usage = new BasicWalkthrough(); 110 | usage.runExample(); 111 | System.out.println(); 112 | } catch (KbException | QueryException | SessionException | RuntimeException kbe) { 113 | kbe.printStackTrace(System.err); 114 | System.exit(1); 115 | } catch (IOException ioe) { 116 | System.err.println("Error closing SessionManager"); 117 | ioe.printStackTrace(System.err); 118 | System.exit(1); 119 | } finally { 120 | System.out.println("... Walkthrough concluded."); 121 | System.exit(0); 122 | } 123 | } 124 | 125 | 126 | // Example code 127 | 128 | /** 129 | * Calls the actual example methods in linear order. 130 | *

131 | * Note that we call all of the example methods within a try-with-resources block, to ensure that 132 | * the CycSession for the current thread is closed before the thread is terminated. This may seem 133 | * a little redundant, as this is a single-threaded application and we're already closing the 134 | * SessionManager in the main() method (thereby closing ALL CycSessions). Although this isn't 135 | * strictly necessary for simple applications like this one, it is good practice for multi- 136 | * threaded applications (e.g., servlets), so we're demonstrating it here. 137 | *

138 | * Typically, we don't need to directly request the current CycSession; if one does not exist, it 139 | * will be automatically created the first time that the Cyc APIs require it. However, wrapping it 140 | * in a try-with-resources statement ensures that the session will be cleaned up at the end of the 141 | * current execution thread. 142 | * 143 | * @throws KbException 144 | * @throws QueryConstructionException 145 | * @throws SessionException 146 | */ 147 | public void runExample() throws KbException, QueryConstructionException, SessionException { 148 | try (CycSession session = CycSession.getCurrent()) { 149 | 150 | configureCurrentSession(); 151 | 152 | setupContexts(); 153 | 154 | basicTermLookup(); 155 | 156 | setupMarvinGardens(); 157 | 158 | setupActorBackgroundKnowledge(); 159 | 160 | setupJackNicholson(); 161 | 162 | createQueryViaSentence(); 163 | 164 | createQueryViaString(); 165 | 166 | runQueryAsynchronously(); 167 | 168 | } 169 | } 170 | 171 | /** 172 | * Configure the current CycSession. There is no need to programmatically specify a Cyc server; 173 | * when one is required, the CycSessionManager will check the System properties to determine how 174 | * to get access to Cyc. By default, in a graphical environment, it will fall back on 175 | * interactively prompting the user for connection information. 176 | * 177 | * @throws SessionConfigurationException 178 | * @throws SessionCommunicationException 179 | * @throws SessionInitializationException 180 | * @throws SessionCommandException 181 | * @throws KbTypeException 182 | * @throws CreateException 183 | */ 184 | protected void configureCurrentSession() 185 | throws SessionConfigurationException, SessionCommunicationException, 186 | SessionInitializationException, SessionCommandException, KbTypeException, 187 | CreateException { 188 | System.out.println(); 189 | 190 | /* 191 | Retrieve the current CycSession, creating one if necessary. In this case a CycSession should 192 | already exist, because we already called CycSessionManager#getCurrentSession() in the 193 | runExample() method. Calling it again here should return the same instance of CycSession. 194 | */ 195 | CycSession session = CycSession.getCurrent(); 196 | 197 | /* 198 | Let's get some information about the Cyc server being used for this session: 199 | */ 200 | CycServerInfo serverInfo = session.getServerInfo(); 201 | System.out.println("Current Cyc server: " + serverInfo.getCycAddress()); 202 | System.out.println("Cyc server release type: " + serverInfo.getSystemReleaseType()); 203 | System.out.println("Cyc server revision number:" + serverInfo.getCycRevisionString()); 204 | 205 | /* 206 | Now let's set some options for the current session. Here we are defining them programmatically, 207 | but future versions of the Session API will allow them to be defined by configuration 208 | properties... 209 | */ 210 | SessionOptions options = session.getOptions(); 211 | 212 | /* 213 | Transcript the Cyc operations issued by the API. These operations can be saved into an ASCII 214 | text file and reloaded on a clean image to recreate a given state of the KB with such 215 | operations. 216 | */ 217 | options.setShouldTranscriptOperations(true); 218 | 219 | /* 220 | Set "CycAdministrator" as the current Cyclist. Setting the cyclist is required for bookkeeping 221 | information to be added for assertions and constants. 222 | */ 223 | options.setCyclistName("CycAdministrator"); 224 | } 225 | 226 | /** 227 | * Choose the Contexts we'll be using. "Contexts" are the objects which the KB API uses to 228 | * represent CycL microtheories. We'll be referring to them often, so we'll assign them to 229 | * instance fields. 230 | * 231 | *

It's very important to ensure that the knowledge used by your application goes into the 232 | * appropriate microtheory; this can have an enormous impact upon the correctness and efficiency 233 | * of inference. 234 | * 235 | * @throws KbTypeException 236 | * @throws CreateException 237 | * @throws SessionConfigurationException 238 | * @throws SessionCommunicationException 239 | * @throws SessionInitializationException 240 | */ 241 | protected void setupContexts() 242 | throws KbTypeException, CreateException, SessionConfigurationException, 243 | SessionCommunicationException, SessionInitializationException { 244 | /* 245 | KbObjects are requested from factories, and there is KB factory for each KbObject type. 246 | Here, we retrieve Context objects. 247 | */ 248 | peopleDataMt = Context.get("PeopleDataMt"); 249 | massMediaDataMt = Context.get("MassMediaDataMt"); 250 | 251 | /* 252 | Instead of manually specifying a Context for every query or assertion, many methods will check 253 | for default assertion and query Contexts if no Context argument is directly provided. 254 | */ 255 | CycSession.getCurrent().getOptions().setDefaultContext( 256 | Context.getDefaultContext(massMediaDataMt, Cyc.Constants.INFERENCE_PSC)); 257 | } 258 | 259 | /** 260 | * Perform some simple term lookup and creation. Most of the methods in the KB API and the Query 261 | * API will accept both Strings and KB objects for their arguments. But it's good practice to 262 | * create the KB object versions, and use them. In this file, we'll alternate back and forth 263 | * between using KB object and using Strings for these arguments. Here's how you retrieve the KB 264 | * objects. 265 | * 266 | * @throws KbTypeException 267 | * @throws CreateException 268 | * @throws DeleteException 269 | */ 270 | protected void basicTermLookup() 271 | throws KbTypeException, CreateException, DeleteException { 272 | System.out.println(); 273 | 274 | /* 275 | KbObjects are requested from factories, and there is KB factory for each KbObject type. 276 | Here, we find or create an Individual term in the KB to represent the actor Jack Nicholson. 277 | */ 278 | KbIndividual nicholsonIndividual = KbIndividual.findOrCreate("JackNicholson"); 279 | System.out.println("Jack Nicholson as an individual: " 280 | + nicholsonIndividual); 281 | 282 | /* 283 | And here, we request JackNicholson as a KbTerm, which is a super-type of KbIndividual. Note 284 | that we're now using the get method, which should only be used if you're sure the term is in 285 | the KB. This code shows how to test whether a term is in the KB (in a form that can be cast to 286 | the desired type) before actually retrieving it. In most real-world cases, you won't run this 287 | test before every call to get. 288 | */ 289 | KbTerm nicholsonTerm = null; 290 | if (KbTerm.existsAsType("JackNicholson")) { 291 | nicholsonTerm = KbTerm.get("JackNicholson"); 292 | } 293 | System.out.println("Jack Nicholson as a term: " + nicholsonTerm); 294 | 295 | /* 296 | We can also confirm that Jack Nicholson isn't, say, a KbCollection. 297 | */ 298 | System.out.println("Is Jack Nicholson a collection? " 299 | + KbCollection.existsAsType("JackNicholson")); 300 | 301 | /* 302 | The KbObject factories are intelligent enough to return an instance of the most specific type. 303 | Because JackNicholson is an Individual, and because KbIndividual is a subclass of KbTerm, 304 | either factory will return an instance of KbIndividual. And, because of caching, they will 305 | return the *same* instance of KbIndividual: 306 | */ 307 | System.out.println("Are the KbTerm and KbIndividual for #$JackNicholson the exact same object? " 308 | + (nicholsonIndividual == nicholsonTerm)); 309 | 310 | /* 311 | Now, let's check whether the movie _King of Marvin Gardens_ exists in Cyc's KB. Here is some 312 | slightly different syntax for checking whether it can be expressed as a KbIndividual: 313 | */ 314 | System.out.println("Does Cyc already know that _King of Marvin Gardens_ is an individual? " 315 | + KbIndividual.existsAsType("TheKingOfMarvinGardens-TheMovie")); 316 | 317 | /* 318 | And here's a way to check whether the term exists at all: 319 | */ 320 | System.out.println("Does _King of Marvin Gardens_ exist in Cyc's KB at all? " 321 | + Cyc.existsInKb("TheKingOfMarvinGardens-TheMovie")); 322 | 323 | /* 324 | For sake of the example, let's ensure that _King of Marvin Gardens_ does NOT exist in Cyc's KB. 325 | Of course, it needs to exist in order for us to delete it, and we could check 326 | KbFactory#existsInKb() (like we just did above) to determine whether it exists. But for sake of 327 | the example let's assume that it's in the KB, and add some code for handling the case where it 328 | isn't: 329 | */ 330 | try { 331 | KbTerm.get("TheKingOfMarvinGardens-TheMovie").delete(); 332 | System.out.println("TheKingOfMarvinGardens-TheMovie: deleted!"); 333 | } catch (KbObjectNotFoundException e) { 334 | System.out.println("Apparently TheKingOfMarvinGardens-TheMovie wasn't in the KB," 335 | + " but we'll just carry on: " + " (" + e.getMessage() + ")"); 336 | } 337 | } 338 | 339 | /** 340 | * Ensure that _King Of Marvin Gardens_ exists in Cyc's KB, and has enough supporting knowledge to 341 | * be useful. This is known as "term elaboration". 342 | * 343 | * @throws CreateException 344 | * @throws KbTypeException 345 | */ 346 | protected void setupMarvinGardens() 347 | throws CreateException, KbTypeException { 348 | System.out.println(); 349 | 350 | /* 351 | Find or create an individual term in the KB to represent the movie _King of Marvin Gardens_, 352 | and simultaneously make it an instance of the DramaticMovies collection in the MassMediaDataMt 353 | Context. Note that we could also have passed the String DramaticMovie and the context 354 | MassMediaDataMt as parameters to the findOrCreate method. Also note that we assumed the 355 | collection DramaticMovie exists in the KB. If DramaticMovie were not in the KB, this code would 356 | throw an exception, and we would have to create it. 357 | */ 358 | KbCollection dramaticMovie = KbCollection.get("DramaticMovie"); 359 | kingOfMarvinGardens = KbIndividual 360 | .findOrCreate("TheKingOfMarvinGardens-TheMovie", dramaticMovie, massMediaDataMt); 361 | System.out.println("We've created _King of Marvin Gardens_: " + kingOfMarvinGardens); 362 | 363 | /* 364 | Now, let's add the fact that the movie "The King of Marvin Gardens" has a restricted rating. 365 | */ 366 | restrictedRating = KbCollection.get("RestrictedRating"); 367 | movieAdvisoryRating = BinaryPredicate.get("movieAdvisoryRating"); 368 | Fact kingOfMarvinGardensRestrictedRating = Fact.findOrCreate( 369 | Sentence.get(movieAdvisoryRating, kingOfMarvinGardens, restrictedRating), 370 | massMediaDataMt); 371 | System.out.println("_King of Marvin Gardens_ is R-rated: " 372 | + kingOfMarvinGardensRestrictedRating); 373 | } 374 | 375 | /** 376 | * Add general background knowledge about actors. Later, this will be leveraged to associated Jack 377 | * Nicholson with the movie _King of Marvin Gardens_. 378 | * 379 | * @throws CreateException 380 | * @throws KbTypeException 381 | */ 382 | protected void setupActorBackgroundKnowledge() 383 | throws CreateException, KbTypeException { 384 | System.out.println(); 385 | 386 | /* 387 | Since we will be talking about Jack Nicholson, we have to make sure Cyc knows about actors. 388 | Most Cyc releases will already have this term, but just in case, here's how you go about 389 | creating it. Don't worry if it's already in your Cyc KB. These operations are idempotent, so 390 | running them in a Cyc that already has the terms won't do anything bad. When in doubt, the 391 | following idiom is most useful. 392 | */ 393 | actorInMovies = KbCollection.findOrCreate("ActorInMovies"); 394 | 395 | /* 396 | Let's also convey the fact that all movie actors are people. (Our apologies to the highly 397 | trained animals who have sometimes carried movies on their shoulders). We assume the collection 398 | Person already exists and we only have to specify the name to retrieve it. 399 | */ 400 | actorInMovies.addGeneralization(KbCollection.get("Person")); 401 | 402 | /* 403 | We need a way to relate actors to the movies they are in. Let's call the relation 404 | "movieActors". This particular predicate already exists in Cyc, but if it didn't, this is how 405 | you would create it. 406 | */ 407 | movieActors = BinaryPredicate.findOrCreate("movieActors"); 408 | System.out.println("Binary predicate associating actors with movies: " + movieActors); 409 | 410 | /* 411 | It is always a good idea to put constraints on the arguments of predicates for semantic 412 | validity. The following establishes in the KB (in the MassMediaDataMt context) that the first 413 | argument of movieActors must be an instance of the collection Movie-CW and the second argument 414 | must be an instance of the collection ActorInMovies. (Note that #$DramaticMovie is a spec of 415 | #$Movie-CW, so #$TheKingOfMarvinGardens-TheMovie will be a valid argument for arg1.) 416 | */ 417 | System.out.println("Asserting constraints on #$movieActors," 418 | + " these might take a little while to propagate..."); 419 | movieActors.addArgIsa(1, KbCollection.get("Movie-CW"), Context.get("MassMediaDataMt")); 420 | movieActors.addArgIsa(2, KbCollection.get("ActorInMovies"), Context.get("MassMediaDataMt")); 421 | 422 | /* 423 | Of course, some movie actors have a starring role. To add this more specific knowledge to the 424 | KB, we need a more specific predicate; let's call it "movieActors-WithStarringRole". Again, 425 | this predicate already exists in most Cyc KBs, so the following will typically retrieve, rather 426 | than create, the predicate in most Cyc KBs. 427 | */ 428 | System.out.println("Asserting constraints on #$movieActors-WithStarringRole," 429 | + " these might take a little while to propagate..."); 430 | movieActorsWithStarringRole = BinaryPredicate.findOrCreate("movieActors-WithStarringRole"); 431 | movieActorsWithStarringRole.addArgIsa(1, KbCollection.get("Movie-CW"), Context.get("MassMediaDataMt")); 432 | movieActorsWithStarringRole.addArgIsa(2, KbCollection.get("ActorInMovies"), Context.get("MassMediaDataMt")); 433 | 434 | /* 435 | Finally, let's establish that movieActors is a generalization of 436 | movieActorsWithStarringRole 437 | */ 438 | movieActorsWithStarringRole.addGeneralization(KbPredicate.get("movieActors"), Context.get("UniversalVocabularyMt")); 439 | 440 | /* 441 | Now, let's view all of the specializations on #$movieActors. 442 | */ 443 | System.out.println("Specializations of #$movieActors:"); 444 | movieActors.getSpecializations() 445 | .forEach(spec -> System.out.println(" - " + spec)); 446 | } 447 | 448 | /** 449 | * Elaborate on Jack Nicholson's role as an actor, and his relation to the movie 450 | * _King Of Marvin Gardens_... 451 | * 452 | * @throws CreateException 453 | * @throws KbTypeException 454 | * @throws DeleteException 455 | * @throws SessionConfigurationException 456 | * @throws SessionCommunicationException 457 | * @throws SessionInitializationException 458 | */ 459 | protected void setupJackNicholson() 460 | throws CreateException, KbTypeException, DeleteException, SessionConfigurationException, 461 | SessionCommunicationException, SessionInitializationException { 462 | System.out.println(); 463 | 464 | /* 465 | We ensured earlier that #$JackNicholson was in the KB. We'll be referring to him a few times 466 | more, though, so let's assign him to an instance field. 467 | */ 468 | nicholson = KbIndividual.get("JackNicholson"); 469 | 470 | /* 471 | Let's convey the fact Jack Nicholson is an instance of the ActorInMovies collection in the 472 | PeopleDataMt Context. 473 | */ 474 | nicholson.instantiates(actorInMovies, peopleDataMt); 475 | 476 | /* 477 | We can easily see what JackNicholson is known to be an instance of from the PeopleDataMt context. 478 | */ 479 | Collection nicholsonTypes = nicholson.instanceOf(Context.get("PeopleDataMt")); 480 | System.out.println("Things that #$JackNicholson is known to be:"); 481 | nicholsonTypes 482 | .forEach(nicholsonType -> System.out.println(" - " + nicholsonType)); 483 | 484 | /* 485 | Since JackNicholson is an instance of ActorInMovies (which is a specialization of Person) we 486 | should be able to prove that JackNicholson is a person without ever having asserted it. 487 | */ 488 | assert (nicholsonTypes.contains(KbCollection.get("Person"))) : 489 | "Jack Nicholson may be an ActorInMovies but he is not a Person"; 490 | 491 | /* 492 | Similarly, Cyc knows that he is a human. 493 | */ 494 | System.out.println("Does Cyc know that #$JackNicholson is a human? " 495 | + nicholson.isInstanceOf(KbCollection.get("HomoSapiens"))); 496 | 497 | /* 498 | Now, assert the fact, in the MassMediaMt context, that JackNicholson was one of the actors in 499 | KingOfMarvinGardens. 500 | */ 501 | Fact nicholsonActedInMarvinGardens = Fact.findOrCreate( 502 | Sentence.get(movieActors, kingOfMarvinGardens, nicholson), massMediaDataMt); 503 | 504 | /* 505 | But wait! Jack Nicholson actually had a starring role in TheKingOfMarvinGardens-TheMovie, so 506 | let's add that more specific assertion. This method shows how to do it with a String containing 507 | a CycL sentence. 508 | */ 509 | Fact nicholsonStarredInMarvinGardens = Fact.findOrCreate( 510 | "(movieActors-WithStarringRole TheKingOfMarvinGardens-TheMovie JackNicholson)", 511 | "MassMediaDataMt"); 512 | System.out.println("Jack Nicholson starred in _King of Marvin Gardens_: " 513 | + nicholsonStarredInMarvinGardens); 514 | 515 | /* 516 | Now that we know he was a star, it's redundant to say that he acted in the 517 | movie, so we can (but are not required to) delete the first fact, and we'll 518 | still know that he acted in the movie. 519 | */ 520 | nicholsonActedInMarvinGardens.delete(); 521 | } 522 | 523 | /** 524 | * Construct a query from a Sentence of KbObjects (which could include other Sentences) and run 525 | * it. 526 | * 527 | *

Here we will retrieve the results as a List of QueryAnswers, with each QueryAnswer 528 | * containing a map of query variables and their bindings. 529 | * 530 | * @throws KbTypeException 531 | * @throws CreateException 532 | * @throws QueryConstructionException 533 | * @throws SessionCommunicationException 534 | * @throws KbException 535 | */ 536 | public void createQueryViaSentence() 537 | throws KbTypeException, CreateException, QueryConstructionException, 538 | SessionCommunicationException, KbException { 539 | System.out.println(); 540 | 541 | Variable movieVar = Variable.get("?MOVIE"); 542 | Sentence querySentence = Sentence.and( 543 | Sentence.get(movieActors, movieVar, nicholson), 544 | Sentence.get(movieAdvisoryRating, movieVar, restrictedRating)); 545 | System.out.println("Query sentence: " + querySentence); 546 | 547 | /* 548 | Now we can construct a query for this sentence. We will use InferencePSC, the all-encompassing 549 | context, as the context in which to execute the query. Note here we retrieve a handle to 550 | InferencePSC from the ContextFactory class, but we could also have retrieved it using 551 | Context.get("InferencePSC"). 552 | 553 | Note that we are wrapping the Query in a try-with-resources statement; this ensures that it 554 | will be cleaned up when we are done with it, without having to manually call Query#close(). 555 | */ 556 | try (Query query = Query.get(querySentence, Cyc.Constants.INFERENCE_PSC)) { 557 | 558 | /* 559 | Let's set a few parameters for efficiency using our knowledge of answer expectations. In 560 | particular we will set a cap on the number of results retrieved and the amount of time spent 561 | in retrieval and we will make the results accessible through the Cyc browser. Note that these 562 | setters return the Query object, so they are chainable. 563 | */ 564 | query.setMaxAnswerCount(10) 565 | .setMaxTime(2) 566 | .getInferenceParameters().setBrowsable(true); 567 | 568 | /* 569 | Calling Query#getAnswers() will force an inference to run, if this has not already happened. 570 | */ 571 | System.out.println("Retrieving query answers as a List of binding-sets..."); 572 | List answers = query.getAnswers(); 573 | 574 | System.out.println("Status: " + query.getStatus()); 575 | System.out.println("Is inference suspended? " 576 | + InferenceStatus.SUSPENDED.equals(query.getStatus())); 577 | System.out.println("Number of results: " + answers.size()); 578 | 579 | answers.forEach(answer -> { 580 | /* 581 | If we know the type of the binding, we can use that as a generic. 582 | */ 583 | KbIndividual binding = answer.getBinding(movieVar); 584 | System.out.println(" - " + binding); 585 | }); 586 | } finally { 587 | /* 588 | We've wrapped the Query in a try-with-resources statement, so it will be automatically closed 589 | at the end of the try block. 590 | 591 | Closing the query performs clean up operations. Not closing queries leaves objects in the Cyc 592 | server, and can cause memory leaks. The finalize method on the query closes it, thereby 593 | releasing resources on the Cyc server, but it is performed at the mercy of the garbage 594 | collector. To ensure that the resources are released promptly on the server, the query 595 | should generally be closed as soon as you are done with it and its directly related objects 596 | (such as any QueryResultSets). 597 | 598 | This is especially important when a query has been run as "browsable" (which this query was), 599 | as the Cyc server will hold onto resources for that query even after the calling application 600 | has terminated. 601 | */ 602 | System.out.println("Done with query!"); 603 | } 604 | } 605 | 606 | /** 607 | * Construct a query from a String containing a CycL sentence and run it. Although it's generally 608 | * preferable to construct Queries via a Sentence of KbObjects (less error-prone), there are 609 | * certainly times when you may want to read raw Strings (user input, prototyping, etc.) 610 | * 611 | *

Here we will retrieve the query answers as a synchronous QueryResultSet, which is very 612 | * similar to a JDBC ResultSet. 613 | * 614 | * @throws KbTypeException 615 | * @throws CreateException 616 | * @throws QueryConstructionException 617 | * @throws KbException 618 | */ 619 | public void createQueryViaString() 620 | throws KbTypeException, CreateException, QueryConstructionException, KbException { 621 | System.out.println(); 622 | 623 | /* 624 | Note that the #$ prefix for constant names is not required, and that the 625 | toString method on KBObjects yields a string that can be used in this kind 626 | of method. 627 | */ 628 | try (Query query = Query.get( 629 | "(and (movieActors ?MOVIE " + nicholson + ")" + 630 | " (movieAdvisoryRating ?MOVIE RestrictedRating))", 631 | "InferencePSC")) { 632 | query.getInferenceParameters() 633 | .setMaxAnswerCount(10) 634 | .setMaxTime(2) 635 | .setBrowsable(true); 636 | 637 | /* 638 | Calling Query#getResultSet() will force an inference to run, if this has not already 639 | happened. 640 | */ 641 | System.out.println("Retrieving query answers as a synchronous QueryResultSet..."); 642 | QueryResultSet results = query.getResultSet(); 643 | 644 | System.out.println("Status: " + query.getStatus()); 645 | System.out.println("Is inference suspended? " 646 | + InferenceStatus.SUSPENDED.equals(query.getStatus())); 647 | System.out.println("Number of results: " + results.getCurrentRowCount()); 648 | while (results.next()) { 649 | KbIndividual binding = results.getKbObject("?MOVIE", KbIndividual.class); 650 | System.out.println(" - " + binding); 651 | } 652 | } finally { 653 | System.out.println("Done with query!"); 654 | } 655 | } 656 | 657 | /** 658 | * Run a query asynchronously and receive answers via listeners. 659 | * 660 | * @throws KbTypeException 661 | * @throws CreateException 662 | * @throws QueryConstructionException 663 | */ 664 | public void runQueryAsynchronously() 665 | throws KbTypeException, CreateException, QueryConstructionException { 666 | System.out.println(); 667 | 668 | final Variable movieVar = Variable.get("?MOVIE"); 669 | Sentence querySentence = Sentence.and( 670 | Sentence.get(movieActors, movieVar, nicholson), 671 | Sentence.get(movieAdvisoryRating, movieVar, restrictedRating)); 672 | Query query = null; 673 | 674 | /* 675 | Note that we are not wrapping this query in a try-with-resource statement. We'll explain that 676 | below. 677 | */ 678 | try { 679 | query = Query.get(querySentence, Cyc.Constants.INFERENCE_PSC); 680 | query.getInferenceParameters() 681 | .setMaxAnswerCount(10) 682 | .setMaxTime(2) 683 | .setBrowsable(true); 684 | query.addListener(new QueryListener() { 685 | @Override 686 | public void notifyInferenceCreated(Query query) { 687 | System.out.println("... Created inference for " + query); 688 | } 689 | @Override 690 | public void notifyInferenceStatusChanged(InferenceStatus oldStatus, 691 | InferenceStatus newStatus, 692 | InferenceSuspendReason suspendReason, 693 | Query query) { 694 | System.out.println("... Inference status changed from " + oldStatus + " to " + newStatus); 695 | } 696 | @Override 697 | public void notifyInferenceAnswersAvailable(Query query, List newAnswers) { 698 | newAnswers.forEach(answer 699 | -> System.out.println("New answer: " + answer.getBinding(movieVar))); 700 | } 701 | @Override 702 | public void notifyInferenceTerminated(Query query, Exception exception) { 703 | if (exception == null) { 704 | System.out.println("... Inference terminated!"); 705 | } else { 706 | System.err.println("... Inference terminated with exception!"); 707 | exception.printStackTrace(System.err); 708 | } 709 | } 710 | }); 711 | System.out.println("Retrieving query answers asynchronously via listeners..."); 712 | query.performInference(); 713 | 714 | /* 715 | Wait a couple of seconds for the purpose of this example. This is an asynchronous query, so 716 | we want to give it a chance to return results. 717 | */ 718 | try { 719 | Thread.sleep(2000); 720 | } catch (InterruptedException ex) { 721 | Thread.currentThread().interrupt(); 722 | } 723 | } finally { 724 | /* 725 | We're closing this query manually to illustrate a point: because this query is asynchronous, 726 | we need to be a little more careful about when (and how) we close it. For example, in a web 727 | service, a client might repeatedly poll the server to pick up new results; the server would 728 | need to be at least mildly intelligent about when to close the query. 729 | */ 730 | if (query != null) { 731 | System.out.println("Closing query..."); 732 | query.close(); 733 | } 734 | System.out.println("Done with asynchronous query!"); 735 | } 736 | } 737 | 738 | } 739 | --------------------------------------------------------------------------------