/* $This file is distributed under the terms of the license in /doc/license.txt$ */

package edu.cornell.mannlib.vitro.webapp.utils.jena;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.RDFNode;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.rdf.model.ResourceFactory;
import com.hp.hpl.jena.rdf.model.StmtIterator;
import com.hp.hpl.jena.shared.Lock;

public class URIUtils {
	
	private static final Log log = LogFactory.getLog(URIUtils.class.getName());
		
	 public static boolean hasExistingURI(String uriStr, OntModel ontModel) {
	    	boolean existingURI = false;
			ontModel.enterCriticalSection(Lock.READ);
			try {
				Resource newURIAsRes = ResourceFactory.createResource(uriStr);
				Property newURIAsProp = ResourceFactory.createProperty(uriStr);
				StmtIterator closeIt = ontModel.listStatements(
						newURIAsRes, null, (RDFNode)null);
				if (closeIt.hasNext()) {
					existingURI = true;
					
				}
				//if not in the subject position, check in object position
				if (!existingURI) {
					closeIt = ontModel.listStatements(null, null, newURIAsRes);
					if (closeIt.hasNext()) {
						existingURI= true;
					}
				}
				//Check for property
				if (!existingURI) {
					closeIt = ontModel.listStatements(
							null, newURIAsProp, (RDFNode)null);
					if (closeIt.hasNext()) {
						existingURI = true;
					}
				}
			} finally {
				ontModel.leaveCriticalSection();
			}
			
			return existingURI;	
	    }
}

@@ -800,83 +800,272 @@
 %09%09%09%09
-Resource newURIAsRes = ResourceFactory.createResource(uriStr);%0A%09%09%09%09Property
+boolean validPropertyURI = true;%0A%09%09%09%09String localName = uriStr.substring(uriStr.lastIndexOf(%22/%22) + 1);%0A%09%09%09%09//if local name is only numbers, this is not a valid uri for a property%0A%09%09%09%09if(localName.matches(%22%5C%5Cd+%22)) %7B%0A%09%09%09%09%09validPropertyURI = false;%0A%09%09%09%09%7D%0A%09%09%09%09Resource
  new
@@ -1069,20 +1069,19 @@
 newURIAs
-Prop
+Res
  = Resou
@@ -1097,24 +1097,24 @@
 y.create
-Property
+Resource
 (uriStr)
@@ -1115,16 +1115,21 @@
 riStr);%0A
+%09%09%09%09%0A
 %09%09%09%09Stmt
@@ -1528,39 +1528,128 @@
 rty%0A%09%09%09%09if (
-!existingURI) %7B
+validPropertyURI && !existingURI) %7B%0A%09%09%09%09%09Property newURIAsProp = ResourceFactory.createProperty(uriStr);
 %0A%09%09%09%09%09closeI

update to check if uri valid property uri before checking it exists as property