getBundleContext method is undefined issue - java

I'm trying to setup an application that runs on OSGi internally and have tried using the tutorial here, but I get the error "The method getBundleContext() is undefined for the type Framework" all the time. As far as I can tell, I'm using the right library, but it's not specified in the mentioned article, so I'm not 100% sure. I've also tried the examples on Apache's website, here, which results in the same issue. Code below:
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.ServiceLoader;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleException;
import org.osgi.framework.launch.Framework;
import org.osgi.framework.launch.FrameworkFactory;
public class Main {
public static void main(String[] args) throws BundleException {
FrameworkFactory frameworkFactory = ServiceLoader.load(FrameworkFactory.class).iterator().next();
Map<String, String> config = new HashMap<String, String>();
Framework framework = frameworkFactory.newFramework(config);
framework.start();
// Throws error that it cannot find method getBundleContext()
BundleContext context = framework.getBundleContext();
List<Bundle> installedBundles = new LinkedList<Bundle>();
installedBundles.add(context.installBundle("file:org.apache.felix.shell-1.4.2.jar"));
installedBundles.add(context.installBundle("file:org.apache.felix.shell.tui-1.4.1.jar"));
for (Bundle bundle : installedBundles) {
bundle.start();
}
}
}
The only thing that makes sense is that either I'm using the wrong libraries, or the libraries have changed and the method I'm attempting to call has since been deprecated out in the last 4 years. Anyone know how I can fix this?
I doubt it makes much of a difference, but in case it does, I'm using Bndtools for Eclipse to create this project.

Found the issue. Apparently, the import of osgi.core that was in the Bndtools' project build path was out of date, preventing the code from accessing the correct version of the framework libraries. Updating that fixed the issue.
Additional side-note; Since I'm using Bndtools, I was adding this to the project build path via the bnd.bnd file's build tab. This, however, was not grabbing the correct version of osgi.core, so I had to go under source and add the version=latest in order to force it to get the latest version available, so the line now appears as: osgi.core;version=latest where it was previously just osgi.core under the -buildpath: section.

Related

import libraries on eclipse 2021 fails Example: org.apache.commons.dbcp.BasicDataSource

I am migrating a Java code that is running on Java 8 and I need to compile it to run on Java 17, so Just downloaded eclipse 2021-09 import the code from Git, change project facet selecting Java, add to Java Build Path the libraries.
libraries added
This is the code:
package itksoluciones.avl.lst.dboperation;
import javax.sql.DataSource;
import org.apache.commons.dbcp.BasicDataSource;
public class PoolConexionUC {
public static DataSource dataSourceUC;
public PoolConexionUC() {
inicializaDataSourceUC();
}
private void inicializaDataSourceUC() {
BasicDataSource basicDataSourceUC = new BasicDataSource();
basicDataSourceUC.setDriverClassName(DataConexion.driverUC);
basicDataSourceUC.setUsername(DataConexion.userUC);
basicDataSourceUC.setPassword(DataConexion.passUC);
basicDataSourceUC.setUrl(DataConexion.urlUC);
basicDataSourceUC.setMaxActive(Integer.parseInt(DataConexion.maxActiveUC));
basicDataSourceUC.setMaxIdle(DataConexion.defaultMaxIdleUC);
basicDataSourceUC.setMaxWait(DataConexion.defaultMaxWaitUC);
basicDataSourceUC.setRemoveAbandoned(DataConexion.removeAbandonedUC);
basicDataSourceUC.setRemoveAbandonedTimeout(DataConexion.removeAbandonedTimeoutUC);
basicDataSourceUC.setValidationQuery(DataConexion.validationQueryUC);
basicDataSourceUC.setTestOnBorrow(DataConexion.testOnBorrowUC);
dataSourceUC = basicDataSourceUC;
}
}
This are the two errors:
Import org.apache could not be resolved
and
BasicDatasourceCore could not be resolved to a type
Errors
As you could see from the error the library seems available, also it autocompletes when typing.
Also one of the solutions suggested by eclipse is to import org.apache.commons.dbcp.BasicDataSource. (after doing it by double clicking on the suggestion first error is resolved but the second one persists).
What is also very curious is that if I copy paste the class PoolConexionCore to PoolConexionCore2. The problem is gone in PoolConexionCore2.
BUT I HAVE MANY CLASSES WITH THE SAME PROBLEM so I really appreciate any suggestion to avoid having to be dedicated to copy pasted for several days.
After doing copy paste

How do I declare a default parser for Rest Assured 3.0.3 (using Java and TestNG)?

Good day folks,
I am an admittedly novice Java programmer but I take care to research docs and FAQ's to try to get past issues. This is a problem that I have not been able to overcome, however. I am using RestAssured (version 3.0.3, as pulled by Maven) and cannot get RestAssured to parse "text/plain" content (rather, I cannot get Java to compile the code to do so).
This compiles but gives an error:
import static io.restassured.RestAssured.*;
import static io.restassured.matcher.RestAssuredMatchers.*;
import static org.hamcrest.Matchers.*;
import static io.restassured.module.jsv.JsonSchemaValidator.*;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.testng.annotations.AfterClass;
public class TestNG2 {
/*
userName, passWord and server defined here as protected static Strings
*/
#Test
public void filter_Asset(){
given().
auth().basic(userName, passWord).
when().
get ("http://" + server +"/api/filter?type=$tAsset").
then().
statusCode(200).
body("count", greaterThan(0));
}
}
The error:
java.lang.IllegalStateException: Expected response body to be verified as JSON, HTML or XML but content-type 'text/plain' is not supported out of the box.
Try registering a custom parser using:
RestAssured.registerParser("text/plain", );
However, when I try to include the following line in the filter_Asset test:
RestAssured.registerParser("text/plain", Parser.JSON);
The code will not compile with the following complaint:
java.lang.Error: Unresolved compilation problems:
RestAssured cannot be resolved
Parser cannot be resolved to a variable
I receive similar complaints when I try to use the following declaration:
RestAssured.defaultParser = Parser.JSON;
For what it's worth, I am working on a Windows 7, 64-bit machine. Using Eclipse Neon.3 (4.6.3) and my JDK is 1.8_131
I've consulted the RestAssured usage and documentation pages, believe am importing the packages correctly, etc. Am I making a rookie error somewhere?
It was a rookie mistake!
In addition to statically importing the class methods, the compiler also required importing of the following classes:
import io.restassured.RestAssured;
import io.restassured.parsing.Parser;
After those declarations, I was able to register the default Parser in the filter_Asset test:
RestAssured.registerParser("text/plain", Parser.JSON);

How can you set the search path for JavaToRascal from Java

We tried to import a test rascal module and a module from the standard library using JavaToRascal.
The test module is stored in C:\Users\Klemens\workspace\RascalInterop\src\MyTest.rsc and contains:
module MyTest
Te java code containing the JavaToRascal invocation is as follows:
import java.io.PrintWriter;
import java.net.URISyntaxException;
import org.rascalmpl.interpreter.JavaToRascal;
import org.rascalmpl.interpreter.load.IRascalSearchPathContributor;
import org.rascalmpl.interpreter.load.StandardLibraryContributor;
import org.rascalmpl.interpreter.load.URIContributor;
import org.rascalmpl.uri.URIUtil;
public class RascalInterop {
public static void main(String[] args) throws URISyntaxException {
JavaToRascal j2r = new JavaToRascal(new PrintWriter(System.out), new PrintWriter(System.err));
IRascalSearchPathContributor modulePath = new URIContributor(URIUtil.createFileLocation("C:\\Users\\Klemens\\workspace\\RascalInterop\\src\\MyTest.rsc"));
j2r.getEvaluator().addRascalSearchPathContributor(modulePath);
try {
j2r.eval("import MyTest;").toString(); // Could not import module MyTest: can not find in search path
} catch (Exception e) {
System.out.println(e.getMessage());
}
try {
j2r.getEvaluator().addRascalSearchPathContributor(StandardLibraryContributor.getInstance());
j2r.eval("import IO;").toString(); // null pointer exception
} catch (Exception e) {
System.out.println(e.getClass());
}
}
}
The print in the first try block that tries to import our MyTest.rsc module results in:
Could not import module MyTest: can not find in search path
?[Advice](http://tutor.rascal-mpl.org/Errors/Static/ModuleImport/ModuleImport.html)
The second import attempting to import the IO module from the standard library results in:
class java.lang.NullPointerException
Any ideas how to use properly set the search path from a Java program?
We tried to use j2r.getEvaluator().addRascalSearchPathContributor in various ways but did not succeed in loading a MyTest.rsc module from the given directory.
Despite that these API will change in the near future (due to the compilation process and related changes), here's an answer. Two answers actually, one for Rascal files and one for Java code that it needs
For Rascal:
j2r.getEvaluator().addRascalSearchPathContributor
What you used is the correct way of doing things. So if it did not work, please provide more code so we can diagnose what goes wrong. So where is your module? Is it in a jar file or a binary folder? If its in a jar, you need some additional wiring I'm glad to explain.
The Rascal search path is distinguished from the Classpath for Java classes which are used by Rascal. So you have different API for that. We use classloaders to find Java files (such that it also works for situations like OSGI bundles in Eclipse):
Evaluator x = ctx.getEvaluator();
x.addClassLoader(getClass().getClassLoader());
This will make sure that the class loader used to load the current class is also used to load the class linked mentioned in the Rascal file. Of course you can also provide other class loaders. Note that if the libraries you depend on are loaded via OSGI, make sure you get a classloader from a class that is in a bundle that has access to these classes. The simple case is when everything is in the same jar file, then any classloader will do.
I think you should change the path to refer to the src directory instead of the source file:
new URIContributor(URIUtil.createFileLocation("C:\\Users\\Klemens\\workspace\\RascalInterop\\src"));
Also: probably you should use forward slashes without C:\, so /Users/.../src
AFAIK The null pointer exception is expected, evaluating import returns null, and you try to call toString().

TitanFactory static build method

I'm new to Java and playing with Titan DB.
Per the documentation of the Cassandra backend, TitanFactory has a static method build():
TitanGraph g = TitanFactory.build()
.set("storage.backend","cassandra")
.set("storage.hostname","127.0.0.1")
.open();
However, when looking at the source, it only seems to have an overloaded open() method:
package com.thinkaurelius.titan.core;
import com.thinkaurelius.titan.graphdb.configuration.GraphDatabaseConfiguration;
import com.thinkaurelius.titan.graphdb.database.StandardTitanGraph;
import org.apache.commons.configuration.Configuration;
import java.io.File;
public class TitanFactory {
public static TitanGraph open(String directoryOrConfigFile) {
return open(GraphDatabaseConfiguration.getConfiguration(new File(directoryOrConfigFile)));
}
public static TitanGraph open(Configuration configuration) {
return new StandardTitanGraph(new GraphDatabaseConfiguration(configuration));
}
}
I thought maybe the version that's up on GitHub is newer than the build I have, but I've got the latest version and GitHub says the file was last modified in May. So I'm thinking I've got to be missing something. TitanFactory.build() does, indeed, work. It returns a TitanFactory Builder. So, where does build come from?
MVN Repository shows the library at version 0.5.1. The code you download with the maven dependency contains a TitanFactory#build() method.
I'm not sure which git branch contains the most up to date code (doesn't seem like master), but this one seems promising.

Writing a java code which will execute every hour(quartz)

Can someone please correct me, I've found this example online and bunch of others not working, this particular example throws the following error :
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/collections/SetUtils
at org.quartz.JobDetail.<init>(JobDetail.java:85)
at tralala.org.xml.CronSchedule.<init>(CronSchedule.java:13)
at tralala.org.xml.CronSchedule.main(CronSchedule.java:20)
Here is the code :
CronJob.java
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
public class CronJob implements Job {
public void execute(JobExecutionContext arg0) throws JobExecutionException {
System.out.println("PRINT SOME TEXT LINE");
}
}
CronSchedule.java
import org.quartz.CronTrigger;
import org.quartz.Scheduler;
import org.quartz.SchedulerFactory;
import org.quartz.impl.StdSchedulerFactory;
import org.quartz.JobDetail;
public class CronSchedule {
public CronSchedule ()throws Exception {
SchedulerFactory sf=new StdSchedulerFactory();
Scheduler sched=sf.getScheduler();
JobDetail jd=new JobDetail("job1","group1",CronJob.class);
CronTrigger ct=new CronTrigger("cronTrigger","group2","0 0/1 * * * ?");
sched.scheduleJob(jd,ct);
sched.start();
}
public static void main(String args[]){
try{
new CronSchedule();
}catch(Exception e){}
}
}
I just wanna run(that is actually works) any example of quartz .. I've been searching for some time now and every example either has compile error or like this one(rare one) throws an error. I just wanna run it this one or any .. just to get some inside with a concrete example. I've been reading http://www.opensymphony.com/quartz/wikidocs/TutorialLesson1.html, the examples don't compile .. any suggestions ? tnx
The error just shows that you don't have the class org.apache.commons.collections.SetUtils in your class path. So you should ensure that. You can download the library from here.
Then extract the download file. You should see a file commons-collections-3.2.1.jar. You just place that file in your class path. OR run it with the option '-cp commons-collections-3.2.1.jar'.
Add to the class path the library containing the SetUtils class.
You can find it here.
You should add commons-collections (v3.1) to you classpath. It's also bundled in the Quartz distribution.
It will probably be much easier for you if you start with the examples that come bundled with in the Quartz distribution archive. They are in the examples subdirectory and for each example there's a script to run it (alongside the ant-based compilation script of course). Study these scripts to see how everything fits together. As Quartz comes bundled with all needed dependencies you should be able to run the examples without downloading whatsoever.

Categories