How to interact with Fuseki using Java in Eclipse - java

I'm following this tutorial here to insert a new resource into Fuseki's dataset, but I'm getting this error:
the method format(String, Object[]) in the type String is not applicable for the arguments (String, String)
This is the code:
import java.util.UUID;
import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.ResultSet;
import com.hp.hpl.jena.query.ResultSetFormatter;
import com.hp.hpl.jena.update.UpdateExecutionFactory;
import com.hp.hpl.jena.update.UpdateFactory;
import com.hp.hpl.jena.update.UpdateProcessor;
/**
* Example connection to Fuseki. For this to work, you need to start a local
* Fuseki server like this: ./fuseki-server --update --mem /ds
*/
public class FusekiTest {
/** A template for creating a nice SPARUL query */
private static final String UPDATE_TEMPLATE =
"PREFIX dc: <http://purl.org/dc/elements/1.1/>"
+ "INSERT DATA"
+ "{ <http://example/%s> dc:title \"A new book\" ;"
+ " dc:creator \"A.N.Other\" ." + "} ";
public static void main(String[] args) {
//Add a new book to the collection
String id = UUID.randomUUID().toString();
System.out.println(String.format("Adding %s", id));
UpdateProcessor upp = UpdateExecutionFactory.createRemote(
UpdateFactory.create(String.format(UPDATE_TEMPLATE, id)),
"http://localhost:3030/ds/update");
upp.execute();
}
}
How can I fix that error?

This issue is common when the java project version is 1.4.
It's a common problem that the project Java version is set to 1.4 or 1.6 by default in the template by the IDE. You should make sure that you have the correct Java version set on your project.
How to change your Java version
Eclipse:
Right click project -> Properties -> Java Build Path -> select JRE System Library click Edit and select JDK or JRE after then click Java Compiler and select Compiler compliance level to 1.8
IntelliJ
Menu -> File -> Project structure -> project SDK
Netbeans
This assumes that you installed JDK 1.6 and NetBeans knows about this.
Right-click on the Project and select Properties.
Under Library, select Java Platform JDK 1.8.
Select Source/Binary Format JDK8 in the Source category.
The JDK 1.8 must already have been supplied to NetBeans. To do that you got to menu -> Tools-> Java Platform Manager.

Related

Intellij IDEA cannot resolve 'andThen' functional interface method when referenced Function::andThen

How can I get IntellijIDEA to find the 'andThen' method of the core java 8 'Function' interface when using the notation Funciton::andThen? I've tried many things unsuccessfully.
My intellijIDEA module is configured to java 8, the sdk used is the oracle java 8, I've invalidated the caches, and tried several other things, but still the editor marks and then as: "cannot resolve method 'andThen'".
I can launch and build this sample, so I think it's something to do with the static code analyzer. Maybe a bug?
package foo.bar;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
public class Meh {
public static void main(String... args) {
final List<Function<String, String>> fs = new ArrayList<>();
fs.add(s -> s + "1");
fs.add(s -> s + "2");
final Function<String, String> f =
fs.stream()
//copmiles from cli and project->make, but editor shows: Cannot resolve method 'andThen'
.reduce(Function::andThen)
.get();
System.out.println(f.apply(""));//succesfully prints 12
final Function<String,String> f2 = f.andThen(s-> s+"a");
//succesfully prints 12a
System.out.println(f2.apply(""));
}
}
Something interesting is that when I reference f.andThen, the static code analyzer doesn't complain. It only happens when I reference Function::andThen.
This is not a problem when using eclipse. Or again, when compiling from the command line, or going to project -> make
This seems to be fixed in IntelliJ 15.0.2, with 15.0.1 I could reproduce this error marker.
Quite some bugs which sound like your kind of problem are mentioned in the release notes, section "Java.Error Highlighting", e.g.:
IDEA-146604 (Bug) Valid code highlighted as error (Enum::compareTo)
IDEA-147873 (Bug) Good code marked red with lambdas/method references

ClassNotFoundException using Processing's PApplet with Arduino Tool

I developer a basic Processing PApplet to run as a Tool in the Arduino IDE and that ran fine until Arduino 1.5.8. The problem I have is that in Arduino 1.6.0 some of the code got refactored and this happened on the Arduino side:
" In order to provide a better command line, IDE has been refactored
into app and arduino-core which is the old core In order to avoid
conflicts between classes, PApplet was moved from
processing.core.PApplet to processing.app.legacy.PApplet "
This explanation came from one of the Arduino IDE developers. It's worth noting that processing.app.legacy.PApplet is a (very)stripped down version of PApplet, discarding all graphics capabilities which I need.
Initially I was getting this error:
Uncaught exception in main method: java.lang.NoClassDefFoundError: processing/core/PApplet
Placing Processing's core.jar in the same location as the eclipse exported tool jar fixed this issues, but let to another:
Exception in thread "AWT-EventQueue-0" java.lang.RuntimeException: You need to use "Import Library" to add processing.core.PGraphicsJava2D to your sketch.
at processing.core.PApplet.makeGraphics(Unknown Source)
at processing.core.PApplet.init(Unknown Source)
The part that is confusing is I've used Processing's library source java files instead of the core.jar compiled library to avoid this issue, but it didn't change anything.
I've gone through PApplet's source code and found the graphics/renderer class gets loaded and instantiated at runtime here like so:
Class<?> rendererClass =
Thread.currentThread().getContextClassLoader().loadClass(renderer);
Constructor<?> constructor = rendererClass.getConstructor(new Class[] { });
PGraphics pg = (PGraphics) constructor.newInstance();
and this is where the ClassNotFoundException is caught throwing the Runtime exception:
catch (ClassNotFoundException cnfe) {
// if (cnfe.getMessage().indexOf("processing.opengl.PGraphicsOpenGL") != -1) {
// throw new RuntimeException(openglError +
// " (The library .jar file is missing.)");
// } else {
if (external) {
throw new RuntimeException("You need to use \"Import Library\" " +
"to add " + renderer + " to your sketch.");
} else {
throw new RuntimeException("The " + renderer +
" renderer is not in the class path.");
}
}
I'm getting more comfortable with java, but I don't have enough experience to figure this one out. It looks like a classpath issue, but I'm not sure why this happens and how I should tell java where to find the classes it needs to load.
Here is the code test I'm using based on the Arduino Tool sample that comes with the IDE. Currently I'm exporting the jar file (not runnable) from eclipse:
/*
Part of the Processing project - http://processing.org
Copyright (c) 2008 Ben Fry and Casey Reas
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package com.transformers.supermangletron;
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import processing.core.PApplet;
import processing.app.Editor;
import processing.app.tools.Tool;
//import processing.app.legacy.PApplet;
/**
* Example Tools menu entry.
*/
public class Mangler implements Tool {
private Editor editor;
public void init(Editor editor) {
this.editor = editor;
}
private void setupSketch(){
int w = 255;
int h = 255;
// PApplet ui = new PApplet();
TestApp ui = new TestApp();
JFrame window = new JFrame(getMenuTitle());
window.setPreferredSize(new Dimension(w,h+20));
window.add(ui);
window.invalidate();
window.pack();
window.setVisible(true);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ui.init();
System.out.println("setup complete");
}
public String getMenuTitle() {
return "Mangle Selection";
}
public void run() {
setupSketch();
}
}
and here's the basic test Applet I'm trying to display:
package com.transformers.supermangletron;
import processing.core.PApplet;
public class TestApp extends PApplet {
public void setup(){
size(100,100);
}
public void draw(){
background((1.0f+sin(frameCount * .01f)) * 127);
}
}
How can I fix this ClassNotFoundException with my setup?
Any hints on what I should double check regarding class paths?
If you're getting this error when you run from eclipse, you have to add the library jars to your classpath. You do this by right-clicking your project, going to properties, then to Java Build Path. Make sure the library jars are listed under the Libraries tab.
If you're getting this error when you run an exported jar, then you need to do one of two things:
Either make sure you export a runnable jar with the library jars embedded inside the main jar. Do this from eclipse by right-clicking the project, going to Export, then choosing "runnable jar" from the list.
Or, make sure you set the classpath as a JVM argument. You do this using the -cp option from the command line.

UnsatisfiedLinkError: no opencv_java249 in java.library.path

Running into some problems making a piece of code run on my mac.
Had someone write me an image analysis java app but I keep getting this error when trying to run it on netbeans.
run: Exception in thread "main" java.lang.UnsatisfiedLinkError: no
opencv_java249 in java.library.path at
java.lang.ClassLoader.loadLibrary(ClassLoader.java:1857) at
java.lang.Runtime.loadLibrary0(Runtime.java:870) at
java.lang.System.loadLibrary(System.java:1119) at
image.prossing.Test.main(Test.java:28) Java Result: 1 BUILD SUCCESSFUL
(total time: 0 seconds)
Have the netbeans project, and added the necessary jar files as libraries. The programmer told me to download the correct OpenCV version and copy the opencv.dll file to my java/jre/bin folder. But I cannot find the dll file or the java/jre folder.
I know most programming happens on windows for a reason. Hope someone can help me resolve this issue and run this application on my mac.
Here is the first part of the code, the part that is most probably creating the error:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package image.prossing;
/**
*
* #author Dumith Salinda
*/
import java.util.ArrayList;
import java.util.List;
import org.opencv.core.Core;
import static org.opencv.core.Core.FONT_HERSHEY_SIMPLEX;
import org.opencv.core.Mat;
import org.opencv.core.MatOfPoint;
import org.opencv.core.Point;
import org.opencv.core.Rect;
import org.opencv.core.Scalar;
import org.opencv.highgui.Highgui;
import org.opencv.imgproc.Imgproc;
public class Test {
public static void main(String[] args) {
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
Sorry if it's not that clear, let me know what info to add if something is missing or not clear.
Would truly appreciate any help you could give. Sincerely
Meir Warcel
Look into your OpenCV directory;
For an example this; (installed using brew install opencv3 --with-java --with-python3)
/usr/local/Cellar/opencv3/XXX/share/OpenCV/java
You will see;
libopencv_javaXXX.so opencv-XXX.jar
Now that you already have OpenCV's native library for Java (libopencv_javaXXX.so) compiled with you, the only thing left is, mac's dynamic library.
Link libopencv_javaXXX.so to libopencv_javaXXX.dylib;
ln -s libopencv_javaXXX.so libopencv_javaXXX.dylib
Now add /usr/local/Cellar/opencv3/XXX/share/OpenCV/java as Native Library Locations in IntelliJ or something similar in Eclipse.
Or add this to your JVM arguments;
-Djava.library.path=/usr/local/Cellar/opencv3/XXX/share/OpenCV/java
On a mac running OSX Yosemite, I dropped the libopencv_java2412.dylib file into /Library/Java/Extensions and it worked.
After you build opencv, the libopencv_java2412.dylib is generated in /build/lib.
After Spending a lots of time , and using different suggestions from StackOverflow I managed to get solution for windows. but I am adding a solution for mac as well. hope it should work.
Load your lib as per your system configuration.
private static void loadLibraries() {
try {
InputStream in = null;
File fileOut = null;
String osName = System.getProperty("os.name");
String opencvpath = System.getProperty("user.dir");
if(osName.startsWith("Windows")) {
int bitness = Integer.parseInt(System.getProperty("sun.arch.data.model"));
if(bitness == 32) {
opencvpath=opencvpath+"\\opencv\\x86\\";
}
else if (bitness == 64) {
opencvpath=opencvpath+"\\opencv\\x64\\";
} else {
opencvpath=opencvpath+"\\opencv\\x86\\";
}
}
else if(osName.equals("Mac OS X")){
opencvpath = opencvpath+"Your path to .dylib";
}
System.out.println(opencvpath);
System.load(opencvpath + Core.NATIVE_LIBRARY_NAME + ".dll");
} catch (Exception e) {
throw new RuntimeException("Failed to load opencv native library", e);
}
}
2.now use this method as per your need
public static void main(String[] args) {
loadLibraries();
}
Building on Harsh Vakharia's answer i tried installing OpenCV on my mac with macports:
sudo port install opencv +java
ls /opt/local/share/OpenCV/java
libopencv_java343.dylib opencv-343.jar
To use this library I was hoping to be able to modify the library path at runtime which was discussed in
Adding new paths for native libraries at runtime in Java
And ended up with the following helper class and unit test. The code is now part of the
Self Driving RC-Car open Source project in which I am a comitter.
JUnit Test
/**
* #see <a href=
* 'https://stackoverflow.com/questions/27088934/unsatisfiedlinkerror-no-opencv-java249-in-java-library-path/35112123#35112123'>OpenCV
* native libraries</a>
* #throws Exception
*/
#Test
public void testNativeLibrary() throws Exception {
if (debug)
System.out.println(String.format("trying to load native library %s",
Core.NATIVE_LIBRARY_NAME));
assertTrue(NativeLibrary.getNativeLibPath().isDirectory());
assertTrue(NativeLibrary.getNativeLib().isFile());
NativeLibrary.load();
}
NativeLibrary
package com.bitplan.opencv;
import java.io.File;
import java.lang.reflect.Field;
import java.util.Arrays;
import org.opencv.core.Core;
/**
* load OpenCV NativeLibrary properly
*/
public class NativeLibrary {
protected static File nativeLibPath = new File("../lib");
/**
* get the native library path
*
* #return the file for the native library
*/
public static File getNativeLibPath() {
return nativeLibPath;
}
/**
* set the native library path
*
* #param pNativeLibPath
* - the library path to use
*/
public static void setNativeLibPath(File pNativeLibPath) {
nativeLibPath = pNativeLibPath;
}
/**
* get the current library path
*
* #return the current library path
*/
public static String getCurrentLibraryPath() {
return System.getProperty("java.library.path");
}
/**
* Adds the specified path to the java library path
*
* #param pathToAdd
* the path to add
* #throws Exception
* #see <a href=
* 'https://stackoverflow.com/questions/15409223/adding-new-paths-for-native-libraries-at-runtime-in-java'>Stackoverflow
* question how to add path entry to native library search path at
* runtime</a>
*/
public static void addLibraryPath(String pathToAdd) throws Exception {
final Field usrPathsField = ClassLoader.class.getDeclaredField("usr_paths");
usrPathsField.setAccessible(true);
// get array of paths
final String[] paths = (String[]) usrPathsField.get(null);
// check if the path to add is already present
for (String path : paths) {
if (path.equals(pathToAdd)) {
return;
}
}
// add the new path
final String[] newPaths = Arrays.copyOf(paths, paths.length + 1);
newPaths[newPaths.length - 1] = pathToAdd;
usrPathsField.set(null, newPaths);
}
public static File getNativeLib() {
File nativeLib = new File(getNativeLibPath(),
"lib" + Core.NATIVE_LIBRARY_NAME + ".dylib");
return nativeLib;
}
/**
* load the native library by adding the proper library path
*
* #throws Exception
* - if reflection access fails (e.g. in Java9/10)
*/
public static void load() throws Exception {
addLibraryPath(getNativeLibPath().getAbsolutePath());
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
}
}
Exception is occurring from below line of code:
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
Your program is trying to load a native library by the name of argument in call to loadLibrary method, which it is not able to locate. Make sure that native library (opencv.dll) is placed at one of the locations present in java.library.path system property as JVM looks at these locations for loading any native library (which might not contain 'java/jre/bin').
You can print java.library.path in your program like below:
System.out.println(System.getProperty("java.library.path"));
You cannot just put Windows library (dll file) on Mac and have it running - you need to compile the library for Mac first (or get Mac version of the library).
Please see here for tips on how to do it:
.dll Equivalent on Mac OS X
How do third-party libraries work in Objective-C and Xcode?
How to use a Windows DLL with Java in Mac OS X?
Instead of struggling with manual installation of OpenCV libraries I suggest you use OpenCV Java library packaged by OpenPnP (https://github.com/openpnp/opencv) that includes all required DLL.
It does not require additonal steps except of adding it to your build automation tool configuration (Gradle in my case) and adding the following code to load the library:
System.loadLibrary(org.opencv.core.Core.NATIVE_LIBRARY_NAME);
Just add into the path the folder where your opencv_java249.dll is; it would be something like C:\bin\opencv\build\java\x32 or C:\bin\opencv\build\java\x64 depending of your machine architecture. The problem is that java.library.path is actually the path variable.
netebans right klick project chosew properti
chose run, working direktory, click Browser change to opencv folder, release/lib,

The method sendKeys(CharSequence[]) in the type WebElement is not applicable for the arguments (String)

I am trying to send a String to the sendkeys() method, but it is not accepting and throwing an error as
my codes follows:
package healthcare;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
import com.thoughtworks.selenium.Selenium;
import com.thoughtworks.selenium.webdriven.WebDriverBackedSelenium;
public class MailRegister_Webdriver {
public WebDriver driver;
public Selenium selenium;
public void openURL(){
//System.setProperty("webdriver.chrome.driver", "F:\\Library\\chromedriver.exe");
driver=new FirefoxDriver();
selenium=new WebDriverBackedSelenium(driver, "http://mail.in.com");
driver.get("http://mail.in.com");
}
public void register() throws Exception{
//driver.findElement(By.cssSelector("input.registernow")).click();
selenium.click("css=input.registernow");
Thread.sleep(3000);
driver.findElement(By.id("fname")).sendKeys("Nagesh");
selenium.select("day", "10");
selenium.select("month", "Jun");
new Select(driver.findElement(By.id("year"))).selectByVisibleText("1999");
Thread.sleep(1000);
driver.findElement(By.xpath("(//input[#name='radiousername'])[5]")).click();
Thread.sleep(2000);
driver.findElement(By.id("password")).sendKeys("nag123");
driver.findElement(By.id("repassword")).sendKeys);
driver.findElement(By.id("altemail")).sendKeys();
driver.findElement(By.id("mobileno")).sendKeys("7894561230");
driver.findElement(By.id("imageField")).click();
}
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
MailRegister_Webdriver m=new MailRegister_Webdriver();
m.openURL();
m.register();
}
}
Can somebody help on this, Why Sendkeys() method is not taking String values as arguments?
It has a simple solution. Change your compiler compliance level from 1.4 to 1.7.
Follow these steps in your eclipse:
Right click on your java project and select Build Path -> Click on
Configure Build Path...
In project properties window, Click/select Java Compiler at the left
panel
At the right panel, change the Compiler compliance level from 1.4 to 1.7
(Select which is higher version in your eclipse)
Lastly Click on Apply and OK
Now check your code. it will never show the same error.
element.sendKeys(new String[]{"Hello, selenium"});
My code looks like this, it's working.
There are two possible solution for this
1- Change the compiler version from old version to 1.5 or greater.
2- Change the JRE version from JRE8 to JRE7.
I have created a detailed article on this may be it will help.
http://learn-automation.com/solution-for-sendkeyscharsequence-in-selenium/
Try to click into the WebElement before you sending keys to it:
public static void login(WebDriver driver, String userName, String password) {
driver.get("loginPage.html");
Thread.sleep(3000);
driver.findElement(By.id("username")).click();
driver.findElement(By.id("username")).clear();
driver.findElement(By.id("username")).sendKeys(userName);
Thread.sleep(TestConfiguration.time);
driver.findElement(By.id("password")).click();
driver.findElement(By.id("password")).clear();
driver.findElement(By.id("password")).sendKeys(password);
Thread.sleep(3000);
driver.findElement(By.name("login")).click();
Thread.sleep(3000);
}
You should use clear() method to clear the input field before using sendKeys().
You can try by replacing your following lines of code:
driver.findElement(By.id("password")).sendKeys("nag123");
driver.findElement(By.id("repassword")).sendKeys);
driver.findElement(By.id("altemail")).sendKeys();
driver.findElement(By.id("mobileno")).sendKeys("7894561230");
driver.findElement(By.id("imageField")).click();
to
driver.findElement(By.id("password")).sendKeys("nag123");
driver.findElement(By.id("repassword")).sendKeys("");
driver.findElement(By.id("altemail")).sendKeys("");
driver.findElement(By.id("mobileno")).sendKeys("7894561230");
driver.findElement(By.id("imageField")).click();
Depending on the version of java you need to either convert the primitive (i.e. Char) to String (look here: http://tech.deepumohan.com/2013/03/java-how-to-convert-primitive-char-to.html)
Or switch to a java version that would do it for you (see here: http://java-performance.info/changes-to-string-java-1-7-0_06/)
Set the JRE System Library again. If you use eclipse follow the steps below:
Go to project properties
Select Java Build Path at the left panel -> Select Libraries tab at the right
Click/select JRE System Library[] -> Click Edit button at the right side
Set your preferred JRE and click Finish button
Lastly click OK button from the project properties pop up window
Instead of editing you can also do by deleting and adding. The steps are:
Right-click on project » Properties » Java Build Path
Select Libraries tab
Find the JRE System Library and remove it
Click Add Library... button at right side » Add the JRE System Library
(Workspace default JRE)

Eclipse internal compiler error

When using this code in Eclipse:
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class Test {
public static void main(String[] args) {
List<Object> objs = Arrays.asList(new Object(), new Object());
Set<String> s = objs.stream().collect(HashSet::new, HashSet::add, Object::toString);
System.out.println(s);
}
}
I get:
Internal compiler error: java.lang.ArrayIndexOutOfBoundsException: 0 at
org.eclipse.jdt.internal.compiler.lookup.ConstraintExpressionFormula.reduceReferenceExpressionCompatibility(ConstraintExpressionFormula
.java:273)
I know that this is this line which is producing the error:
Set<String> s = objs.stream().collect(HashSet::new, HashSet::add, Object::toString);
Not sure if it's relevant but I'm using:
Eclipse Kepler 4.3.2
Plugins: Eclipse Java Development Tools Patch with Java 8 support (for Kepler SR2) and Eclipse Plug-in Development Environment Patch with Java 8 support (for Kepler SR2)
java.runtime.version=1.8.0-b132
Here's the screenshot:
I know that the collect method is not correct but why I don't have a compiler error telling something like:
- The method collect(Supplier<R>, BiConsumer<R,? super Object>, BiConsumer<R,R>) in the type Stream<Object> is not applicable for the arguments etc.
This looks like Eclipse bug 433085 a duplicate of bug 430766. This is targeted to be fixed in Eclipse 4.4 Luna M7.

Categories

Resources