I'm newbie here. I'm dealing with my first program using osgi bundles and JmDNS. After adding JmDNS 3.4.1 jar to my project, I'm testing the following basic code:
My Activator:
package test.discoverservice;
import java.io.IOException;
import test.DiscoverServices;
import javax.jmdns.JmDNS;
import javax.jmdns.ServiceTypeListener;
import org.equinoxosgi.jmdns.dev.discoverservice.DiscoverServices.SampleListener;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
public class JmdnsActivator implements BundleActivator {
public void start(BundleContext context) throws Exception {
System.out.println("Launching");
try {
System.out.println("step 1");
final JmDNS jmdns = JmDNS.create();
System.out.println("step 2");
jmdns.addServiceListener("_http._tcp.local.", new SampleListener());
// jmdns.close();
// System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}
public void stop(BundleContext context) throws Exception {
System.out.println("Terminating");
}
}
and here is the bundle:
package test.discoverservice;
import javax.jmdns.ServiceEvent;
import javax.jmdns.ServiceListener;
public class DiscoverServices {
static class SampleListener implements ServiceListener {
#Override
public void serviceAdded(ServiceEvent event) {
System.out.println("Service added : " + event.getName() + "." + event.getType());
}
#Override
public void serviceRemoved(ServiceEvent event) {
System.out.println("Service removed : " + event.getName() + "." + event.getType());
}
#Override
public void serviceResolved(ServiceEvent event) {
System.out.println("Service resolved: " + event.getInfo());
}
}
}
when I run the code, I get :
osgi> Launching
step 1
and then it stops, so I guess there is a probelm with the creation of the JmDNS instance..
Any idea please?
Note that if I don't use a bundle with an activator (simple program with main) everything works properly
import java.io.IOException;
import javax.jmdns.JmDNS;
import javax.jmdns.ServiceEvent;
import javax.jmdns.ServiceTypeListener;
public class DiscoverServiceTypes {
static class SampleListener implements ServiceTypeListener {
#Override
public void serviceTypeAdded(ServiceEvent event) {
System.out.println("Service type added: " + event.getType());
}
public void subTypeForServiceTypeAdded(ServiceEvent event) {
System.out.println("SubType for service type added: " + event.getType());
}
}
public static void main(String[] args) {
try {
JmDNS jmdns = JmDNS.create();
System.out.println("JmDNS created !!");
jmdns.addServiceTypeListener(new SampleListener());
// jmdns.close();
// System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}
}
PS: I'm running it on Windows
You have to add the imported library in the classpath of the MANIFEST.MF file of the OSGI Framework if not already done.
Bundle-ClassPath: org.json.jar,
lib/jmdns-3.4.1.jar, ...
If you got the lirary from sourceforge check if the jar file is correct and no class is present twice in the jar. (If so, just use the .jar from Maven)
Related
I want to use separate configuration files for different bundles instead of using a single configuration/config.ini file. I am following this doc https://www.eclipse.org/equinox/documents/quickstart-framework.php .
I am not able to figure out how to achieve this. Any suggestion would be very helpful.
Thanks in advance.
Following links solve the problem I was facing-
https://www.eclipse.org/forums/index.php/t/1072082/
https://git.eclipse.org/c/om2m/org.eclipse.om2m.git/tree/org.eclipse.om2m.site.mn-cse/configurations/services/lifx.basedriver.properties
https://git.eclipse.org/c/om2m/org.eclipse.om2m.git/tree/org.eclipse.om2m.sdt/org.eclipse.om2m.sdt.home.lifx/src/main/java/org/eclipse/om2m/sdt/home/lifx/impl/Activator.java
Steps I followed to achieve this -
Create configurations/services/<config_file_name>.properties having configurations in key-value pair. For example - property1 property1_value
Import package org.osgi.service.cm for your bundle
Use the following code
package <package_name>;
import java.util.Dictionary;
import java.util.Hashtable;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.cm.ConfigurationException;
import org.osgi.service.cm.ManagedService;
public class Activator implements BundleActivator, ManagedService {
private static BundleContext context;
private ServiceRegistration managedServiceServiceRegistration;
static BundleContext getContext() {
return context;
}
public void start(BundleContext bundleContext) throws Exception {
Activator.context = bundleContext;
Dictionary properties = new Hashtable<>();
properties.put(Constants.SERVICE_PID, "config_file_name");
managedServiceServiceRegistration =
bundleContext.registerService(ManagedService.class.getName(), this, properties);
}
public void stop(BundleContext bundleContext) throws Exception {
Activator.context = null;
}
#Override
public void updated(Dictionary properties) throws ConfigurationException {
try {
System.out.println(properties.get("property1"));
} catch (Exception e) {
e.printStackTrace();
}
}
}
When I create jetty websocket, I register my endpoint handler like this:
public class MyWebSocketEndpoint extends WebSocketServlet {
#Override
public void configure(WebSocketServletFactory webSocketServletFactory) {
webSocketServletFactory.register(MyEndpointHandler.class);
}
}
for MyEndpoingHandler class, I can't define a constructor with some parameters, or it will got runtime exception. How can I pass some parameters when create the MyEndpointHandler instance?
Use a WebSocketCreator.
When you call WebSocketServletFactory.register(MyEndpoingHandler.class) all that's happening internally is the equivalent of ...
#Override
public void register(Class<?> websocketPojo)
{
this.setCreator(new SingleEndpointCreator(websocketPojo));
}
Complete example on WebSocketCreator:
package websocket;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.DefaultHandler;
import org.eclipse.jetty.server.handler.HandlerList;
import org.eclipse.jetty.servlet.DefaultServlet;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketMessage;
import org.eclipse.jetty.websocket.api.annotations.WebSocket;
import org.eclipse.jetty.websocket.servlet.ServletUpgradeRequest;
import org.eclipse.jetty.websocket.servlet.ServletUpgradeResponse;
import org.eclipse.jetty.websocket.servlet.WebSocketCreator;
import org.eclipse.jetty.websocket.servlet.WebSocketServlet;
import org.eclipse.jetty.websocket.servlet.WebSocketServletFactory;
public class DemoWebSocketCreator
{
public static class MyWebSocketServlet extends WebSocketServlet
{
#Override
public void configure(WebSocketServletFactory wsFactory)
{
wsFactory.setCreator(new MyWebSocketCreator());
}
}
public static class MyWebSocketCreator implements WebSocketCreator
{
private AtomicInteger idGen = new AtomicInteger(0);
#Override
public Object createWebSocket(ServletUpgradeRequest servletUpgradeRequest, ServletUpgradeResponse servletUpgradeResponse)
{
String id = "ws" + idGen.incrementAndGet();
return new MyWebSocket(id);
}
}
#WebSocket
public static class MyWebSocket
{
private final String id;
public MyWebSocket(String id)
{
this.id = id;
}
#OnWebSocketMessage
public void onMessage(Session session, String msg)
{
try
{
session.getRemote().sendString("Hello, my id is [" + id + "]: You said: " + msg);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
public static void main(String[] args) throws Exception
{
Server server = new Server(8080);
ServletContextHandler context = new ServletContextHandler();
context.setContextPath("/");
context.addServlet(MyWebSocketServlet.class, "/ws/");
// always last, and on default pathspec
context.addServlet(DefaultServlet.class, "");
HandlerList handlers = new HandlerList();
handlers.addHandler(context);
handlers.addHandler(new DefaultHandler());
server.setHandler(handlers);
server.start();
server.join();
}
}
How can I create a Spring Aspect (annotation driven e.g. #ExceptionTranslation) surrounding an entire method and put this method in a try...catch method?
#ExceptionTranslation
public void method() {
// do some stuff here...
}
so logically it does:
public void method() {
try {
// do some stuff here ...
} catch( Exception ex ) {
}
}
Below you can find a sample implementation of AfterThrows advice solving your problem.
CustomException.java
package com.yourpackage;
public class CustomException extends Exception {
public CustomException(final Throwable cause) {
super(cause);
}
}
ErrorBean.java
package com.yourpackage;
public class ErrorBean {
#ExceptionTranslation
public void translatedException() throws Exception {
throw new Exception("Foo");
}
public void notTranslatedException() throws Exception {
throw new Exception("Bar");
}
}
ExceptionTranslation.java
package com.yourpackage;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.METHOD)
public #interface ExceptionTranslation {
}
SimpleThrowsAdvice.java
package com.yourpackage;
import org.springframework.aop.Advisor;
import org.springframework.aop.ThrowsAdvice;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.aop.support.annotation.AnnotationMatchingPointcut;
public class SimpleThrowsAdvice implements ThrowsAdvice {
public static void main(String[] args) throws Exception {
ErrorBean errorBean = new ErrorBean();
AnnotationMatchingPointcut pc = AnnotationMatchingPointcut.forMethodAnnotation(ExceptionTranslation.class);
SimpleThrowsAdvice advice = new SimpleThrowsAdvice();
Advisor advisor = new DefaultPointcutAdvisor(pc, advice);
ProxyFactory pf = new ProxyFactory();
pf.setTarget(errorBean);
pf.addAdvisor(advisor);
ErrorBean proxy = (ErrorBean) pf.getProxy();
try {
proxy.translatedException();
} catch (CustomException ex) {
System.out.println("CustomException caught");
} catch (Exception ex) {
System.out.println("Exception caught");
}
try {
proxy.notTranslatedException();
} catch (CustomException ex) {
System.out.println("CustomException caught");
} catch (Exception ex) {
System.out.println("Exception caught");
}
}
public void afterThrowing(Exception ex) throws Throwable {
System.out.println("***");
System.out.println("Generic Exception Capture");
System.out.println("Caught: " + ex.getClass().getName());
System.out.println("***\n");
throw new CustomException(ex);
}
}
all.
i am a newbie of lucene, and i'm using spring-mvc (3.2.5.RELEASE) and lucene(4.6.0).
both are newest version currently.
how can i use NEAR REAL TIME search?
i write this code to get instance of IndexWriter (sington)
package com.github.yingzhuo.mycar.search;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.Resource;
import org.springframework.util.Assert;
import org.wltea.analyzer.lucene.IKAnalyzer;
public class IndexWriterFactoryBean implements FactoryBean<IndexWriter>, InitializingBean, DisposableBean {
private static final Logger LOGGER = LoggerFactory.getLogger(IndexWriterFactoryBean.class);
private Analyzer analyzer = new IKAnalyzer(false);
private Resource indexDirectory = null;
private IndexWriter indexWriter = null;
private Directory directory = null;
public IndexWriterFactoryBean() {
if (indexDirectory != null) {
try {
if (! indexDirectory.getFile().exists()) {
FileUtils.forceMkdir(indexDirectory.getFile());
}
} catch (IOException e) {
LOGGER.warn(e.getMessage(), e);
}
}
}
#Override
public IndexWriter getObject() throws Exception {
return indexWriter;
}
#Override
public Class<?> getObjectType() {
return IndexWriter.class;
}
#Override
public boolean isSingleton() {
return true;
}
#Override
public void afterPropertiesSet() throws Exception {
Assert.notNull(analyzer, "property 'analyzer' must be set.");
Assert.notNull(indexDirectory, "property 'indexDirectory' must be set.");
directory = FSDirectory.open(indexDirectory.getFile());
indexWriter = new IndexWriter(directory, new IndexWriterConfig(Version.LUCENE_46, analyzer));
}
#Override
public void destroy() throws Exception {
IOUtils.closeQuietly(indexWriter);
IOUtils.closeQuietly(directory);
IOUtils.closeQuietly(analyzer);
}
// getter & setter
// ------------------------------------------------------------------------------------------
public void setAnalyzer(Analyzer analyzer) {
this.analyzer = analyzer;
}
public void setIndexDirectory(Resource indexDirectory) {
this.indexDirectory = indexDirectory;
}
}
and this utility to get DirectoryReader by static method.
import java.io.IOException;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexWriter;
import com.github.yingzhuo.mycar.config.SpringUtils;
public final class DirectoryReaderHolder {
private static DirectoryReader HOLDER = null;
public synchronized static DirectoryReader get() {
if (HOLDER == null) {
try {
HOLDER = DirectoryReader.open(SpringUtils.getBean(IndexWriter.class), true);
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
return HOLDER;
}
public static synchronized void set(DirectoryReader directoryReader) {
if (directoryReader == null) {
throw new NullPointerException();
} else {
HOLDER = directoryReader;
}
}
}
and this bean to inject into my spring-mvc controller. In 'create' method, i am trying to get a new reader before i create a IndexSearcher, but HOW SHOULD I HANDLE THE OLD READER ?
can i close it directly? if other threads are still using the old reader, very bad thing will happen ?
package com.github.yingzhuo.mycar.search;
import java.io.IOException;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.search.IndexSearcher;
public class IndexSearcherManager {
public IndexSearcher create() {
try {
DirectoryReader oldReader = DirectoryReaderHolder.get();
DirectoryReader newReader = DirectoryReader.openIfChanged(oldReader);
if (newReader != null) {
oldReader.close(); // AM I RIGHT ???
oldReader = newReader;
}
return new IndexSearcher(oldReader);
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
}
Any suggestions? thank you.
I am trying to do an Jetty Web Socket example .
I copied a example from internet , which was working fine when i deployed directly into server without making any chnages .
But when i copied the Source (the servlet) into Eclipse IDE , it was giving Compilation
Exceptions related to
The method onClose(int, String) of type Html5Servlet.StockTickerSocket must override a superclass method
- The method onOpen(WebSocket.Connection) of type Html5Servlet.StockTickerSocket must override a superclass method
The method onMessage(String) of type Html5Servlet.StockTickerSocket must override a superclass method
This is my servlet , i kept the jars as it is mentioned in that example
package org.ajeesh.app;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.atomic.AtomicInteger;
import javax.servlet.http.HttpServletRequest;
import org.eclipse.jetty.websocket.WebSocket;
import org.eclipse.jetty.websocket.WebSocketServlet;
public class Html5Servlet extends WebSocketServlet {
private AtomicInteger index = new AtomicInteger();
private static final List<String> tickers = new ArrayList<String>();
static{
tickers.add("ajeesh");
tickers.add("peeyu");
tickers.add("kidillan");
tickers.add("entammo");
}
/**
*
*/
private static final long serialVersionUID = 1L;
public WebSocket doWebSocketConnect(HttpServletRequest req, String resp) {
System.out.println("On server");
return new StockTickerSocket();
}
protected String getMyJsonTicker(){
StringBuilder start=new StringBuilder("{");
start.append("\"stocks\":[");
int counter=0;
for (String aTicker : tickers) {
counter++;
start.append("{ \"ticker\":\""+aTicker +"\""+","+"\"price\":\""+index.incrementAndGet()+"\" }");
if(counter<tickers.size()){
start.append(",");
}
}
start.append("]");
start.append("}");
return start.toString();
}
public class StockTickerSocket implements WebSocket.OnTextMessage{
private Connection connection;
private Timer timer;
#Override
public void onClose(int arg0, String arg1) {
System.out.println("Web socket closed!");
}
#Override
public void onOpen(Connection connection) {
System.out.println("onOpen!");
this.connection=connection;
this.timer=new Timer();
}
#Override
public void onMessage(String data) {
System.out.println("onMessage!");
if(data.indexOf("disconnect")>=0){
connection.close();
timer.cancel();
}else{
sendMessage();
}
}
private void sendMessage() {
System.out.println("sendMessage!");
if(connection==null||!connection.isOpen()){
System.out.println("Connection is closed!!");
return;
}
timer.schedule(new TimerTask() {
#Override
public void run() {
try{
System.out.println("Running task");
connection.sendMessage(getMyJsonTicker());
}
catch (IOException e) {
e.printStackTrace();
}
}
}, new Date(),5000);
}
}
}