기은P
시간이 멈추는 장소
기은P
  • Programming (272)
    • 개발노트 (1)
    • FrontEnd (56)
      • ES&JS 문법 (14)
      • HTML&CSS (4)
      • React 기본 (18)
      • React 심화 (12)
      • React 이슈 (2)
      • Project 연습 (1)
      • Next.js (5)
    • Backend&Devops (33)
      • AWS (2)
      • Docker (9)
      • Jenkins (6)
      • Nginx (6)
      • Node.js (1)
      • ElasticSearch (5)
      • 프레임워크&아키텍처 (2)
      • 암호화 (0)
      • 기타 (2)
    • 알고리즘 (3)
    • C# (8)
      • WPF (8)
    • Java (51)
      • 순수 Java (18)
      • RDF&Jena (12)
      • RCP&GEF (9)
      • JMX (5)
      • JMapper (3)
      • 오류해결 (4)
    • Database (21)
      • RDBMS (9)
      • NoSQL (2)
      • TSDB (1)
      • GraphQL (1)
      • Hibernate (3)
      • 데이터베이스 이론 (4)
      • Redis (1)
    • 프로토콜 (11)
      • Netty (4)
      • gRPC (5)
      • 프로토콜 개념 (2)
    • Server (4)
      • Linux (4)
    • 2020 정보처리기사 필기 (43)
      • 목차 (1)
      • 기출문제 (1)
      • 1과목 - 소프트웨어 설계 (6)
      • 2과목 - 소프트웨어 개발 (7)
      • 3과목 - 데이터베이스 구축 (8)
      • 4과목 - 프로그래밍 언어 활용 (7)
      • 5과목 - 정보시스템 구축 관리 (10)
    • 2020 정보처리기사 실기 (31)
      • 목차 (4)
      • 기출예상문제 (19)
      • 실기요약 (8)
    • 빅데이터분석기사 필기 (4)
      • 목차 (0)
      • 필기 요약 (3)
    • 전기 공학 (1)
      • CIM (1)
    • 산업자동화시스템 (3)
      • SCADA (1)
      • OPC UA (2)
    • 디자인패턴 (1)
    • 휴지통 (0)

공지사항

  • 공지사항/포스팅 예정 항목

최근 댓글

최근 글

전체 방문자
오늘
어제

티스토리

hELLO · Designed By 정상우.
기은P

시간이 멈추는 장소

Java/RDF&Jena

RDF - Eclipse Apache Jena 다운로드 및 사용법

2020. 3. 4. 17:37
반응형

- 시맨틱 웹에서 사용되는 RDF를 이클립스에서 사용할 수 있는 Apache Jena API가 있다.

아파치 제나(Apache Jena)는 Java용 오픈 소스 시맨틱 웹 프레임워크로, RDF 그래프에서 데이터를 추출하거나 기록하는 API를 제공한다. 그래프는 추상적인 모델로 표현되는 데, 파일, 데이터베이스, URL, 또는 이들의 조합에서 데이터를 공급 받는다. 모델은 SPARQL 1.1을 통해 질의할 수 있다.

Jena는 Sesame와 유사하지만, 이와는 달리, OWL (Web Ontology Language)를 지원한다. Jena 프레임워크는 다양한 내부 추론기와 펠릿(Pellet) 추론기(오픈 소스 Java OWL-DL 추론기)를 설정하여 작업할 수 있다.

Jena는 다음과 같은 RDF 그래프의 직렬화를 지원한다:

  • 관계형 데이터베이스
  • RDF/XML
  • Turtle
  • Notation 3

- API를 제공하는 Jena의 홈페이지 주소 :: https://jena.apache.org/

 

Apache Jena -

Triple store Persist your data using TDB, a native high performance triple store. TDB supports the full range of Jena APIs. Expose your triples as a SPARQL end-point accessible over HTTP. Fuseki provides REST-style interaction with your RDF data.

jena.apache.org

- 먼저 위 라이브러리를 이클립스에 다운받기 위해선 절차가 필요한데, 아래 pdf 파일을 참고하길 바란다.

 

Jena_Install_Guide.pdf
3.34MB

- RDF 형태로 output이 나오도록 하는 코드를 약 5개 정도 샘플로 준비해보았다.

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;

import com.hp.hpl.jena.datatypes.xsd.XSDDatatype;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.RDFNode;
import com.hp.hpl.jena.rdf.model.ResIterator;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.rdf.model.Statement;
import com.hp.hpl.jena.rdf.model.StmtIterator;
import com.hp.hpl.jena.vocabulary.VCARD;

public class Main {
	static String personURI = "http://somewhere/JohnSmith";
	static String fullName = "John Smith";

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		new Main().func1();
	}

	private void func1() {
		Model model = ModelFactory.createDefaultModel();
		String ns = "http://example.com/test/";

		Resource r = model.createResource(ns + "r");
		Property p = model.createProperty(ns + "p");

		r.addProperty(p, "hello world", XSDDatatype.XSDstring);

		model.write(System.out, "Turtle");

	}
}

 

 

private void func2() {
		// some definitions
		String personURI = "http://somewhere/JohnSmith";
		String fullName = "John Smith";

		// create an empty Model
		Model model = ModelFactory.createDefaultModel();

		// create the resource
		Resource johnSmith = model.createResource(personURI);

		// add the property
		johnSmith.addProperty(VCARD.FN, fullName); // vocabulary
		Print(model);

	}

 

	private void func3() {
		// some definitions
		String personURI = "http://somewhere/JohnSmith";
		String givenName = "John";
		String familyName = "Smith";
		String fullName = givenName + " " + familyName;

		// create an empty Model
		Model model = ModelFactory.createDefaultModel();

		// create the resource
		// and add the properties cascading style
		Resource johnSmith = model.createResource(personURI).addProperty(VCARD.FN, fullName).addProperty(VCARD.N,
				model.createResource().addProperty(VCARD.Given, givenName).addProperty(VCARD.Family, familyName));
		model.write(System.out, "RDF/XML");
	}

 

private void func4() {
		// create an empty Model
		Model model = ModelFactory.createDefaultModel();

		// create the resource
		Resource johnSmith = model.createResource(personURI);

		// add the property
		johnSmith.addProperty(VCARD.FN, fullName);

		model.write(System.out, "RDF/XML");
	}

 

	private void func5() {
		Model m = ModelFactory.createDefaultModel();
		String nsA = "http://somewhere/else#";
		String nsB = "http://nowhere/else#";
		Resource root = m.createResource(nsA + "root");
		Property P = m.createProperty(nsA + "P");
		Property Q = m.createProperty(nsB + "Q");
		Resource x = m.createResource(nsA + "x");
		Resource y = m.createResource(nsA + "y");
		Resource z = m.createResource(nsA + "z");
		m.add(root, P, x).add(root, P, y).add(y, Q, z);
		System.out.println("# -- no special prefixes defined");
		m.write(System.out);
		System.out.println("# -- nsA defined");
		m.setNsPrefix("nsA", nsA);
		m.write(System.out);
		System.out.println("# -- nsA and cat defined");
		m.setNsPrefix("cat", nsB);
		m.write(System.out);

		// Iterator 선언
		StmtIterator iter = m.listStatements();
	}

 

	private void Print(Model model) {
		// list the statements in the Model
		StmtIterator iter = model.listStatements();

		// print out the predicate, subject and object of each statement
		while (iter.hasNext()) {
			Statement stmt = iter.nextStatement(); // get next statement
			Resource subject = stmt.getSubject(); // get the subject
			Property predicate = stmt.getPredicate(); // get the predicate
			RDFNode object = stmt.getObject(); // get the object

			System.out.print(subject.toString());
			System.out.print(" " + predicate.toString() + " ");
			if (object instanceof Resource) {
				System.out.print(object.toString());
			} else {
				// object is a literal
				System.out.print(" \"" + object.toString() + "\"");
			}

			System.out.println(" .");
		}

	}

 


 * Model model = ModelFactory.createDefaultModel();

 => RDF형태의 근간이 되는 객체다. 이 객체 위에 Resource를 담고 Property를 담아 Jena에서 지원하는 write()함수로 RDF 파일이 생성된다.

 * Resource, Property, Object = 주어, 서술어, 목적어 라고 생각하면 된다.

 * 기본적으로 RDF는 Iterator를 통해 조회가 된다.

 * model를 출력할 때의 setup이 다양하다. 상황에 맞게 이용하면 된다.

 

model.write(System.out, "RDF/XML-ABBREV"); 
model.write(System.out, "N3"); 
model.write(System.out, "RDF/XML"); // rdf Description과 태그 내용이 출력 
model.write(System.out, "N-TRIPLES"); // 태그 내용 없이 결과 값만 출력 
model.write(System.out, "N-QUADS"); // 출력 안됨 
model.write(System.out, "TriG"); // 출력 안됨 
model.write(System.out, "TTL"); // N3와 결과 동일. 태그 내용 없이 태그 밑의 하위 요소 별로 출력 
model.write(System.out, "SSE"); // 출력 안됨

 

[ 메서드(인자) : Return 값 ]

* model.getResource(uri : String) : Resource

 => URI가 uri인 resource를 리턴하거나, 존재하지 않을 경우엔 새로 생성하여 리턴한다.

* resource.getProperty(p : Property) : Statement

 => resource가 속성 p를 가지면 Statement를 리턴하고, 속성 p를 갖지 않으면 null을 리턴한다.

* statement.getObject() : RDFNode

 => statement의 object node를 리턴

* statement.getResource() : Resouce

 => statement의 object가 Resource면 Resource를 리턴 아니면 Exception

* statement.getString() : String

 => statement의 object가 Literal이면 그것을 리턴, 아니면 Exception

* resource.listProperties(p : Property) : StmtIterator

 => getProperty(p)는 딱 한개의 Statement를 리턴하는 반면에, 이 함수는 해당되는 속성(Property)의 모든 Statement를 리턴한다.

 

반응형

'Java > RDF&Jena' 카테고리의 다른 글

Jena SPARQL 사용 방법 및 소스 코드  (0) 2020.03.20
Jena SDB 사용 예제  (0) 2020.03.20
RDF - Jena 예제 및 주로 사용하는 함수 정리  (0) 2020.03.12
RDF - Eclipse Apache Jena Xml 파일 읽어오기  (0) 2020.03.10
RDF(Resource Description Framework)란  (0) 2020.03.04
    'Java/RDF&Jena' 카테고리의 다른 글
    • Jena SDB 사용 예제
    • RDF - Jena 예제 및 주로 사용하는 함수 정리
    • RDF - Eclipse Apache Jena Xml 파일 읽어오기
    • RDF(Resource Description Framework)란
    기은P
    기은P
    기은P의 블로그 일상과 개발 관련 포스팅 #React #Typescript #Next #Nest https://github.com/kimdongjang

    티스토리툴바