how to add image in table(XSLFTable) cell in powerpoint poi api in java - image

how to add image in table(XSLFTable) cell in powerpoint poi api in java, we are not able to get the CTBlipFillProperties through poi latest jar poi-3.15.jar
how to add image in table(XSLFTable) cell in powerpoint poi api in java, we are not able to get the CTBlipFillProperties through poi latest jar poi-3.15.jar
public static void main(String[] args) throws Exception {
XMLSlideShow pptx = new XMLSlideShow();
XSLFSlide slide = pptx.createSlide();
// you need to include ooxml-schemas:1.1 for this to work!!!
// otherwise an empty table will be created
// see https://issues.apache.org/bugzilla/show_bug.cgi?id=49934
XSLFTable table = slide.createTable();
table.setAnchor(new Rectangle2D.Double(50, 50, 500, 20));
XSLFTableRow row = table.addRow();
row.addCell().setText("Cell 1");
XSLFTableCell cell = row.addCell();
cell.setText("Cell 2");
CTBlipFillProperties blipPr = cell.getXmlObject().getTcPr().addNewBlipFill();
blipPr.setDpi(72);
// http://officeopenxml.com/drwPic-ImageData.php
CTBlip blib = blipPr.addNewBlip();
blipPr.addNewSrcRect();
CTRelativeRect fillRect = blipPr.addNewStretch().addNewFillRect();
fillRect.setL(30000);
fillRect.setR(30000);
PackagePartName partName = PackagingURIHelper.createPartName("/ppt/media/100px.gif");
PackagePart part = pptx.getPackage().createPart(partName, "image/gif");
OutputStream partOs = part.getOutputStream();
FileInputStream fis = new FileInputStream("src/test/resources/100px.gif");
byte buf[] = new byte[1024];
for (int readBytes; (readBytes = fis.read(buf)) != -1; partOs.write(buf, 0, readBytes));
fis.close();
partOs.close();
PackageRelationship prs = slide.getPackagePart().addRelationship(partName, TargetMode.INTERNAL, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image");
blib.setEmbed(prs.getId());
FileOutputStream fos = new FileOutputStream("test2.pptx");
pptx.write(fos);
fos.close();
}

You were quite close ... the following was tested on the POI trunk (POI 3.16-beta2), but should work on POI 3.15 too ...
import java.awt.geom.Rectangle2D;
import java.io.File;
import java.io.FileOutputStream;
import org.apache.poi.POIXMLDocumentPart.RelationPart;
import org.apache.poi.sl.usermodel.PictureData.PictureType;
import org.apache.poi.xslf.usermodel.XMLSlideShow;
import org.apache.poi.xslf.usermodel.XSLFPictureData;
import org.apache.poi.xslf.usermodel.XSLFRelation;
import org.apache.poi.xslf.usermodel.XSLFSlide;
import org.apache.poi.xslf.usermodel.XSLFTable;
import org.apache.poi.xslf.usermodel.XSLFTableCell;
import org.apache.poi.xslf.usermodel.XSLFTableRow;
import org.openxmlformats.schemas.drawingml.x2006.main.CTBlip;
import org.openxmlformats.schemas.drawingml.x2006.main.CTBlipFillProperties;
import org.openxmlformats.schemas.drawingml.x2006.main.CTRelativeRect;
import org.openxmlformats.schemas.drawingml.x2006.main.CTTableCell;
public class TablePics {
public static void main(String[] args) throws Exception {
XMLSlideShow pptx = new XMLSlideShow();
XSLFPictureData pd = pptx.addPicture(new File("wrench.emf"), PictureType.EMF);
XSLFSlide slide = pptx.createSlide();
XSLFTable table = slide.createTable();
table.setAnchor(new Rectangle2D.Double(50, 50, 500, 20));
XSLFTableRow row = table.addRow();
row.addCell().setText("Cell 1");
XSLFTableCell cell = row.addCell();
cell.setText("Cell 2");
CTBlipFillProperties blipPr = ((CTTableCell)cell.getXmlObject()).getTcPr().addNewBlipFill();
blipPr.setDpi(72);
// http://officeopenxml.com/drwPic-ImageData.php
CTBlip blib = blipPr.addNewBlip();
blipPr.addNewSrcRect();
CTRelativeRect fillRect = blipPr.addNewStretch().addNewFillRect();
fillRect.setL(30000);
fillRect.setR(30000);
RelationPart rp = slide.addRelation(null, XSLFRelation.IMAGES, pd);
blib.setEmbed(rp.getRelationship().getId());
FileOutputStream fos = new FileOutputStream("test2.pptx");
pptx.write(fos);
fos.close();
}
}

Related

How to create two scenes in scalafx

I am new to creating GUI using scalafx. I am trying to create two scenes with the following code but getting some error
import com.sun.glass.ui.Application
import scalafx.event.ActionEvent
import scalafx.event.EventHandler
import scalafx.scene.Scene
import scalafx.scene.control.Button
import scalafx.scene.control.Label
import scalafx.scene.layout.StackPane
import scalafx.scene.layout.VBox
import scalafx.stage.Stage
class example extends Application {
var scene1: Scene = null
var scene2: Scene = null
override def start(primaryStage: Stage): Unit = { primaryStage.setTitle("My First JavaFX GUI")
//Scene 1
val label1 = new Label("This is the first scene")
val button1 = new Button("Go to scene 2"){
onAction = (e: ActionEvent) => {
primaryStage.setScene(scene2)
}
}
val layout1 = new VBox(20)
layout1.getChildren.addAll(label1, button1)
scene1 = new Scene(layout1, 300, 250)
//Scene 2
val label2 = new Label("This is the second scene")
val button2 = new Button("Go to scene 1") {
onAction = (e: ActionEvent) => {
primaryStage.setScene(scene1)
}
}
val layout2 = new VBox(20)
layout2.getChildren.addAll(label2, button2)
scene2 = new Scene(layout2, 300, 250)
primaryStage.setScene(scene1)
primaryStage.show()
}
}
The error is:
found : scalafx.event.ActionEvent => Unit
[error] required: javafx.event.EventHandler[javafx.event.ActionEvent]
[error] onAction = (e: ActionEvent) => {}
How can I declare the action events to switch between the scenes?
It would be really helpful if anyone can help
In ScaleFX, your first troubleshooting is to check if you included the ScaleFX implicit conversion magic:
import scalafx.Includes._
In your case, that will fix the issue with the action handler.
Additionally, you should not use com.sun packages neither in ScalaFX nor in JavaFX code. In ScalaFX you should use JFXApp3 instead. Here is your code corrected to use JFXApp3 with some minor corrections:
import scalafx.Includes._
import scalafx.application.JFXApp3
import scalafx.application.JFXApp3.PrimaryStage
import scalafx.event.{ActionEvent, EventHandler}
import scalafx.scene.Scene
import scalafx.scene.control.{Button, Label}
import scalafx.scene.layout.VBox
import scalafx.stage.Stage
object CreteTwoScenes1App extends JFXApp3 {
var scene1: Scene = _
var scene2: Scene = _
override def start(): Unit = {
stage = new PrimaryStage {
title = "My First JavaFX GUI"
}
// Scene 1
val label1 = new Label("This is the first scene")
val button1 = new Button("Go to scene 2") {
onAction = (e: ActionEvent) => {
stage.setScene(scene2)
}
}
val layout1 = new VBox(20)
layout1.children ++= Seq(label1, button1)
scene1 = new Scene(layout1, 300, 250)
// Scene 2
val label2 = new Label("This is the second scene")
val button2 = new Button("Go to scene 1") {
onAction = (e: ActionEvent) => {
stage.setScene(scene1)
}
}
val layout2 = new VBox(20)
layout2.children ++= Seq(label2, button2)
scene2 = new Scene(layout2, 300, 250)
stage.setScene(scene1)
}
}
You can also rewrite that in more idiomatic ScalaFX builder style. Using Scala 3 can make it much more compact too (no curly braces needed):
import scalafx.Includes.*
import scalafx.application.JFXApp3
import scalafx.scene.Scene
import scalafx.scene.control.{Button, Label}
import scalafx.scene.layout.VBox
object CreteTwoScenes2App extends JFXApp3:
override def start(): Unit =
lazy val scene1: Scene = new Scene(300, 200):
root = new VBox(20):
children = Seq(
new Label("This is the first scene"),
new Button("Go to scene 2"):
onAction = () => stage.setScene(scene2)
)
lazy val scene2: Scene = new Scene(300, 200):
root = new VBox(20):
children = Seq(
new Label("This is the second scene"),
new Button("Go to scene 1"):
onAction = () => stage.setScene(scene2)
)
stage = new JFXApp3.PrimaryStage:
title = "My First JavaFX GUI"
scene = scene1

List as an object field - how to handle it via Stream (Java 8)?

There is a Waybill object that has a Set<Packing> field, the Packing object has a PRICE field.
I get a List<Waybill>.
Need to calculate the total cost of all Packing from the entire List<Waybill>.
How it competently to make through Stream?
Thank you.
class Waybill {
Set<Packing> setOfPacking;
}
class Packing {
int PRICE;
}
List<Waybill> allWaybills = ...
This worked for me:
double total = allWaybills.stream()
.flatMap(waybill -> waybill.setOfPacking.stream())
.mapToInt(packing -> packing.PRICE)
.sum();
I think it is easier to reason about because there aren't any multi-level stream operations.
I would be interested to see how to use flatMapToInt to replace both the flatMap and map operations with one operation without making it multi-level.
Here is a test program:
import java.util.Set;
import java.util.List;
import java.util.HashSet;
import java.util.ArrayList;
import java.util.stream.Collectors;
public class HelloWorld
{
public static class Packing
{
public int PRICE = 0;
}
public static class Waybill
{
public Set<Packing> setOfPacking = new HashSet<Packing>();
}
public static void main(String []args){
List<Waybill> allWaybills = new ArrayList<Waybill>();
Waybill w1 = new Waybill();
Packing p1 = new Packing(); p1.PRICE = 1; w1.setOfPacking.add(p1);
Packing p2 = new Packing(); p2.PRICE = 2; w1.setOfPacking.add(p2);
allWaybills.add(w1);
Waybill w2 = new Waybill();
Packing p3 = new Packing(); p3.PRICE = 3; w2.setOfPacking.add(p3);
Packing p4 = new Packing(); p4.PRICE = 4; w2.setOfPacking.add(p4);
allWaybills.add(w2);
double total = allWaybills.stream()
.flatMap(waybill -> waybill.setOfPacking.stream())
.mapToInt(packing -> packing.PRICE)
.sum();
System.out.println("total = "+total);
}
}
import java.util.stream.*
List<Waybill> allWaybills = ...
int totalCost = allWaybills
.stream()
.mapToInt(w -> w.setOfPacking
.stream()
.mapToInt(p -> p.PRICE)
.sum()
)
.sum();

page X of Y with re-ordered TOC: X will start from 1 again after the TOC

I could create seprately the "page x of y" and re-ordered the TOC with the official examples. "Page x of y" is created according to iText 7: Building Blocks Chapter 7: Handling events; setting viewer preferences and writer properties with the examples Solving the "Page X of Y" problem; and TOC is created with reference to iText 7 examples TOC as first page.
Now I want the generated PDF to have both "page x of y" and re-ordered TOC. And "page x of y" shall be shown on all pages, i.e. on the 1st page (the TOC page), it shall show "Page 1 of 35", the 2nd page (start page of the main text) shall show "Page 2 of 35" (In this Jekyll and Hyde example, TOC has one page).
But when I tried to put "page x of y" and re-order TOC together, I found a problem in the generated PDF: the 1st page (the TOC page) showed correctly "Page 1 of 35", but the 2nd page (start page of the main text) showed also "Page 1 of 35".
What is the tricks to let the 2nd page to show "Page 2 of 35" with re-ordered TOC?
==code for Page X of Y and re-order TOC==
package main;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.AbstractMap.SimpleEntry;
import java.util.ArrayList;
import java.util.List;
import com.itextpdf.io.IOException;
import com.itextpdf.io.font.FontConstants;
import com.itextpdf.kernel.events.Event;
import com.itextpdf.kernel.events.IEventHandler;
import com.itextpdf.kernel.events.PdfDocumentEvent;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfName;
import com.itextpdf.kernel.pdf.PdfOutline;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.PdfString;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.action.PdfAction;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.kernel.pdf.canvas.draw.DottedLine;
import com.itextpdf.kernel.pdf.navigation.PdfDestination;
import com.itextpdf.kernel.pdf.xobject.PdfFormXObject;
import com.itextpdf.layout.Canvas;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.AreaBreak;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Tab;
import com.itextpdf.layout.element.TabStop;
import com.itextpdf.layout.hyphenation.HyphenationConfig;
import com.itextpdf.layout.layout.LayoutContext;
import com.itextpdf.layout.layout.LayoutResult;
import com.itextpdf.layout.property.AreaBreakType;
import com.itextpdf.layout.property.TabAlignment;
import com.itextpdf.layout.property.TextAlignment;
import com.itextpdf.layout.renderer.ParagraphRenderer;
public class CreateTOC {
public static final String SRC = "D:/work/java_workspace/result/jekyll_hyde.txt";
public static final String DEST = "D:/work/java_workspace/result/test_toc.pdf";
public static void main(String args[]) throws IOException, Exception {
File file = new File(DEST);
file.getParentFile().mkdirs();
new CreateTOC().createPdf(DEST);
}
public void createPdf(String dest) throws IOException, java.io.IOException {
PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
pdf.getCatalog().setPageMode(PdfName.UseOutlines);
PageXofY event = new PageXofY(pdf);
pdf.addEventHandler(PdfDocumentEvent.END_PAGE, event);
PdfFont font = PdfFontFactory.createFont(FontConstants.TIMES_ROMAN);
PdfFont bold = PdfFontFactory.createFont(FontConstants.HELVETICA_BOLD);
Document document = new Document(pdf);
document.setTextAlignment(TextAlignment.JUSTIFIED)
.setHyphenation(new HyphenationConfig("en", "uk", 3, 3))
.setFont(font)
.setFontSize(11);
// // add the cover
// document.add(new Paragraph("this is the cover 1"));
// document.add(new AreaBreak(AreaBreakType.NEXT_PAGE));
//
//
// document.add(new Paragraph("this is the cover 2"));
// document.add(new AreaBreak(AreaBreakType.NEXT_PAGE));
// parse text to PDF
BufferedReader br = new BufferedReader(new FileReader(SRC));
String name, line;
Paragraph p;
boolean title = true;
int counter = 0;
PdfOutline outline = null;
List<SimpleEntry<String,SimpleEntry<String, Integer>>> toc = new ArrayList<>();
while ((line = br.readLine()) != null) {
p = new Paragraph(line);
p.setKeepTogether(true);
if (title) {
name = String.format("title%02d", counter++);
outline = createOutline(outline, pdf, line, name);
int pagesWithoutCover = pdf.getNumberOfPages();
SimpleEntry<String, Integer> titlePage = new SimpleEntry(line, pagesWithoutCover);
p.setFont(bold).setFontSize(12)
.setKeepWithNext(true)
.setDestination(name)
.setNextRenderer(new UpdatePageRenderer(p, titlePage));
title = false;
document.add(p);
toc.add(new SimpleEntry(name, titlePage));
}
else {
p.setFirstLineIndent(18);
if (line.isEmpty()) {
p.setMarginBottom(12);
title = true;
}
else {
p.setMarginBottom(0);
}
document.add(p);
}
}
document.add(new AreaBreak(AreaBreakType.NEXT_PAGE));
// create table of contents
int startToc = pdf.getNumberOfPages();
p = new Paragraph().setFont(bold).add("Table of Contents").setDestination("toc");
document.add(p);
toc.remove(0);
List<TabStop> tabstops = new ArrayList();
tabstops.add(new TabStop(580, TabAlignment.RIGHT, new DottedLine()));
for (SimpleEntry<String, SimpleEntry<String, Integer>> entry : toc) {
SimpleEntry<String, Integer> text = entry.getValue();
p = new Paragraph()
.addTabStops(tabstops)
.add(text.getKey())
// .setFixedLeading(150)
.add(new Tab())
.add(String.valueOf(text.getValue()))
.setAction(PdfAction.createGoTo(entry.getKey()));
document.add(p);
}
int tocPages = pdf.getNumberOfPages() - startToc;
// reorder pages
PdfPage page;
for (int i = 0; i <= tocPages; i++) {
page = pdf.removePage(startToc + i);
pdf.addPage(i + 1, page);
}
event.writeTotal(pdf);
document.close();
}
protected class UpdatePageRenderer extends ParagraphRenderer {
protected SimpleEntry<String, Integer> entry;
public UpdatePageRenderer(Paragraph modelElement, SimpleEntry<String, Integer> entry) {
super(modelElement);
this.entry = entry;
}
#Override
public LayoutResult layout(LayoutContext layoutContext) {
LayoutResult result = super.layout(layoutContext);
entry.setValue(layoutContext.getArea().getPageNumber());
return result;
}
}
public PdfOutline createOutline(PdfOutline outline, PdfDocument pdf, String title, String name) {
if (outline == null) {
outline = pdf.getOutlines(false);
outline = outline.addOutline(title);
outline.addDestination(PdfDestination.makeDestination(new PdfString(name)));
return outline;
}
PdfOutline kid = outline.addOutline(title);
kid.addDestination(PdfDestination.makeDestination(new PdfString(name)));
return outline;
}
protected class PageXofY implements IEventHandler {
protected PdfFormXObject placeholder;
protected float side = 20;
protected float x = 300;
protected float y = 25;
protected float space = 4.5f;
protected float descent = 3;
public PageXofY(PdfDocument pdf) {
placeholder = new PdfFormXObject(new Rectangle(0, 0, side, side));
}
#Override
public void handleEvent(Event event) {
PdfDocumentEvent docEvent = (PdfDocumentEvent) event;
PdfDocument pdf = docEvent.getDocument();
PdfPage page = docEvent.getPage();
int pageNumber = pdf.getPageNumber(page);
Rectangle pageSize = page.getPageSize();
PdfCanvas pdfCanvas = new PdfCanvas(
page.newContentStreamBefore(), page.getResources(), pdf);
Canvas canvas = new Canvas(pdfCanvas, pdf, pageSize);
Paragraph p = new Paragraph().add("Page ").add(String.valueOf(pageNumber)).add(" of");
canvas.showTextAligned(p, x, y, TextAlignment.RIGHT);
pdfCanvas.addXObject(placeholder, x + space, y - descent);
pdfCanvas.release();
}
public void writeTotal(PdfDocument pdf) {
Canvas canvas = new Canvas(placeholder, pdf);
canvas.showTextAligned(String.valueOf(pdf.getNumberOfPages()),
0, descent, TextAlignment.LEFT);
}
}
}
In general
You will obviously run into trouble if you first create pages including a "page x/y" using the current page number of each page and then re-order the pages.
If you know beforehand how many pages you will move up front, you can take this re-ordering into account by adding this number as offset to the page number in your event listener. Be sure to reset that offset when you start creating the TOC pages.
If you don't know that number, it does not make sense to try to number the pages before re-ordering at all. Instead add page numbers afterwards as described in the iText 7: Building Blocks Chapter 2: Working with the RootElement example Adding a Page X of Y footer, i.e. loop over every page in the document and add a "Page X of Y" Paragraph to each page:
int n = pdf.getNumberOfPages();
Paragraph footer;
for (int page = 1; page <= n; page++) {
footer = new Paragraph(String.format("Page %s of %s", page, n));
document.showTextAligned(footer, 297.5f, 20, page,
TextAlignment.CENTER, VerticalAlignment.MIDDLE, 0);
}
document.close();
Don't forget to set immediateFlush to false as described right after that example.
Using an offset
In a comment you indicated that you did not want to use the solution from chapter 2 referenced above as you didn't want to keep the whole PDF in memory. Then you posted your code.
Thus, let's try and implement the offset mentioned above in your code.
The offset variable is best located right in the event listener. Having added it, it might looks like this:
protected class PageXofY implements IEventHandler
{
// vvv added
int offset = 0;
// ^^^ added
protected PdfFormXObject placeholder;
protected float side = 20;
protected float x = 300;
protected float y = 25;
protected float space = 4.5f;
protected float descent = 3;
public PageXofY(PdfDocument pdf)
{
placeholder = new PdfFormXObject(new Rectangle(0, 0, side, side));
}
#Override
public void handleEvent(Event event)
{
PdfDocumentEvent docEvent = (PdfDocumentEvent) event;
PdfDocument pdf = docEvent.getDocument();
PdfPage page = docEvent.getPage();
int pageNumber = pdf.getPageNumber(page);
Rectangle pageSize = page.getPageSize();
PdfCanvas pdfCanvas = new PdfCanvas(
page.newContentStreamBefore(), page.getResources(), pdf);
Canvas canvas = new Canvas(pdfCanvas, pdf, pageSize);
// vvv changed
Paragraph p = new Paragraph().add("Page ").add(String.valueOf(pageNumber + offset)).add(" of");
// ^^^ changed
canvas.showTextAligned(p, x, y, TextAlignment.RIGHT);
pdfCanvas.addXObject(placeholder, x + space, y - descent);
pdfCanvas.release();
}
public void writeTotal(PdfDocument pdf)
{
Canvas canvas = new Canvas(placeholder, pdf);
canvas.showTextAligned(String.valueOf(pdf.getNumberOfPages()),
0, descent, TextAlignment.LEFT);
}
}
(PageXofY)
(You might want to add getters and setters for the offset.)
When importing the text body your page numbers currently are created off-by-one as the TOC page will later be pulled up to the front. Thus, you need to use an offset of 1 (1 page TOC) during that import.
Afterwards, before starting the TOC page, you will have to reset the offset to 0 as nothing will be pulled before the TOC page thereafter.
Id est:
public void createPdf(Reader reader, String dest) throws IOException
{
[...]
Document document = new Document(pdf);
document.setTextAlignment(TextAlignment.JUSTIFIED)
.setHyphenation(new HyphenationConfig("en", "uk", 3, 3))
.setFont(font)
.setFontSize(11);
// vvv added
event.offset = 1;
// ^^^ added
// // add the cover
[...]
document.add(new AreaBreak(AreaBreakType.NEXT_PAGE));
// vvv added
event.offset = 0;
// ^^^ added
// create table of contents
int startToc = pdf.getNumberOfPages();
[...]
}
(CreateTOC method createPdf)
In the current iText 7 development 7.0.3-SNAPSHOT version this results in desired page numbering.
Beware: There had been reports on delayed page event execution. Probably the event timing meanwhile has been changed. With older versions, therefore, the code might still apply wrong page numbers.

How to save a file as rdf in Protege 4.3?

I have made an ontology on Protege. it has . owl extension. I am trying to import this ontology in oracle 12c using jena. but model. Read method requires an rdf file. I am giving the code as well as error. Kindly help me in this case.
error
Exception in thread "main" com.hp.hpl.jena.shared.JenaException: java.lang.UnsatisfiedLinkError: no ocijdbc11 in java.library.path
at oracle.spatial.rdf.client.jena.Oracle.<init>(Oracle.java:207)
at test.TestClass.main(TestClass.java:26)
code package test;
import java.io.InputStream;
import com.hp.hpl.jena.rdf.model.*;
import oracle.spatial.rdf.client.jena.GraphOracleSem;
import oracle.spatial.rdf.client.jena.ModelOracleSem;
import oracle.spatial.rdf.client.jena.Oracle;
import oracle.spatial.rdf.client.jena.OracleUtils;
import com.hp.hpl.jena.graph.GraphUtil;
import com.hp.hpl.jena.graph.Triple;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.util.FileManager;
public class TestJena{
public static void main(String[] args) throws Exception
{
//String szJdbcURL = args[0];
//String szUser = args[1];
//String szPasswd = args[2];
//String szModelName = args[3];
// in memory Jena Model
Model model = ModelFactory.createDefaultModel();
InputStream is = FileManager.get().open("E:/abcd.owl");
model.read(is, "", "RDF/XML");
is.close();
Oracle oracle = new Oracle("jdbc:oracle:oci8:#", "c##hr_admin","Hira123");
ModelOracleSem modelDest = ModelOracleSem.createOracleSemModel(oracle,"M1");
GraphOracleSem g = modelDest.getGraph();
g.dropApplicationTableIndex();
int method = 2; // try bulk loader
String tbs = "SYSAUX"; // can be customized
if (method == 0) {
System.out.println("start incremental");
modelDest.add(model);
System.out.println("end size " + modelDest.size());
}
else if (method == 1) {
System.out.println("start batch load");
g.getBulkUpdateHandler().addInBatch(
GraphUtil.findAll(model.getGraph()), tbs);
System.out.println("end size " + modelDest.size());
}
else {
System.out.println("start bulk load");
g.getBulkUpdateHandler().addInBulk(
GraphUtil.findAll(model.getGraph()), tbs);
System.out.println("end size " + modelDest.size());
}
g.rebuildApplicationTableIndex();
long lCount = g.getCount(Triple.ANY);
System.out.println("Asserted triples count: " + lCount);
model.close();
OracleUtils.dropSemanticModel(oracle, "M1");
oracle.dispose();
}
}
You can rename the file to RDF: under the assumption that the format you used for the ontology is RDF/XML (the default), all that is needed is changing the file extension.
Regarding the error you post, you are missing a binary library. You need to set java.library.path to point at the folder containing the library mentioned in the error.
See for example how to set java library path for processing for how to do this.

XPATH better way to parse xml

What is the better way to parse such xml:
<FindLicensesResponse xmlns="http://abc.com">
<FindLicensesResult>
<Licensies>
<ActivityLicense>
<id>1</id>
<DateIssue>2011-12-29T00:00:00</DateIssue>
<ActivityType xmlns:s01="http://www.w3.org/2001/XMLSchema-instance" s01:type="ActivityType">
<code>somecode1</code>
</ActivityType>
<ActivityTerritory xmlns:s02="http://www.w3.org/2001/XMLSchema-instance" s02:type="Territory">
<code>somecode2</code>
</ActivityTerritory>
<ActivityLicenseAttachments />
</ActivityLicense>
<ActivityLicense>
<id>2</id>
<DateIssue>2011-12-21T00:00:00</DateIssue>
<ActivityType xmlns:s01="http://www.w3.org/2001/XMLSchema-instance" s01:type="ActivityType">
<code>somecode3</code>
</ActivityType>
<ActivityTerritory xmlns:s02="http://www.w3.org/2001/XMLSchema-instance" s02:type="Territory">
<code>somecode4</code>
</ActivityTerritory>
<ActivityLicenseAttachments />
</ActivityLicense>
</Licensies>
</FindLicensesResult>
I need to get values from each ActivityLicense: id, DateIssue and inner ActivityType: code and inner ActivityTerritory: code.
Now I do it like this:
CachedXPathAPI xpathAPI = new CachedXPathAPI();
Element nsctx = result.getSOAPPart().createElementNS(null, "nsctx");
nsctx.setAttributeNS("http://www.w3.org/2000/xmlns/","xmlns:el","http://abc.com");
NodeList activityLicenses = xpathAPI.selectNodeList(result.getSOAPPart(),"//el:ActivityLicense", nsctx);
for (int i = 0; i < activityLicenses.getLength(); i++) {
Node id = xpathAPI.selectSingleNode(activityLicenses.item(i), "//el:id", nsctx);
Node dateIssue = xpathAPI.selectSingleNode(activityLicenses.item(i), "//el:DateIssue",nsctx);
System.out.println("id: " + id.getTextContent());
System.out.println("dateIssue: " + dateIssue.getTextContent());
}
But I can't get values from ActivityType/code and ActivityTerritory/code
check out this solution
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
public class StringTest {
public static void main(String[] args) throws Exception {
String xml = "";
java.util.Scanner sc = new java.util.Scanner(new File("xml.xml"));
while(sc.hasNextLine()){
xml+=sc.nextLine();
}
javax.xml.parsers.DocumentBuilderFactory dbFactory = javax.xml.parsers.DocumentBuilderFactory.newInstance();
javax.xml.parsers.DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
InputStream is = new ByteArrayInputStream(xml.getBytes());
org.w3c.dom.Document doc = dBuilder.parse(is);
doc.getDocumentElement().normalize();
XPath xpath = XPathFactory.newInstance().newXPath();
org.w3c.dom.NodeList nodeList = doc.getElementsByTagName("ActivityLicense");
for(int i=0;i<nodeList.getLength();i++){
org.w3c.dom.Node node = nodeList.item(i);
System.out.println(xpath.evaluate("ActivityTerritory/code/text()", node, XPathConstants.STRING));
}
}
}

Resources