Show Cyc2RDB.java syntax highlighted
/*
* Cyc2RDB.java
*
* Created on October 16, 2006, 3:33 AM
*
* Description: Upon receipt of a start-processing message, this bean extracts all the assertions
* from of OpenCyc, one microtheory at a time, and persists them as objects in the relational
* database.
*
* Copyright (C) 2006 Stephen L. Reed.
*
* This program is free software; you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with this program;
* if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package org.texai.kb.ejb.mdb;
import java.io.IOException;
import java.io.Serializable;
import java.math.BigInteger;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
import javax.annotation.Resource;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.EJB;
import javax.ejb.EJBTransactionRolledbackException;
import javax.ejb.MessageDriven;
import javax.ejb.MessageDrivenContext;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.HeuristicMixedException;
import javax.transaction.HeuristicRollbackException;
import javax.transaction.RollbackException;
import javax.transaction.SystemException;
import javax.transaction.TransactionManager;
import javax.transaction.UserTransaction;
import org.apache.log4j.Logger;
import org.opencyc.api.CycAccess;
import org.opencyc.api.CycApiException;
import org.opencyc.api.CycObjectFactory;
import org.opencyc.cycobject.CycAssertion;
import org.opencyc.cycobject.CycConstant;
import org.opencyc.cycobject.CycList;
import org.opencyc.cycobject.CycNart;
import org.opencyc.cycobject.CycObject;
import org.opencyc.cycobject.CycSymbol;
import org.opencyc.cycobject.CycVariable;
import org.texai.kb.Constants;
import org.texai.kb.ejb.entity.AbstractReifiedTerm;
import org.texai.kb.ejb.entity.AbstractTerm;
import org.texai.kb.ejb.entity.AtomicTerm;
import org.texai.kb.ejb.entity.Formula;
import org.texai.kb.ejb.entity.NonAtomicTerm;
import org.texai.kb.ejb.entity.PDouble;
import org.texai.kb.ejb.entity.PLong;
import org.texai.kb.ejb.entity.PString;
import org.texai.kb.ejb.entity.PVariable;
import org.texai.kb.ejb.entity.Rule;
import org.texai.kb.ejb.entity.Symbol;
import org.texai.kb.ejb.entity.TimePoint;
import org.texai.kb.ejb.session.shared.TermFinderFacadeLocal;
import org.texai.util.TexaiException;
/**
* Message Driven Bean class Cyc2RDB
*
* @author reed
*/
@SuppressWarnings(value={"unchecked"})
@TransactionManagement(TransactionManagementType.BEAN)
@MessageDriven(mappedName = "jms/Cyc2RDB", activationConfig = {
@ActivationConfigProperty(propertyName = "acknowledgeMode", propertyValue = "Auto-acknowledge"),
@ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue"),
@ActivationConfigProperty(propertyName = "destination", propertyValue = "queue/mdb")})
public class Cyc2RDB implements MessageListener, Serializable { // NOPMD
/**
* Determines if a de-serialized file is compatible with this class.
*
* Maintainers must change this value if and only if the new version
* of this class is not compatible with old versions. See Sun docs
* for <a href=http://java.sun.com/products/jdk/1.1/docs/guide
* /serialization/spec/version.doc.html> details. </a>
*
* Not necessary to include in first version of the class, but
* included here as a reminder of its importance.
*/
private transient static final long serialVersionUID = 1L;
/** the indicator that the cachedAssertionFormula is uninitialized */
private static final CycList UNINITIALIZED_ASSERTION_FORMULA = new CycList(0);
/** the indicator that the process should shut down */
private transient static boolean isShutdown = false;
/** the message driven context injected by the container */
@Resource
private MessageDrivenContext messageDrivenContext; // NOPMD
/** the transaction injected by the container */
@Resource
private UserTransaction userTransaction; // NOPMD
/** the entity manager instance injected by the container */
@PersistenceContext(unitName=Constants.PERSISTENCE_UNIT_NAME)
private EntityManager entityManager; // NOPMD
/** the term finder, which is injected by the container */
@EJB
private TermFinderFacadeLocal termFinderFacade; // NOPMD
/** the logger */
private transient Logger logger; // NOPMD
/** the Cyc server interface */
private transient CycAccess cycAccess;
/** the cached assertion formula */
private transient CycList cachedAssertionFormula = UNINITIALIZED_ASSERTION_FORMULA;
/** the cached assertion strength */
private transient Integer cachedAssertionStrength = Constants.UNINITIALIZED_ASSERTION_STRENGTH;
/** the restart assertion sequence number */
private transient int restartAssertionSequenceNbr;
/** the restart microtherory name */
private transient String restartMicrotheoryName;
/** the creator */
private transient AtomicTerm creator;
/** the creation purpose */
private transient AtomicTerm creationPurpose;
/** Creates a new instance of Cyc2RDB */
public Cyc2RDB() {
super();
}
/** Receives the asynchronously delivered message.
*
* @param message the message
*/
public void onMessage(final Message message) {
ObjectMessage objectMessage = null;
try {
final long jmsMillis = message.getJMSTimestamp();
if (System.currentTimeMillis() > jmsMillis + Constants.MESSAGE_EXPIRATION_MILLIS) {
getLogger().info("ignoring expired message");
return;
}
if (message instanceof ObjectMessage) {
objectMessage = (ObjectMessage) message;
assert objectMessage.getObject() instanceof Cyc2RDBMessage
: objectMessage.getObject().toString() + " must be a ProcessingMessage";
final Cyc2RDBMessage cyc2RDBMessage = (Cyc2RDBMessage) objectMessage.getObject();
getLogger().info("cyc2RDBMessage: " + cyc2RDBMessage);
if ("start".equals(cyc2RDBMessage.getCommand())) {
getLogger().info("starting Cyc2RDB, skipping termOfUnit assertions");
restartAssertionSequenceNbr = cyc2RDBMessage.getRestartAssertionSequenceNbr();
restartMicrotheoryName = cyc2RDBMessage.getRestartMicrotheoryName();
cycAccess = new CycAccess();
isShutdown = false;
creator = termFinderFacade.findOrCreateBootstrapAtomicTerm(
"SomeCyclist",
"some cyclist",
UUID.randomUUID().toString());
creationPurpose = termFinderFacade.findOrCreateBootstrapAtomicTerm(
"OpenCycProject",
"the OpenCyc Project",
UUID.randomUUID().toString());
setTransactionTimeout();
convertAssertions();
} else if ("stop".equals(cyc2RDBMessage.getCommand())) {
getLogger().info("stopping Cyc2RDB");
isShutdown = true;
}
}
} catch (final JMSException ex) {
getLogger().fatal(ex.getMessage(), ex);
messageDrivenContext.setRollbackOnly();
} catch (final IOException ex) {
getLogger().fatal(ex.getMessage(), ex);
messageDrivenContext.setRollbackOnly();
}
}
/** Sets the message driven context when performing a unit test of this class.
*
* @param messageDrivenContext the message driven context
*/
public void setMessageDrivenContext(final MessageDrivenContext messageDrivenContext) {
//Preconditions
assert messageDrivenContext != null : "messageDrivenContext must not be null";
this.messageDrivenContext = messageDrivenContext;
}
/** Sets the Cyc server interface.
*
* @param cycAccess the Cyc server interface
*/
public void setCycAccess(final CycAccess cycAccess) {
//Preconditions
assert cycAccess != null : "cycAccess must not be null";
this.cycAccess = cycAccess;
}
/** Sets the term finder during out-of-the-container unit testing.
*
* @param termFinderFacade the term finder
*/
public void setTermFinderFacade(final TermFinderFacadeLocal termFinderFacade) {
//Preconditions
assert termFinderFacade != null : "termFinderFacade must not be null";
this.termFinderFacade = termFinderFacade;
}
/** Sets the entity manager during out-of-the-container unit testing.
*
* @param entityManager the term entity manager
*/
public void setEntityManager(final EntityManager entityManager) {
//Preconditions
assert entityManager != null : "entityManager must not be null";
this.entityManager = entityManager;
}
/** Iterates through the Cyc microtheories, converting the contained assertions into database entries.
*
* @throws IOException in case of a communications problem
*/
public void convertAssertions() throws IOException { // NOPMD
// Preconditions
assert cycAccess != null : Constants.CYC_ACCESS_ERR;
assert restartMicrotheoryName != null : "restartMicrotheoryName must not be null";
setTransactionTimeout(Constants.TRANSACTION_TIMEOUT_SECONDS);
final CycList microtheories = cycAccess.getAllInstances(cycAccess.getKnownConstantByName("Microtheory"));
getLogger().info("converting " + microtheories.size() + " microtheories");
int nbrAssertionsConverted = 0;
final Iterator microtheoriesIter = microtheories.sort().iterator();
final CycList command = new CycList(2);
while (microtheoriesIter.hasNext()) {
if (isShutdown) {
getLogger().info("shutting down");
return;
}
final CycObject microtheory = (CycObject) microtheoriesIter.next();
final String microtheoryString = microtheory.toString();
if (microtheoryString.startsWith("(ContentMtOfCDAFromEventFn ")
|| "GAFGatheringLogMt".equals(microtheoryString)) {
getLogger().info("skipping " + microtheory.cyclify());
continue;
}
if (restartMicrotheoryName.length() > 0) {
if (microtheoryString.equals(restartMicrotheoryName)) {
restartMicrotheoryName = "";
} else {
getLogger().info("restart, skipping " + microtheory.cyclify());
continue;
}
}
getLogger().info(microtheory.cyclify());
final String script =
" (clet (assertion-infos assertion-strength assertion-strength-code) \n"
+ " (cdolist (assertion (gather-mt-index " + cycAccess.makeELMt(microtheory).stringApiValue() + ")) \n"
+ " (csetq assertion-strength (assertion-strength assertion)) \n"
+ " (pif (eq assertion-strength :DEFAULT) \n"
+ " (csetq assertion-strength-code 1) \n"
+ " (pif (eq assertion-strength :MONOTONIC) \n"
+ " (csetq assertion-strength-code 2) \n"
+ " (csetq assertion-strength-code 3))) \n"
+ " (cpush (list (assertion-id assertion) assertion-strength-code) assertion-infos)) \n"
+ " assertion-infos)";
//getLogger().info(script);
final CycList assertionInfos = cycAccess.converseList(script);
int assertionNbr = 0;
final Iterator assertionInfosIter = assertionInfos.iterator();
while (assertionInfosIter.hasNext()) {
if (isShutdown) {
getLogger().info("shutting down");
return;
}
final CycList assertionInfo = (CycList) assertionInfosIter.next();
final Integer assertionId = (Integer) assertionInfo.first();
cachedAssertionStrength = (Integer) assertionInfo.second();
command.clear();
command.add(CycObjectFactory.makeCycSymbol("find-assertion-by-id"));
command.add(assertionId);
final CycAssertion assertion = (CycAssertion) cycAccess.converseObject(command);
assert assertion.getMt().equals(microtheory)
: "assertion mt " + assertion.getMt().cyclify() + " must equal the assertion's containing microtheory " + microtheory.cyclify();
final CycList assertionFormula = assertionFormula(assertion);
if (assertionFormula.isEmpty()) {
getLogger().info("skipping assertion " + assertion.toString() + " with empty formula");
} else {
cachedAssertionFormula = assertionFormula;
if (!hasExcludedTerm(assertionFormula)) {
try {
nbrAssertionsConverted++;
if (nbrAssertionsConverted >= Constants.ASSERTION_PROCESSING_LIMIT) {
getLogger().info("processing limit exceeded, shutting down");
return;
}
assertionNbr++;
if (restartAssertionSequenceNbr == 0 || restartAssertionSequenceNbr <= nbrAssertionsConverted) {
getLogger().info("assertion (" + nbrAssertionsConverted + " of " + Constants.TOTAL_ASSERTIONS + "): "
+ assertionFormula.cyclify() + " restart " + assertionNbr + " in " + microtheoryString);
beginTransaction();
findOrCreateAssertion(assertion);
commitTransaction();
clearEntityManager();
} else {
getLogger().info("restart, skipping assertion (" + nbrAssertionsConverted + " of " + Constants.TOTAL_ASSERTIONS + "): "
+ assertionFormula.cyclify() + " restart " + assertionNbr + " in " + microtheoryString);
}
} catch (final IOException ex) {
getLogger().error("\n\n***************************************************");
getLogger().error("assertion: " + assertionFormula + "\n");
getLogger().fatal(ex.getMessage() + "\n", ex);
getLogger().error("***************************************************\n\n");
} catch (final CycApiException ex) {
getLogger().error("\n\n***************************************************");
getLogger().error("assertion: " + assertionFormula + "\n");
getLogger().fatal(ex.getMessage() + "\n", ex);
getLogger().error("***************************************************\n\n");
} catch (final EJBTransactionRolledbackException ex) {
getLogger().error("\n\n***************************************************");
getLogger().error("assertion: " + assertionFormula + "\n");
getLogger().fatal(ex.getMessage() + "\n", ex);
getLogger().info("shutting down");
getLogger().error("***************************************************\n\n");
return;
}
}
}
}
}
}
/** finds or creates the given assertion.
*
* @param assertion the given assertion to find or create
* @return the assertion object
* @throws IOException in case of a communications proble
*/
public AbstractTerm findOrCreateAssertion(final CycAssertion assertion) throws IOException {
// Preconditions
assert assertion != null : Constants.ASSERTION_ERR;
assert cycAccess != null : Constants.CYC_ACCESS_ERR;
CycList assertionFormula = null;
if (cachedAssertionFormula.equals(UNINITIALIZED_ASSERTION_FORMULA)) {
assertionFormula = assertionFormula(assertion);
} else {
assertionFormula = cachedAssertionFormula;
cachedAssertionFormula = UNINITIALIZED_ASSERTION_FORMULA;
}
if (isGAF(assertion)) {
return findOrCreateGAFAssertion(assertion, assertionFormula);
} else {
return findOrCreateRuleAssertion(assertion, assertionFormula);
}
}
/** finds or creates the given GAF assertion.
*
* @param assertion the given assertion to find or create
* @param assertionFormula the assertion formula
* @return the GAF object
* @throws IOException in case of a communications problem
*/
public AbstractTerm findOrCreateGAFAssertion(
final CycAssertion assertion,
final CycList assertionFormula) throws IOException {
// Preconditions
assert assertion != null : Constants.ASSERTION_ERR;
assert cycAccess != null : Constants.CYC_ACCESS_ERR;
final CycConstant predicateTerm = (CycConstant) assertionFormula.first();
final AtomicTerm predicate = (AtomicTerm) findOrCreateTerm(predicateTerm);
final CycList argTerms = (CycList) assertionFormula.rest();
final int argTermsSize = argTerms.size();
final List<AbstractTerm> args = new ArrayList<AbstractTerm>(argTermsSize);
for (int i = 0; i < argTermsSize; i++) {
final Object argTerm = argTerms.get(i);
args.add(findOrCreateTerm(argTerm));
}
AbstractReifiedTerm context = null;
context = (AbstractReifiedTerm) findOrCreateTerm(assertion.getMt());
final Double strength = getAssertionStrength(assertion);
switch (argTermsSize) {
case 1:
return termFinderFacade.findOrCreateUnaryGAFByConstituents(
predicate,
args,
context,
strength,
null,
creator,
creationPurpose);
case 2:
return termFinderFacade.findOrCreateBinaryGAFByConstituents(
predicate,
args,
context,
strength,
null,
false,
creator,
creationPurpose);
case 3:
return termFinderFacade.findOrCreateTernaryGAFByConstituents(
predicate,
args,
context,
strength,
null,
creator,
creationPurpose);
case 4:
return termFinderFacade.findOrCreateQuaternaryGAFByConstituents(
predicate,
args,
context,
strength,
null,
creator,
creationPurpose);
case 5:
return termFinderFacade.findOrCreateQuintaryGAFByConstituents(
predicate,
args,
context,
strength,
null,
creator,
creationPurpose);
default:
assert false : "invalid number of arguments " + assertion.cyclify();
return null;
}
}
/** Retrieves the assertion strength.
*
* @param assertion the OpenCyc assertion
* @return the assertion strength
* @throws IOException when an input/output problem occurs
*/
private Double getAssertionStrength(final CycAssertion assertion) throws IOException {
final CycList command = new CycList(2);
Double strength = null;
if (cachedAssertionStrength.equals(Constants.UNINITIALIZED_ASSERTION_STRENGTH)) {
command.add(CycObjectFactory.makeCycSymbol("assertion-strength"));
command.add(assertion);
final String strengthSymbolString = cycAccess.converseObject(command).toString();
if (":DEFAULT".equals(strengthSymbolString)) {
strength = Constants.STRENGTH_DEFAULT;
} else if (":MONOTONIC".equals(strengthSymbolString)) {
strength = Constants.STRENGTH_MONOTONIC;
} else {
strength = Constants.STRENGTH_DEFAULT;
}
} else {
if (cachedAssertionStrength.intValue() == 1) {
strength = Constants.STRENGTH_DEFAULT;
} else if (cachedAssertionStrength.intValue() == 2) {
strength = Constants.STRENGTH_MONOTONIC;
} else {
strength = Constants.STRENGTH_DEFAULT;
}
cachedAssertionStrength = Constants.UNINITIALIZED_ASSERTION_STRENGTH;
}
return strength;
}
/** finds or creates the given rule assertion.
*
* @param assertion the given assertion to find or create
* @param assertionFormula the assertion formula
* @return the rule object
* @throws IOException in case of a communications problem
*/
public Rule findOrCreateRuleAssertion(final CycAssertion assertion, final CycList assertionFormula)
throws IOException {
// Preconditions
assert assertion != null : Constants.ASSERTION_ERR;
assert cycAccess != null : Constants.CYC_ACCESS_ERR;
final Formula formula = findOrCreateFormula(assertionFormula);
final AbstractReifiedTerm context = (AbstractReifiedTerm) findOrCreateTerm(assertion.getMt());
Double strength = null;
final CycList command = new CycList();
command.add(CycObjectFactory.makeCycSymbol("assertion-strength"));
command.add(assertion);
final String strengthSymbolString = cycAccess.converseObject(command).toString();
if (":DEFAULT".equals(strengthSymbolString)) {
strength = Constants.STRENGTH_DEFAULT;
} else if (":MONOTONIC".equals(strengthSymbolString)) {
strength = Constants.STRENGTH_MONOTONIC;
} else {
strength = Constants.STRENGTH_DEFAULT;
}
return termFinderFacade.findOrCreateRuleByFormula(
formula,
context,
strength,
creator,
creationPurpose);
}
/** Gets the assertion's EL formula, using the minimum calls to OpenCyc.
*
* @param assertion the given assertion
* @return the assertion's EL formula
* @throws IOException in case of a communications problem
*/
public CycList assertionFormula(final CycAssertion assertion) throws IOException {
// Preconditions
assert assertion != null : Constants.ASSERTION_ERR;
assert cycAccess != null : Constants.CYC_ACCESS_ERR;
CycList assertionFormula = null;
if (isGAF(assertion)) {
final CycList positiveLiterals = (CycList) assertion.getFormula().second();
assertionFormula = (CycList) positiveLiterals.first();
} else {
final CycList command = new CycList(2);
command.add(CycObjectFactory.makeCycSymbol("assertion-formula"));
command.add(assertion);
assertionFormula = cycAccess.converseList(command);
}
// Postconditions
assert assertionFormula != null : "assertionFormula must not be null";
return assertionFormula;
}
/** Finds or creates the given term.
*
* @param term the given OpenCyc term
* @return the persisted term object
* @throws IOException in case of a communications problem
*/
public AbstractTerm findOrCreateTerm(final Object term) throws IOException { // NOPMD
// Preconditions
assert term != null : Constants.TERM_ERR;
assert cycAccess != null : Constants.CYC_ACCESS_ERR;
getLogger().debug("findOrCreateTerm: " + term.toString());
AbstractTerm abstractTerm = null;
if (term instanceof CycVariable) {
abstractTerm = findOrCreateVariableTerm((CycVariable) term);
} else if (term instanceof CycSymbol) {
abstractTerm = findOrCreateSymbolTerm((CycSymbol) term);
} else if (term instanceof Integer || term instanceof Long || term instanceof BigInteger) {
abstractTerm = findOrCreateIntegerTerm(term);
} else if (term instanceof Float || term instanceof Double) {
abstractTerm = findOrCreateFloatTerm(term);
} else if (term instanceof String) {
abstractTerm = findOrCreateStringTerm((String) term);
} else if (term instanceof CycConstant) {
abstractTerm = findOrCreateAtomicTerm((CycConstant) term);
} else if (term instanceof CycNart) {
abstractTerm = findOrCreateNonAtomicTerm((CycNart) term);
} else if (term instanceof CycList) {
abstractTerm = findOrCreateFormula((CycList) term);
} else if (term instanceof CycAssertion) {
abstractTerm = findOrCreateAssertion((CycAssertion) term);
} else {
assert false : "unhandled term type: (" + term.getClass().getName() + ") " + term.toString();
}
return abstractTerm;
}
/** Finds or creates the corresponding variable term.
*
* @param term the given variable term
* @return the variable object
*/
private PVariable findOrCreateVariableTerm(final CycVariable term) {
// Preconditions
assert term != null : Constants.TERM_ERR;
return termFinderFacade.findOrCreatePVariableByNameValue(term.toString());
}
/** Finds or creates the corresponding symbol term.
*
* @param term the given symbol term
* @return the symbol object
*/
private Symbol findOrCreateSymbolTerm(final CycSymbol term) {
// Preconditions
assert term != null : Constants.TERM_ERR;
String symbolName = term.toString();
if (symbolName.charAt(0) != ':') {
symbolName = ":" + symbolName;
}
return termFinderFacade.findOrCreateSymbolByNameValue(symbolName);
}
/** Finds or creates the corresponding integer term.
*
* @param term the given integer term
* @return the PLong object
*/
private PLong findOrCreateIntegerTerm(final Object term) {
// Preconditions
assert term != null : Constants.TERM_ERR;
return termFinderFacade.findOrCreatePLongByLongValue(Long.valueOf(term.toString()));
}
/** Finds or creates the corresponding float term.
*
* @param term the given float term
* @return the PFloat object
*/
private PDouble findOrCreateFloatTerm(final Object term) {
// Preconditions
assert term != null : Constants.TERM_ERR;
return termFinderFacade.findOrCreatePDoubleByDoubleValue(Double.valueOf(term.toString()));
}
/** Finds or creates the corresponding string term.
*
* @param term the given string term
* @return the PFloat object
*/
private PString findOrCreateStringTerm(final Object term) {
// Preconditions
assert term != null : Constants.TERM_ERR;
return termFinderFacade.findOrCreatePStringByStringValue(term.toString());
}
/** Finds or creates the given atomic term.
*
* @param term the given atomic term
* @return the atomic term object
* @throws IOException when an input/output problem occurs
*/
private AtomicTerm findOrCreateAtomicTerm(final CycConstant term) throws IOException {
// Preconditions
assert term != null : Constants.TERM_ERR;
assert cycAccess != null : Constants.CYC_ACCESS_ERR;
final String termName = term.toString();
String prettyName = (String) cycAccess.getArg2(cycAccess.getKnownConstantByName("prettyString-Canonical"), term);
if (prettyName == null) {
prettyName = term.toString();
}
final String uuid = term.getGuid().toString();
return termFinderFacade.findOrCreateAtomicTermByTermName(
termName,
prettyName,
uuid,
creator,
creationPurpose);
}
/** Finds or creates the given non-atomic term.
*
* @param term the given non-atomic term
* @return the non-atomic term object
* @throws IOException when an input/output problem occurs
*/
private NonAtomicTerm findOrCreateNonAtomicTerm(final CycNart term) throws IOException {
// Preconditions
assert term != null : Constants.TERM_ERR;
final String uuid = UUID.randomUUID().toString();
final List argTerms = term.getArguments();
final int argTermsSize = argTerms.size();
final List<AbstractTerm> args = new ArrayList<AbstractTerm>(argTermsSize + 1);
//TODO ensure that embedded narts are expanded to term lists
args.add(findOrCreateTerm(term.getFunctor()));
for (int i = 0; i < argTermsSize; i++) {
args.add(findOrCreateTerm(argTerms.get(i)));
}
final java.util.Date today = new java.util.Date();
final Timestamp now = new Timestamp(today.getTime());
final TimePoint creationTimePoint = termFinderFacade.findOrCreateTimePointByTimePointValue(now);
final Formula formula = new Formula(
args,
creator,
creationPurpose,
creationTimePoint);
final String termName = formula.toString();
return termFinderFacade.findOrCreateNonAtomicTermByTermName(
termName,
null,
uuid,
formula,
creator,
creationPurpose);
}
/** Finds or creates the given formula.
*
* @param term the given formula term
* @return the formula object
* @throws IOException in case of a communications problem
*/
public Formula findOrCreateFormula(final CycList term) throws IOException {
// Preconditions
assert term != null : Constants.TERM_ERR;
assert cycAccess != null : Constants.CYC_ACCESS_ERR;
final int termSize = term.size();
final List<AbstractTerm> termList = new ArrayList<AbstractTerm>(termSize);
for (int i = 0; i < termSize; i++) {
//TODO ensure that embedded narts are expanded to term lists
termList.add(findOrCreateTerm(term.get(i)));
}
return termFinderFacade.findOrCreateFormulaByTermList(
termList,
creator,
creationPurpose);
}
/** Returns true if the given assertion formula contains a term that should not be converted.
*
* @param assertionFormula the given assertion formula
* @return true if the given assertion contains a term that should not be converted
*/
public boolean hasExcludedTerm(final CycList assertionFormula) { // NOPMD
// Preconditions
assert assertionFormula != null : "assertionFormula must not be null";
final CycList terms = expandEmbeddedNarts(assertionFormula).flatten();
final int termsSize = terms.size();
for (int i = 0; i < termsSize; i++) {
final String termString = terms.get(i).toString();
if (termString.startsWith("ObtainingASearchResult")) {
return true;
} else if ("termOfUnit".equals(termString)) {
return true;
} else if ("URLFn".equals(termString)) {
return true;
} else if ("URIFn".equals(termString)) {
return true;
} else if ("WordNetSynsetReifiedFn".equals(termString)) {
return true;
} else if ("BuilderQueryTemplateForLogicalFieldTypeOfSKSFn".equals(termString)) {
return true;
} else if ("MeaningInSystemFn".equals(termString)) {
return true;
} else if ("PhysicalFieldFn".equals(termString)) {
return true;
} else if ("LogicalFieldFn".equals(termString)) {
return true;
}
}
return false;
}
/** Returns whether the given assertion is a ground atomic formula with an atomic predicate.
*
* @param assertion the given assertion
* @return whether the given assertion is a ground atomic formula with an atomic predicate
* @throws IOException in case of a communications problem
*/
public boolean isGAF(final CycAssertion assertion) throws IOException {
// Preconditions
assert assertion != null : Constants.ASSERTION_ERR;
final Object negativeLiterals = assertion.getFormula().first();
if (negativeLiterals instanceof CycList && !((CycList) negativeLiterals).isEmpty()) {
return false;
}
final CycList positiveLiterals = (CycList) assertion.getFormula().second();
if (positiveLiterals.size() > 1) {
return false;
}
final CycList positiveLiteral = (CycList) positiveLiterals.first();
final CycObject predicate = (CycObject) positiveLiteral.first();
if (!(predicate instanceof CycConstant)) {
return false;
}
final CycList args = (CycList) positiveLiteral.rest();
final int argsSize = args.size();
for (int i = 0; i < argsSize; i++) {
final Object arg = args.get(i);
if (arg instanceof CycVariable) {
return false;
}
}
return true;
}
/** Returns true if the given object is a CycVariable or is a list that contains an embedded CycVariable.
*
* @param obj the given object
* @return true if the given object is a CycVariable or is a list that contains an embedded CycVariable
*/
public boolean isCycVariableContained(final Object obj) {
// Preconditions
assert obj != null : "obj must not be null";
if (obj instanceof CycVariable) {
return true;
} else if (obj instanceof CycList) {
final Iterator listIter = ((CycList) obj).iterator();
while (listIter.hasNext()) {
if (isCycVariableContained(listIter.next())) {
return true;
}
}
}
return false;
}
/**
* Returns a list with any embedded NARTs expanded into list form.
*
* @param cycList the given list to expand
* @return a list with any embedded NARTs expanded into list form
*/
public CycList expandEmbeddedNarts(final CycList cycList) {
final CycList expandedCycList = new CycList();
final Iterator expandedCycListIter = cycList.iterator();
while (expandedCycListIter.hasNext()) {
final Object obj = expandedCycListIter.next();
if (obj instanceof CycNart) {
expandedCycList.add(((CycNart) obj).toDeepCycList());
} else {
expandedCycList.add(obj);
}
}
return expandedCycList;
}
/**
* Returns a list with any improper lists of the form (A . B) converted to the form (A :REST B).
*
* @param cycList the given list to fix
* @return a list with any improper lists of the form (A . B) converted to the form (A :REST B)
*/
public CycList fixImproperLists(final CycList cycList) {
final CycList fixedCycList = new CycList();
final Iterator cycListIter = cycList.iterator();
while (cycListIter.hasNext()) {
final Object obj = cycListIter.next();
if (obj instanceof CycList) {
fixedCycList.add(fixImproperLists((CycList) obj));
} else {
fixedCycList.add(obj);
}
}
if (!cycList.isProperList()) {
final int positionOfRestSymbol = fixedCycList.size() - 1;
final Object lastElement = fixedCycList.get(positionOfRestSymbol);
fixedCycList.set(positionOfRestSymbol, CycObjectFactory.makeCycSymbol(":REST"));
fixedCycList.add(lastElement);
}
return fixedCycList;
}
/** Gets the logger.
*
* @return the logger
*/
private Logger getLogger() {
if (logger == null) {
logger = Logger.getLogger(Cyc2RDB.class.getName());
}
return logger;
}
/** Sets the transaction timeout. */
private void setTransactionTimeout() {
try {
final TransactionManager transactionManager =
(TransactionManager) new InitialContext().lookup(Constants.JAVA_TRANSACTION_MANAGER_NAME);
transactionManager.setTransactionTimeout(Constants.TRANSACTION_TIMEOUT_SECONDS);
} catch (NamingException ex) {
throw new TexaiException(ex);
} catch (SystemException ex) {
throw new TexaiException(ex);
}
}
/** Sets the transaction timeout. */
public void setTransactionTimeout(final int timeoutSeconds) {
//Preconditions
assert timeoutSeconds >= 0 : "timeoutSeconds " + timeoutSeconds + " must not be negative";
assert userTransaction != null : "entityTransaction must not be null";
try {
userTransaction.setTransactionTimeout(timeoutSeconds);
} catch (final SystemException ex) {
throw new TexaiException(ex);
}
}
/** Begins the transaction. */
public void beginTransaction() {
//Preconditions
assert userTransaction != null : "entityTransaction must not be null";
try {
userTransaction.begin();
} catch (final javax.transaction.NotSupportedException ex) {
throw new TexaiException(ex);
} catch (final SystemException ex) {
throw new TexaiException(ex);
}
}
/** Commits the transaction. */
public void commitTransaction() {
//Preconditions
assert userTransaction != null : "entityTransaction must not be null";
try {
userTransaction.commit();
} catch (final IllegalStateException ex) {
throw new TexaiException(ex);
} catch (final SecurityException ex) {
throw new TexaiException(ex);
} catch (final HeuristicRollbackException ex) {
throw new TexaiException(ex);
} catch (final HeuristicMixedException ex) {
throw new TexaiException(ex);
} catch (final SystemException ex) {
throw new TexaiException(ex);
} catch (final RollbackException ex) {
throw new TexaiException(ex);
}
}
/** Clears the entity manager. */
public void clearEntityManager() {
//Preconditions
assert entityManager != null : "entityManager must not be null";
entityManager.clear();
}
} // NOPMD
See more files for this project here