I am not able to update ontology model - java

I have made an Ontologu in Protege and imported in Eclipse.My ontology already 10 instances and i want to add more instances.The following piece of code adds instances to existing class (Noun) of ontology. After excecution it do not update ontology model and shows same number of instances.
public static void main(String[] args) throws OWLException, IOException{
OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
File file = new File("D:\\word.owl");{
OntModel model=ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM_RULE_INF);
System.out.println("Model is called successfully");
OWLOntology ont = manager.loadOntologyFromOntologyDocument(file);
System.out.println("Loaded ontology: " + ont);
String SOURCE = ("D:\\word.owl");
String NS = SOURCE;
OntModel base = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM_RULE_INF);
base.read( SOURCE, "" );
OntModel inf =ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM_RULE_INF, base );
OntClass Noun = base.getOntClass( NS + "Noun" );
Individual jack = base.createIndividual( NS + "Jack", Noun );
Individual Helley = base.createIndividual( NS + "Helley", Noun );
manager.saveOntology(ont);
System.out.println("Number of individuals: " + ont.getIndividualsInSignature().size());
}
}
}
Output
Model is called successfully
Loaded ontology:
Number of individuals: 10

I dont use that API but I can see your issue.
At the start of your code you create an OWLOntology object:
OWLOntology ont = manager.loadOntologyFromOntologyDocument(file);
And here is the issue, you do not alter ont anywhere in your code, so when you call the line below, it will only show/save the same 10 individuals that you loaded from file at the beginning of your code:
manager.saveOntology(ont);
System.out.println("Number of individuals: " + ont.getIndividualsInSignature().size());
So to fix this you need to somehow modify ont to include the new Individual before using the above lines.

This works:
import java.io.FileWriter;
import java.io.InputStream;
import org.apache.jena.ontology.Individual;
import org.apache.jena.ontology.OntClass;
import org.apache.jena.ontology.OntModel;
import org.apache.jena.ontology.OntModelSpec;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.util.FileManager;
import org.apache.jena.vocabulary.RDF;
public class Mgt {
public static void main(String[] args) throws Exception {
String namespace = "http://www.semanticweb.org/Word#";
String file = "word.owl";
OntModel jenaModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM_RULE_INF);
InputStream in = FileManager.get().open(file);
jenaModel.read(in, null);
OntClass Noun = jenaModel.getOntClass(namespace + "Noun");
Individual Organization = Noun.createIndividual(namespace + "Organization");
jenaModel.add(Organization, RDF.type, Noun);
FileWriter out = new FileWriter("word.out.owl");
jenaModel.getWriter("RDF/XML-ABBREV").write(jenaModel, out, namespace);
out.close();
}
}
Note that namespace is not related to the file name.

Updated Code It gives Exception in thread "main" java.lang.NullPointerException
at Mgt.main(Mgt.java:29)
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import org.apache.jena.ontology.Individual;
import org.apache.jena.ontology.OntClass;
import org.apache.jena.ontology.OntModel;
import org.apache.jena.ontology.OntModelSpec;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.util.FileManager;
public class Mgt {
static OntModel jenaModel = null;
public static void main(String[] args) throws Exception{
String file =("D:\\word.owl");
jenaModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM_RULE_INF);
InputStream in = FileManager.get().open(file);
try
{
jenaModel.read(in, null);
}
catch (Exception e)
{
e.printStackTrace();
}
System.out.println("Ontology " + file + " loaded.");
OntClass Noun = jenaModel.getOntClass( "http://www.semanticweb.org/Word#Noun" );
Individual Organization = Noun.createIndividual(file + "Organization");
FileWriter out = null;
try {
// XML format - long and verbose
out = new FileWriter( file);
jenaModel.write( out, "RDF/XML" );
}
finally {
if (out != null) {
try {out.close();
} catch (IOException ignore) {}
}
}
}
}

Related

Java: Error marshalling or unmarshalling data: null

I am trying to use a model that is built on java. Here is the model main class:
package madamira;
import edu.columbia.ccls.madamira.MADAMIRAWrapper;
import edu.columbia.ccls.madamira.configuration.MadamiraInput;
import edu.columbia.ccls.madamira.configuration.MadamiraOutput;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.File;
import java.util.concurrent.ExecutionException;
/**
* An example class that shows how MADAMIRA can be called through its API.
*
*/
public class madamira {
// MADAMIRA namespace as defined by its XML schema
private static final String MADAMIRA_NS = "edu.columbia.ccls.madamira.configuration";
private static final String INPUT_FILE = "~/Users/user/Desktop/comp_ling/ACL_arabic_parser/udpipe-master/src/MADAMIRA-release-20170403-2.1/padt_sents.xml";
private static final String OUTPUT_FILE = "~/Users/user/Desktop/comp_ling/ACL_arabic_parser/udpipe-master/src/MADAMIRA-release-20170403-2.1/sampleOutputFile.xml";
public static void main(String [] args) {
final MADAMIRAWrapper wrapper = new MADAMIRAWrapper();
JAXBContext jc = null;
try {
jc = JAXBContext.newInstance(MADAMIRA_NS);
Unmarshaller unmarshaller = jc.createUnmarshaller();
// The structure of the MadamiraInput object is exactly similar to the
// madamira_input element in the XML
final MadamiraInput input = (MadamiraInput)unmarshaller.unmarshal(
new File( INPUT_FILE ) );
{
int numSents = input.getInDoc().getInSeg().size();
String outputAnalysis = input.getMadamiraConfiguration().
getOverallVars().getOutputAnalyses();
String outputEncoding = input.getMadamiraConfiguration().
getOverallVars().getOutputEncoding();
System.out.println("processing " + numSents +
" sentences for analysis type = " + outputAnalysis +
" and output encoding = " + outputEncoding);
}
// The structure of the MadamiraOutput object is exactly similar to the
// madamira_output element in the XML
final MadamiraOutput output = wrapper.processString(input);
{
int numSents = output.getOutDoc().getOutSeg().size();
System.out.println("processed output contains "+numSents+" sentences...");
}
jc.createMarshaller().marshal(output, new File(OUTPUT_FILE));
} catch (JAXBException ex) {
System.out.println("Error marshalling or unmarshalling data: "
+ ex.getMessage());
} catch (InterruptedException ex) {
System.out.println("MADAMIRA thread interrupted: "
+ex.getMessage());
} catch (ExecutionException ex) {
System.out.println("Unable to retrieve result of task. " +
"MADAMIRA task may have been aborted: "+ex.getCause());
}
wrapper.shutdown();
}
}
I am getting this error:
Unable to read form brown file resources/paths in resources dir. resources/paths
Error marshalling or unmarshalling data: null
I am not sure what the problem is. could you guys help? I think the problem has to do with some missing or clashing dependencies.
By the way, I am using Java "11.0.2" 2019-01-15 LTS and running the model in eclipse.
thank you

Reading XSD from URL using Java

Objective : I want to read a WSDL and print the services in the WSDL, complex types and Complex type definitions.
Worked : I've used WSDL4J for reading WSDL and successfully able to print the services and their parameters (complex types). Now I want to read the complex type definitions which is available in XSD. I'm unable to read XSD .Is ther any way to do it ?
I'm getting XSModel as null
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import javax.wsdl.BindingOperation;
import javax.wsdl.Definition;
import javax.wsdl.WSDLException;
import javax.wsdl.xml.WSDLReader;
import org.w3c.dom.bootstrap.DOMImplementationRegistry;
import com.ibm.wsdl.BindingImpl;
import com.ibm.wsdl.xml.WSDLReaderImpl;
import com.sun.org.apache.xerces.internal.impl.xs.XSImplementationImpl;
import com.sun.org.apache.xerces.internal.xs.XSLoader;
import com.sun.org.apache.xerces.internal.xs.XSModel;
public class WSDLDetails {
public static void main(String[] args) {
try {
String wsdlURL = "https://abc.xyz.com/webservice/MessagingSevice?WSDL";
String xsdURL = "https://abc.xyz.com/webservice/MessagingSevice?xsd=1";
java.lang.System.setProperty("https.protocols", "TLSv1.2");
getAllBindingOperation(wsdlURL);
readXSD(xsdURL);
} catch (Exception e) {
e.printStackTrace();
}
}
public static List<String> getAllBindingOperation(String wsdlUrl) {
List<BindingOperation> operationList = new ArrayList();
List<String> nameList = new ArrayList();
try {
WSDLReader reader = new WSDLReaderImpl();
reader.setFeature("javax.wsdl.verbose", false);
Definition definition = reader.readWSDL(wsdlUrl.toString());
Map<String, BindingImpl> defMap = definition.getAllBindings();
Collection<BindingImpl> collection = defMap.values();
for (BindingImpl binding : collection) {
operationList.addAll(binding.getBindingOperations());
}
for (BindingOperation operation:operationList) {
nameList.add(operation.getName());
System.out.println("Name :: " + operation.getName());
System.out.println("Request :: " + operation.getBindingInput());
System.out.println("Response :: " + operation.getBindingOutput());
}
} catch (WSDLException e) {
System.out.println("get wsdl operation fail.");
e.printStackTrace();
}
return nameList;
}
public static void readXSD(String xsdURL) {
try {
System.setProperty(DOMImplementationRegistry.PROPERTY, "com.sun.org.apache.xerces.internal.dom.DOMXSImplementationSourceImpl");
DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
com.sun.org.apache.xerces.internal.impl.xs.XSImplementationImpl impl = (XSImplementationImpl) registry.getDOMImplementation("XS-Loader");
XSLoader schemaLoader = impl.createXSLoader(null);
XSModel model = schemaLoader.loadURI(xsdURL);
System.out.println(model);
} catch (Exception e) {
e.printStackTrace();
}
}
You can use xsd2java plugin with maven
https://github.com/qaware/xsd2java-gradle-plugin
Here is an example showing how to retrieve the XSModel from an XSD URL, and print the complex types declared therein.
import org.apache.xerces.impl.xs.XMLSchemaLoader;
import org.apache.xerces.impl.xs.XSComplexTypeDecl;
import org.apache.xerces.impl.xs.XSElementDecl;
import org.apache.xerces.xs.XSConstants;
import org.apache.xerces.xs.XSModel;
import org.apache.xerces.xs.XSNamedMap;
import org.apache.xerces.xs.XSTypeDefinition;
public class Test {
public static void main(String[] args) {
try {
String xsdURL = "http://fsharp.github.io/FSharp.Data/data/po.xsd";
XMLSchemaLoader xsLoader = new XMLSchemaLoader();
XSModel xsModel = xsLoader.loadURI(xsdURL);
// print global element declarations
System.out.println("\nGlobal Element Declarations:");
XSNamedMap globalElemDecls = xsModel.getComponents(XSConstants.ELEMENT_DECLARATION);
globalElemDecls.forEach((k,v) -> System.out.println((XSElementDecl) v));
// print global complex type declarations
System.out.println("\nGlobal Complex Type Declarations:");
XSNamedMap globalComplexTypeDecls = xsModel.getComponents(XSTypeDefinition.COMPLEX_TYPE);
globalComplexTypeDecls.forEach((k,v) -> System.out.println((XSComplexTypeDecl) v));
} catch (Exception e) {
e.printStackTrace();
}
}
}
If you got null at xsLoader.loadURI(xsdURL), it is likely there are some flaws in the given XSD file. For example, "White spaces are required between publicId and systemId". You might need to fix these flaws first.

Replace Image in an placeholder inside generated PPT using PPTX4j

#JasonPlutext,
Hi Jason! I tried the above code but it just replaces an totally the image deleting the whole template.
I would like to just replace/add a particular relationship of the image ,say
<Relationship Id="rId8" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" Target="../media/image10.png"/>
in place of rId8 i would like to replace rId7 image.
My Source Code:
public static void main(String[] args) throws Exception {
String inputfilepath = "C:\\Users\\saranyac\\QUERIES\\Estimation\\PPT-PSR\\PSR_Dev0ps\\PSRAutomationTemplate.pptx";
PresentationMLPackage presentationMLPackage = (PresentationMLPackage)OpcPackage.load(new java.io.File(inputfilepath));
MainPresentationPart pp = presentationMLPackage.getMainPresentationPart();
SlidePart slidePart = presentationMLPackage.getMainPresentationPart().getSlide(0);
SlideLayoutPart layoutPart = slidePart.getSlideLayoutPart();
System.out.println("SlidePart Name:::::"+slidePart.getPartName().getName());
String layoutName = layoutPart.getJaxbElement().getCSld().getName();
System.out.println("layout: " + layoutPart.getPartName().getName() + " with cSld/#name='" + layoutName + "'");
System.out.println("Master: " + layoutPart.getSlideMasterPart().getPartName().getName());
System.out.println("layoutPart.getContents()::::::::s: " + layoutPart.getContents());
//layoutPart.setContents( (SldLayout)XmlUtils.unmarshalString(SAMPLE_PICTURE, Context.jcPML));
// Add image part
File file = new File("C:\\Users\\saranyac\\PPT-PSR\\PSR_Dev0ps\\ppt\\media\\image10.png" );
BinaryPartAbstractImage imagePart
= BinaryPartAbstractImage.createImagePart(presentationMLPackage, slidePart, file);
Relationship rel = pp.getRelationshipsPart().getRelationshipByID("rId8");
System.out.println("Relationship:::::::s: " +imagePart.getSourceRelationship().getId());
// pp.removeSlide(rel);
java.util.HashMap<String, String>mappings = new java.util.HashMap<String, String>();
mappings.put("rId8", imagePart.getSourceRelationship().getId());
String outputfilepath = "C:\\Work\\24Jan2018_CheckOut\\PPT-TRAILS\\Success.pptx";
//presentationMLPackage.save(new java.io.File(outputfilepath));
SaveToZipFile saver = new SaveToZipFile(presentationMLPackage);
saver.save(outputfilepath);
System.out.println("\n\n done .. saved " + outputfilepath);
}
Please help me how to replace an image in the generated PPT.
With Regards,
Saranya
See https://github.com/plutext/docx4j/blob/master/src/samples/pptx4j/org/pptx4j/samples/TemplateReplaceSimple.java (just added):
package org.pptx4j.samples;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.xml.bind.JAXBException;
import org.apache.commons.io.FileUtils;
import org.docx4j.TraversalUtil;
import org.docx4j.TraversalUtil.CallbackImpl;
import org.docx4j.dml.CTBlip;
import org.docx4j.dml.CTBlipFillProperties;
import org.docx4j.openpackaging.exceptions.Docx4JException;
import org.docx4j.openpackaging.packages.OpcPackage;
import org.docx4j.openpackaging.packages.PresentationMLPackage;
import org.docx4j.openpackaging.parts.Part;
import org.docx4j.openpackaging.parts.PresentationML.SlidePart;
import org.docx4j.openpackaging.parts.WordprocessingML.BinaryPartAbstractImage;
import org.pptx4j.Pptx4jException;
/**
* Example of how to replace text and images in a Pptx.
*
* Text is replaced using the familiar VariableReplace approach.
*
* Images are replaced by replacing their byte content.
*
* #author jharrop
*
*/
public class TemplateReplaceSimple {
public static void main(String[] args) throws Docx4JException, Pptx4jException, JAXBException, IOException {
// Input file
String inputfilepath = System.getProperty("user.dir") + "/sample-docs/pptx/image.pptx";
// String replacements
HashMap<String, String> mappings = new HashMap<String, String>();
mappings.put("colour", "green");
// Image replacements
List<ImageReplacementDetails> imageReplacements = new ArrayList<ImageReplacementDetails>();
ImageReplacementDetails example1 = new ImageReplacementDetails();
example1.slideIndex = 0;
example1.imageRelId = "rId2";
example1.replacementImageBytes = FileUtils.readFileToByteArray(new File("test.png"));
imageReplacements.add(example1);
PresentationMLPackage presentationMLPackage =
(PresentationMLPackage)OpcPackage.load(new java.io.File(inputfilepath));
// First, the text replacements
List<SlidePart> slideParts=
presentationMLPackage.getMainPresentationPart().getSlideParts();
for (SlidePart slidePart : slideParts) {
slidePart.variableReplace(mappings);
}
// Second, the image replacements.
// We have a design choice here.
// Either we can replace text placeholders with images,
// or we can replace existing images with new images, but keep the XML specifying size etc
// Here I opt for the latter, so what we need is the relId and image bytes.
for( ImageReplacementDetails ird : imageReplacements) {
// its a bit inefficient to potentially traverse a single slide
// multiple times, but I've done it this way to keep this example simple
SlidePart slidePart=
presentationMLPackage.getMainPresentationPart().getSlide(ird.slideIndex);
SlidePicFinder traverser = new SlidePicFinder();
new TraversalUtil(slidePart.getJaxbElement().getCSld().getSpTree().getSpOrGrpSpOrGraphicFrame(), traverser);
for(org.pptx4j.pml.Pic pic : traverser.pics) {
CTBlipFillProperties blipFill = pic.getBlipFill();
if (blipFill!=null) {
CTBlip blip = blipFill.getBlip();
if (blip.getEmbed()!=null) {
String relId = blip.getEmbed();
// is this the one we want?
if (relId.equals(ird.imageRelId)) {
Part part = slidePart.getRelationshipsPart().getPart(relId);
try {
BinaryPartAbstractImage imagePart = (BinaryPartAbstractImage)part;
// you'll need to ensure that you replace like with like,
// ie png for png, not eg jpeg for png!
imagePart.setBinaryData(ird.replacementImageBytes);
} catch (ClassCastException cce) {
System.out.println(part.getClass().getName());
}
} else {
System.out.println(relId + " isn't a match for this replacement. ");
}
} else {
System.out.println("No a:blip/#r:embed");
}
}
}
}
System.out.println("\n\n saving .. \n\n");
String outputfilepath = System.getProperty("user.dir") + "/OUT_VariableReplace.pptx";
presentationMLPackage.save(new java.io.File(outputfilepath));
System.out.println("\n\n done .. \n\n");
}
static class ImageReplacementDetails {
int slideIndex;
String imageRelId;
byte[] replacementImageBytes;
}
static class SlidePicFinder extends CallbackImpl {
List<org.pptx4j.pml.Pic> pics = new ArrayList<org.pptx4j.pml.Pic>();
public List<Object> apply(Object o) {
if (o instanceof org.pptx4j.pml.Pic) {
pics.add((org.pptx4j.pml.Pic) o);
System.out.println("added pic");
}
return null;
}
}
}

Protégé OWL API programming

I have a problem with my code i'm working on an antologie file using Protege OWL API (3.4.8) and i want to have all the classes define by the user in the ontologie , the problem is i keep having errors in the for loop i can't fix those errors, is there any way to get the classes.
package Test;
import java.util.Collection;
import javax.swing.text.html.HTMLDocument.Iterator;
import antlr.collections.List;
import edu.stanford.smi.protege.model.Cls;
import edu.stanford.smi.protegex.owl.ProtegeOWL;
import edu.stanford.smi.protegex.owl.jena.JenaOWLModel;
import edu.stanford.smi.protegex.owl.model.OWLDatatypeProperty;
import edu.stanford.smi.protegex.owl.model.OWLIndividual;
import edu.stanford.smi.protegex.owl.model.OWLModel;
import edu.stanford.smi.protegex.owl.model.OWLNamedClass;
import edu.stanford.smi.protegex.owl.model.OWLObjectProperty;
import edu.stanford.smi.protegex.owl.model.RDFSClass;
public class Class4 {
public static JenaOWLModel owlModel =null;
public static String scorKos_Uri="C:/Users/souad/Desktop/SCOR-KOS.owl";
//where my ontologie file exist
//change the URI by this
"http://protege.cim3.net/file/pub/ontologies/travel/travel.owl"; to have a
OWL file
/**
* #param args
*/
public static void main(String[] args) {
/**
* ontologie
*/
try {
owlModel=ProtegeOWL.createJenaOWLModelFromURI(scorKos_Uri);
System.out.println("Worked");
Collection classes = owlModel.getUserDefinedOWLNamedClasses();
for (Iterator it = classes.iterator(); it.hasNext();) {
OWLNamedClass cls = (OWLNamedClass) it.next();
Collection instances = cls.getInstances(false);
System.out.println("Class " + cls.getBrowserText() + " (" +
instances.size() + ")");
for (Iterator jt = instances.iterator(); jt.hasNext();) {
OWLIndividual individual = (OWLIndividual) jt.next();
System.out.println(" - " + individual.getBrowserText());
}
}
}catch (Exception exception) {
System.out.println("Error can't upload the ontologie ");
System.exit(1);
}
}
}
You're not importing java.util.Iterator.

HTML parsing to file from directory with java and Jsoup

I am having trouble with parsing some html files from a directory into an output directory. I'm using Jsoup to remove HTML tags and writing to an output directory but some of the data is lost when I'm testing it. What I want to do in the end with the parsed files is to populate a hashmap so that I can sort the words by frequency and then in a separate directory sort them by alphabetical order. This compiles and runs, but I am getting stuck at the very end when it comes to write out. Code would be lovely and all, but I'm only interested in the steps to take in order to set this entire thing up. Thank you.
Update: Here is code.
Update: Also I feel like Jsoup is getting rid of data.
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
import org.jsoup.Jsoup;
public class Parser {
public static File infolder = new File("input folder folder path goes here");
static String temp = "";
static ArrayList<String> list = new ArrayList<String>();
public static void main(String[] args) throws FileNotFoundException
{
String outfolder = "output folder path goes here";
File theDir = new File(outfolder);
// if the directory does not exist, create it
if (!theDir.exists()) {
System.out.println("creating directory: " + outfolder);
boolean result = theDir.mkdir();
if (result) {
System.out.println("DIR created");
}
}
System.out.println("Reading files under the folder " + infolder.getAbsolutePath());
parseFiles(infolder);
// System.out.println();
}
public static void parseFiles(final File folder) throws FileNotFoundException
{
PrintWriter out = null;
for (final File fileEntry : folder.listFiles()) {
if (fileEntry.isFile()) {
temp = fileEntry.getName();
if ((temp.substring(temp.lastIndexOf('.') + 1, temp.length()).toLowerCase()).equals("html")) {
System.out.println("File= " + folder.getAbsolutePath() + "\\" + fileEntry.getName());
File file = new File(folder.getAbsolutePath() + "\\" + fileEntry.getName());
ArrayList<String> filetext = new ArrayList<String>();
Scanner in = new Scanner(file);
while (in.hasNextLine()) {
filetext.add(in.nextLine());
}
String filename = "tokenfile" + fileEntry.getName();
try {
out = new PrintWriter(new BufferedWriter(new FileWriter("C:/Users/bounty213/Desktop/Output/" + filename + ".txt", true)));
}
catch (IOException e) {
//exception handling left as an exercise for the reader
}
String parsed;
for (String word : filetext) {
parsed = Jsoup.parse(word).text();
System.out.println(parsed);
out.println(parsed);
}
out.close();
}
}
}
}
}

Categories

Resources