I created my ontology by Protege. my ontology has some classes and instances. Now i'm going to add other classes and instances by jena that's why i write the below code to create a new class and one instance in this class. the name of new class is "person" and the name of new instance is "base". when i run this code in java it works without any error and create the class and instance. but when i back to protege i can not see the new class and also the new instance. do you have any idea to help me.
thanks
public void create_model(){
modelMem = ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM);
ModelMaker modelMaker = ModelFactory.createFileModelMaker("Ontologies/VBnet.owl");
Model modeltmp = modelMaker.createDefaultModel();
modelMem = ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM, modeltmp);
System.out.println("Model has been Successfully Built");
}
public void addFile() {
System.out.println("Loading from FOAF instance File");
InputStream inFoafInstance =FileManager.get().open("Ontologies/VBnet.owl");
modelMem.read(inFoafInstance, defaultNameSpace);
//inFoafInstance.close();
System.out.println(modelMem.toString());
}
public void adddata() {
OntClass person = modelMem.createClass(defaultNameSpace + "Person");
Individual l1 = modelMem.createIndividual( defaultNameSpace + "base", person );
for (Iterator i = l1.listRDFTypes(true); i.hasNext(); )
System.out.println( l1.getURI() + " is asserted in class " + i.next() );
}
public static void main(String[] args) {
AddInfo add=new AddInfo();
add.create_model();
add.addFile();
add.adddata();
}
You don't seem to have saved the altered model:
OutputStream out = new FileOutputStream("altered.rdf");
modelMem.write( out, "RDF/XML-ABBREV"); // readable rdf/xml
out.close();
Related
I'm trying to make a simple graph using java but keep getting error
Code:
public class PlantUMLDemoMain {
public static void main(String[] args) throws Exception {
generateFromStringSource(new File("from-string.png"));
generateFromApi(new File("from-api.png"));
}
private static void generateFromApi(File file) throws IOException {
// 1. setup:
SequenceDiagramFactory f = new SequenceDiagramFactory();
SequenceDiagram diagram = f.createEmptyDiagram();
// 2. Build the diagram:
// "Bob -> Alice : hello"
// See net.sourceforge.plantuml.sequencediagram.command.CommandArrow#executeArg
Display bobD = Display.getWithNewlines("Bob");
Participant bobP = diagram.getOrCreateParticipant("Bob", bobD);
Display aliceD = Display.getWithNewlines("Alice");
Participant aliceP = diagram.getOrCreateParticipant("Alice", aliceD);
Display label = Display.getWithNewlines("hello");
ArrowConfiguration config = ArrowConfiguration.withDirectionNormal();
Message msg = new Message(bobP, aliceP, label, config, diagram.getNextMessageNumber());
checkState(null == diagram.addMessage(msg));
// 3. Output the diagram
// See net.sourceforge.plantuml.SourceStringReader#generateImage
diagram.makeDiagramReady();
checkState(1 == diagram.getNbImages());
try (OutputStream os = new FileOutputStream(file)) {
ImageData imageData = diagram.exportDiagram(os, 0, new FileFormatOption(FileFormat.PNG));
System.out.println("generateFromApi: " + diagram.getDescription().getDescription());
}
}
private static void generateFromStringSource(File file) throws IOException {
String source = "#startuml\n";
source += "Bob -> Alice : hello\n";
source += "#enduml\n";
StringBuffer stringBuffer = new StringBuffer();
SourceStringReader reader = new SourceStringReader(source);
// Write the first image to "png"
String desc = reader.generateImage(file);
// Return a null string if no generation
System.out.println("generateFromStringSource: " + desc);
}
}
Error: Exception in thread "main" java.lang.IllegalAccessError: class net.sourceforge.plantuml.png.PngIOMetadata (in unnamed module #0x9597028) cannot access class com.sun.imageio.plugins.png.PNGMetadata (in module java.desktop) because module java.desktop does not export com.sun.imageio.plugins.png to unnamed module #0x9597028
at net.sourceforge.plantuml.png.PngIOMetadata.writeWithMetadata(PngIOMetadata.java:60)
at net.sourceforge.plantuml.png.PngIO.write(PngIO.java:86)
at net.sourceforge.plantuml.png.PngIO.write(PngIO.java:80)
at net.sourceforge.plantuml.ugraphic.g2d.UGraphicG2d.writeImageTOBEMOVED(UGraphicG2d.java:219)
at net.sourceforge.plantuml.ugraphic.ImageBuilder.writeImageInternal(ImageBuilder.java:249)
at net.sourceforge.plantuml.ugraphic.ImageBuilder.writeImageTOBEMOVED(ImageBuilder.java:171)
at net.sourceforge.plantuml.sequencediagram.graphic.SequenceDiagramFileMakerPuma2.createOne(SequenceDiagramFileMakerPuma2.java:234)
at net.sourceforge.plantuml.sequencediagram.SequenceDiagram.exportDiagramInternal(SequenceDiagram.java:222)
at net.sourceforge.plantuml.UmlDiagram.exportDiagramNow(UmlDiagram.java:236)
at net.sourceforge.plantuml.AbstractPSystem.exportDiagram(AbstractPSystem.java:127)
at net.sourceforge.plantuml.SourceStringReader.generateImage(SourceStringReader.java:124)
at net.sourceforge.plantuml.SourceStringReader.generateImage(SourceStringReader.java:111)
at net.sourceforge.plantuml.SourceStringReader.generateImage(SourceStringReader.java:101)
at scr.graphviz.sk.PlantUMLDemoMain.generateFromStringSource(PlantUMLDemoMain.java:66)
at scr.graphviz.sk.PlantUMLDemoMain.main(PlantUMLDemoMain.java:23)
I found someone with similar problem and older version of plantuml worked for him. I have jar file of the older version but I'm not sure how to apply it. I tried inspecting the file and find out versions of libraries used and added maven dependencies for them but it didnt seem to work.
This is similar problem i mentioned https://github.com/plantuml/plantuml/issues/69
Here are the two java classes:
package je3.io;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
/**
* Created by IDEA on 31/01/15.
*/
public class DirWalker {
private List<File> recursiveList = new ArrayList<File>();
public void walkDir(String pathname) {
File d = new File(pathname);
recursiveList.add(d);
if(d.isDirectory()) {
for(String f : d.list()) {
walkDir(f);
}
}
}
public void reset() {
recursiveList.clear();
}
public List<File> getRecursiveList() {
return recursiveList;
}
public static void main(String[] args) {
DirWalker dirWalker = new DirWalker();
dirWalker.walkDir("/tmp");
dirWalker.getRecursiveList().forEach(System.out::println);
}
}
package je3.io;
import java.io.File;
/**
* Created by IDEA on 31/01/15.
*/
public class DirSummariser {
private DirWalker dirWalker = new DirWalker();
private long dirSize = 0;
public DirSummariser(String pathname) {
dirWalker.reset();
dirWalker.walkDir(pathname);
}
public DirSummariser(File file) {
this(file.getAbsolutePath());
}
public long calculateDirSize() {
for(File f : dirWalker.getRecursiveList()) {
dirSize += f.length();
}
return dirSize;
}
public static void main(String[] args) {
DirSummariser dirSummariser = new DirSummariser("/Users/hualin/Downloads/pdf");
System.out.println(dirSummariser.calculateDirSize());
}
}
In the main method of the second class, I was trying to calculate the total size of the pdf folder, which should be around 30MB. The java program compiles without error, but says the size of the folder is only 1600 bytes.
The problem is in DirWalker:
public void walkDir(String pathname) {
File d = new File(pathname);
recursiveList.add(d);
if(d.isDirectory()) {
for(String f : d.list()) { // <-- here
walkDir(f); // <--
}
}
}
The strings returned by d.list() are just the file names, without a path attached to them. If you find, for example, a file some_directory/foo.txt, the string you'll pull out of the list is foo.txt, and since foo.txt is not in the current working directory, the File object you construct from it will be invalid (or describe a different file).
You'll have to make the path you're trying to inspect part of the recursion to make this work properly, for example like this:
walkDir(pathname + File.separator + f);
Or, as #Adam mentions in the comments, by passing the File object that describes the parent directory into the recursion and using the File(parent, child) constructor, as in
// new parameter here: parent directory
public void walkDir(String pathname, File parent) {
System.out.println(pathname);
File d = new File(parent, pathname); // <-- File constructor with parent
recursiveList.add(d);
if(d.isDirectory()) {
for(String f : d.list()) {
walkDir(f, d); // passing parent here
}
}
}
// entry point, to keep old interface.
public void walkDir(String pathname) {
walkDir(pathname, null);
}
Note: This answer, I think this should be mentioned, is rather tailored to OP's use case of an exercise, so I mainly tried to explain why his code didn't work and suggested ways to make it work. If you're a stray visitor in the future and looking for ways to walk through a directory with Java, look at #fge's answer for a better way.
Use the java.nio.file API, it's much better at doing things like this.
Here is an example, also using throwing-lambdas, calculating the total size of all files in a directory, recursively:
final Path theDirectory = Paths.get("path/to/your/directory");
final long totalSize = Files.walk(theDirectory)
.filter(Files::isRegularFile)
.mapToLong(Functions.rethrow(Files::size))
.sum();
If you don't have Java 8, use Files.walkFileTree().
Frankly, I do not know even it is possible or not.
But what I am trying to do is just like below.
I made a class file from ClassFile.java via javac command in terminal.
Then I want to get an instance from .java file or .class file.
Next, I made another project in eclipse, As you guess this project path and upper file path are completely different. For instance, ClassFile.java/class file can be located in '~/Downloads' folder, the other hand, new eclipse project can be in '~/workspace/'.
So I read file which referred in step 1 by FileInputStream.
From here, I just paste my code.
public class Main {
private static final String CLASS_FILE_PATH =
"/Users/juneyoungoh/Downloads/ClassFile.class";
private static final String JAVA_FILE_PATH =
"/Users/juneyoungoh/Downloads/ClassFile.java";
private static Class getClassFromFile(File classFile) throws Exception {
System.out.println("get class from file : [" + classFile.getCanonicalPath() + " ]");
Object primativeClz = new Object();
ObjectInputStream ois = null;
ois = new ObjectInputStream(new FileInputStream(classFile));
primativeClz = ois.readObject();
ois.close();
return primativeClz.getClass();
}
public static void main(String[] args) throws Exception {
getClassInfo(getClassFromFile(new File(CLASS_FILE_PATH)));
}
}
just like your assumption, this code has errors.
For example, it shows :
java.io.StreamCurruptedException: invalid stream header : CAFEBABE
this there any way to get object instance from .class file or .java file?
P.S.
I wish do not use extra libraries.
private static final String CLASS_FOLDER =
"/Users/juneyoungoh/Downloads/";
private static Class getClassFromFile(String fullClassName) throws Exception {
URLClassLoader loader = new URLClassLoader(new URL[] {
new URL("file://" + CLASS_FOLDER)
});
return loader.loadClass(fullClassName);
}
public static void main( String[] args ) throws Exception {
System.out.println((getClassFromFile("ClassFile"));
}
There's a bug in the Guice grapher utility that causes most or all graphs to render corrupted. Is there a workaround or fix for this?
I modified #wuppi's answer slightly to also hide class paths and long random name annotations to make the graph much more compact and readable. His answer with edited code follows:
I find this utility method pretty useful and it never pritned incorrect graphs for me.
Regarding the style=invis bug: The Guice grapher plugin generates a dot file, which styles some of the clases as invisible. The replaceAll() in the below posted method works around that. The rest of the code is nearly the same from the Guice example.
I've incorporated Scot's fix for Guice 4.x, which included Tim's answer as well:
public class Grapher {
public static void main(String[] args) throws Exception {
Grapher.graph4("filename.dot", Guice.createInjector(new MyModule()));
}
public static void graph4(String filename, Injector inj) throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintWriter out = new PrintWriter(baos);
Injector injector = Guice.createInjector(new GraphvizModule());
GraphvizGrapher renderer = injector.getInstance(GraphvizGrapher.class);
renderer.setOut(out);
renderer.setRankdir("TB");
renderer.graph(inj);
out = new PrintWriter(new File(filename), "UTF-8");
String s = baos.toString("UTF-8");
s = fixGrapherBug(s);
s = hideClassPaths(s);
out.write(s);
out.close();
}
public static String hideClassPaths(String s) {
s = s.replaceAll("\\w[a-z\\d_\\.]+\\.([A-Z][A-Za-z\\d_\\$]*)", "$1");
s = s.replaceAll("value=[\\w-]+", "random");
return s;
}
public static String fixGrapherBug(String s) {
s = s.replaceAll("style=invis", "style=solid");
s = s.replaceAll("margin=(\\S+), ", " margin=\"$1\", ");
return s;
}
}
Of course you are free to generate any other Filename :)
Guice 4.x example incorporating Jeff and Tim's solutions:
public class Grapher {
public static void main(String[] args) throws Exception {
Grapher.graph4("filename.dot", Guice.createInjector(new MyModule()));
}
public static void graph4(String filename, Injector inj) throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintWriter out = new PrintWriter(baos);
Injector injector = Guice.createInjector(new GraphvizModule());
GraphvizGrapher renderer = injector.getInstance(GraphvizGrapher.class);
renderer.setOut(out);
renderer.setRankdir("TB");
renderer.graph(inj);
out = new PrintWriter(new File(filename), "UTF-8");
String s = baos.toString("UTF-8");
s = fixGrapherBug(s);
s = hideClassPaths(s);
out.write(s);
out.close();
}
public static String hideClassPaths(String s) {
s = s.replaceAll("\\w[a-z\\d_\\.]+\\.([A-Z][A-Za-z\\d_]*)", "");
s = s.replaceAll("value=[\\w-]+", "random");
return s;
}
public static String fixGrapherBug(String s) {
s = s.replaceAll("style=invis", "style=solid");
s = s.replaceAll("margin=(\\S+), ", " margin=\"$1\", ");
return s;
}
}
When using the most recent version of GraphViz, I find that the following substitution also helps (otherwise GraphViz refuses to open the file):
s.replaceAll(" margin=(\\S+), ", " margin=\"$1\", ")
The first replaceAll in the hideClassPaths() method above is over zealous -- it removes the class name as well as the package. It should be
s = s.replaceAll("\\w[a-z\\d_\\.]+\\.([A-Z][A-Za-z\\d_\\$]*)", "$1");
Note the addition of the dollar-sign so this also works for internal class names.
i'm looking for a way to generate an aspectJ aspect out of a Java class during my build process.
The goal ist to generate an inter-type declaration aspect that contains a String constant for each attribute of the java class.
Java class:
public class CarDTO {
private String vendor;
private String name;
public String getVendor() {}
public String getName() {}
[..]
}
This is the aspect which should be generated:
aspect CarAspect
{
public static final String CarDTO.VENDOR = "vendor";
public static final String CarDTO.NAME = "name";
}
Does any obne know a tool or a plugin for maven etc with which i can achieve this behaviour?
Thanks
martin
You could generate this code with CodeSmith Generator. If you are using JScript (Microsoft) inside of Visual Studio you could use our GenerateOnBuild or MSBuild (see this document aswell) support. Otherwise you could shell the CodeSmith Generator executable from within your build process and have it generate code that way too.
A custom template would need to be built to parse the file and generate the code. Out of the box we support Parsing Visual Basic or CSharp Code Files and generating off of Visual Basic or CSharp (this isn't helpful for you but it shows you that it has been done and is supported). Here is some documentation on creating a custom template.
Also, I do know that you can take a compiled jar file and convert it to a .NET assembly. From here you could use reflection in a template and generate your Java code.
This might not be the best alternative as you don't have Eclipse integration (depending on your editor, but it is an alternative solution that could solve this issue easily. Also you can write your template in JScript, CSharp or Visual Basic)
Thanks
-Blake Niemyjski (CodeSmith Employee)
Perhaps you can try annotation processing. See apt:
http://download.oracle.com/javase/1.5.0/docs/guide/apt/GettingStarted.html
Eclipse and AspectJ recognize annotation processing in both full and incremental builds.
Well,
finally i got a solution but still get stuck at one point.
The hint with the apt was a success.
I managed to create a AnnotationProcessor which generates an aspect as String. And here is the problem. Is it bad to create a new File object and paste the String into it to create the aspect file for each annotated class?
Thats the only way i currently can imageing.
thanks
martin
Solution:
I created an AnnotationProcessor (JDK1.6) that creates my aspects. The method generateAspect creates a file in the default source output folder for each aspect.
#SupportedAnnotationTypes( { "my.own.annotation.GenerateDTOConstants" } )
#SupportedSourceVersion( SourceVersion.RELEASE_6 )
public class DTOConstantAnnotationProcessor extends AbstractProcessor {
private static final Logger LOG = LoggerFactory
.getLogger( DTOConstantAnnotationProcessor.class );
private static final String ASPECT_POSTFIX = ".aj";
#Override
public boolean process( Set<? extends TypeElement> annotations, RoundEnvironment roundEnv ) {
DTOConstantElementVisitor visitor = new DTOConstantElementVisitor();
for( TypeElement element : annotations ) {
Set<? extends Element> annotatedClasses = roundEnv.getElementsAnnotatedWith( element );
for( Element dto : annotatedClasses ) {
generateAspect( visitor, dto );
}
}
return true;
}
/**
* #param visitor
* #param dto
*/
private void generateAspect( DTOConstantElementVisitor visitor, Element dto ) {
dto.accept( visitor, null );
LOG.info( "Generating aspect for " + dto.getSimpleName() );
Filer filer = this.processingEnv.getFiler();
try {
String fileName = visitor.getFileName() + ASPECT_POSTFIX;
String pkg = visitor.getPkg();
FileObject aspectFile = filer.createResource( StandardLocation.SOURCE_OUTPUT, pkg,
fileName );
Writer writer = aspectFile.openWriter();
LOG.info( "writing aspect content into file" );
writer.write( visitor.getFileContent() );
writer.close();
LOG.info( "Aspect generated for " + visitor.getFileName() );
}
catch( IOException e ) {
e.printStackTrace();
throw new java.lang.RuntimeException( e );
}
}
}
Ans here is the visitor i used (just a snippet):
public class DTOConstantElementVisitor extends AbstractElementVisitor6<Void, String> {
private static final String FIELD_PREFIX = "public static final String ";
private String fileName = null;
private String clazzName;
private String pkg;
private StringBuffer fileContentBuff;
#Override
public Void visitPackage( PackageElement e, String p ) {
System.out.println( "visitPackage" + e );
return null;
}
#Override
public Void visitType( TypeElement e, String p ) {
System.out.println( "visitTypeElement" + e );
try {
Class<?> clazz = Class.forName( e.getQualifiedName().toString() );
this.clazzName = clazz.getSimpleName();
createFileName( clazz );
this.pkg = clazz.getPackage().getName();
this.fileContentBuff = new StringBuffer();
fileContentBuff.append( "package " + this.pkg + ";\n" );
fileContentBuff.append( "public aspect " + this.fileName + " {\n" );
for( Field field : clazz.getDeclaredFields() ) {
if( Modifier.isPrivate( field.getModifiers() ) ) {
String fieldName = field.getName();
if( shouldGenerateField( fieldName ) ) {
fileContentBuff.append( FIELD_PREFIX + clazzName + "."
+ fieldName.toUpperCase() + " = \"" + fieldName + "\";\n" );
}
}
}
fileContentBuff.append( "}\n" );
System.out.println( fileContentBuff.toString() );
}
catch( ClassNotFoundException e1 ) {
throw new java.lang.RuntimeException( e1 );
}
return null;
}
private boolean shouldGenerateField( String fieldName ) {
if( "serialVersionUID".equals( fieldName ) ) {
return false;
}
return true;
}
private void createFileName( Class clazz ) {
this.fileName = clazzName + "Aspect";
}
}
Additonally you have to create config file in
META-INF/services
called
javax.annotation.processing.Processor
that contains the package and the name of the AnnotationProcessor
my.package.annotation.processor.DTOConstantAnnotationProcessor
And finally, the include in the maven build process:
<build>
<plugin>
<groupId>org.bsc.maven</groupId>
<artifactId>maven-processor-plugin</artifactId>
<version>2.0.0</version>
<executions>
<execution>
<id>aspectprocessing</id>
<phase>compile</phase>
<goals>
<goal>process</goal>
</goals>
</execution>
</executions>
</plugin>
</build>
For single call of the goal use
mvn processor:process
Thats all =)
AspectJ Version 1.8.2 now supports Annotation Processing. You can use this feature to generate ApspectJ Files during the build process, triggered by some annotations.
See this blog post for an example:
http://andrewclement.blogspot.de/2014/08/annotation-processing-in-ajdt.html