Skip to content

Instantly share code, notes, and snippets.

@mbruch
Last active December 17, 2015 08:18
Show Gist options
  • Save mbruch/5579139 to your computer and use it in GitHub Desktop.
Save mbruch/5579139 to your computer and use it in GitHub Desktop.
OSGI Service Implementation
package com.example.miniscout.client;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;
import com.example.miniscout.client.services.LocalDatabaseService;
import com.example.miniscout.shared.IDatabaseService;
public class Activator extends AbstractUIPlugin {
private static Activator plugin;
public void start(BundleContext context) throws Exception {
super.start(context);
plugin = this;
context.registerService(IDatabaseService.class, new LocalDatabaseService(),
null);
}
public void stop(BundleContext context) throws Exception {
plugin = null;
super.stop(context);
}
public static Activator getDefault() {
return plugin;
}
}
package com.example.miniscout.shared;
import java.net.URI;
public interface IDatabaseService {
public Form load(URI source);
public void save(Form form, URI target);
}
package com.example.miniscout.client.services;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.net.URI;
import com.example.miniscout.shared.Form;
import com.example.miniscout.shared.IDatabaseService;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
/**
* A Gson based database service that reads data from JSON files and converts
* them to forms.
*/
public class LocalDatabaseService implements IDatabaseService {
@Override
public Form load(URI source) {
try {
File f = new File(source);
FileReader r = new FileReader(f);
Gson b = new GsonBuilder().create();
return b.fromJson(r, Form.class);
} catch (Exception e) {
// swallowing just for simplicity of training...
e.printStackTrace();
return null;
}
}
@Override
public void save(Form form, URI target) {
try {
Gson b = new GsonBuilder().create();
File f = new File(target);
FileWriter w = new FileWriter(f);
b.toJson(form, w);
w.close();
} catch (Exception e) {
// swallowing just for simplicity of training...
e.printStackTrace();
}
}
}
package com.example.miniscout.client.services;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.FrameworkUtil;
import org.osgi.framework.ServiceReference;
public class Services {
public static <T> T get(Class<T> clazz) {
Bundle bundle = FrameworkUtil.getBundle(Services.class);
BundleContext context = bundle.getBundleContext();
ServiceReference<T> ref = context.getServiceReference(clazz);
T service = context.getService(ref);
context.ungetService(ref);
return service;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment