I am trying to work with bacnet4j. but unable to find any tutorial or guide. I am using Bacnet-stack simulator for testing.
I tried this code to check i am functionality and I have also tried localdevice but both the cases i am getting error of no class definition error in this package com.serotonin.bacnet4j.npdu.Network.
package bacnet_4_j_test;
import com.serotonin.bacnet4j.LocalDevice;
import com.serotonin.bacnet4j.RemoteDevice;
import com.serotonin.bacnet4j.RemoteObject;
import com.serotonin.bacnet4j.ServiceFuture;
import com.serotonin.bacnet4j.event.DeviceEventAdapter;
import com.serotonin.bacnet4j.exception.BACnetException;
import com.serotonin.bacnet4j.exception.ErrorAPDUException;
import com.serotonin.bacnet4j.npdu.ip.IpNetwork;
import com.serotonin.bacnet4j.service.acknowledgement.ReadPropertyAck;
import
com.serotonin.bacnet4j.service.acknowledgement.ReadPropertyMultipleAck;
import com.serotonin.bacnet4j.service.confirmed.*;
import com.serotonin.bacnet4j.service.unconfirmed.WhoIsRequest;
import com.serotonin.bacnet4j.transport.DefaultTransport;
import com.serotonin.bacnet4j.transport.Transport;
import com.serotonin.bacnet4j.type.constructed.ReadAccessResult;
import com.serotonin.bacnet4j.type.constructed.ReadAccessSpecification;
import com.serotonin.bacnet4j.type.constructed.SequenceOf;
import com.serotonin.bacnet4j.type.enumerated.ObjectType;
import com.serotonin.bacnet4j.type.enumerated.PropertyIdentifier;
import com.serotonin.bacnet4j.type.enumerated.Segmentation;
import com.serotonin.bacnet4j.type.primitive.ObjectIdentifier;
import com.serotonin.bacnet4j.type.primitive.Real;
import com.serotonin.bacnet4j.util.DiscoveryUtils;
import java.util.ArrayList;
import java.util.List;
/**
*
* #author kaushikdas
*/
public class Bacnet_4_j_test {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws Exception {
IpNetwork network = new IpNetwork("192.168.2.255", IpNetwork.DEFAULT_PORT);
Transport transport = new DefaultTransport(network);
transport.setTimeout(500000);
transport.setSegTimeout(15000);
final LocalDevice localDevice = new LocalDevice(1338, transport);
localDevice.getEventHandler().addListener(new DeviceEventAdapter() {
public void iAmReceived(RemoteDevice device) {
System.out.println("Discovered device " + device);
localDevice.addRemoteDevice(device);
final RemoteDevice remoteDevice = localDevice.getRemoteDevice(device.getAddress());
remoteDevice.setSegmentationSupported(Segmentation.segmentedBoth);
new Thread(new Runnable() {
#Override
public void run() {
try {
try {
DiscoveryUtils.getExtendedDeviceInformation(localDevice, remoteDevice);
} catch (BACnetException e) {
e.printStackTrace();
}
System.out.println(remoteDevice.getName() + " " + remoteDevice.getVendorName() + " " + remoteDevice.getModelName() + " " + remoteDevice.getAddress() + " " + remoteDevice.getProtocolRevision() + " " + remoteDevice.getProtocolVersion());
ReadPropertyAck ack = localDevice.send(remoteDevice, new ReadPropertyRequest(remoteDevice.getObjectIdentifier(), PropertyIdentifier.objectList)).get();
SequenceOf<ObjectIdentifier> value = ack.getValue();
for (ObjectIdentifier id : value) {
List<ReadAccessSpecification> specs = new ArrayList<ReadAccessSpecification>();
specs.add(new ReadAccessSpecification(id, PropertyIdentifier.presentValue));
specs.add(new ReadAccessSpecification(id, PropertyIdentifier.units));
specs.add(new ReadAccessSpecification(id, PropertyIdentifier.objectName));
specs.add(new ReadAccessSpecification(id, PropertyIdentifier.description));
specs.add(new ReadAccessSpecification(id, PropertyIdentifier.objectType));
ReadPropertyMultipleRequest multipleRequest = new ReadPropertyMultipleRequest(new SequenceOf<ReadAccessSpecification>(specs));
ReadPropertyMultipleAck send = localDevice.send(remoteDevice, multipleRequest).get();
SequenceOf<ReadAccessResult> readAccessResults = send.getListOfReadAccessResults();
System.out.print(id.getInstanceNumber() + " " + id.getObjectType() + ", ");
for (ReadAccessResult result : readAccessResults) {
for (ReadAccessResult.Result r : result.getListOfResults()) {
System.out.print(r.getReadResult() + ", ");
}
}
System.out.println();
}
ObjectIdentifier mode = new ObjectIdentifier(ObjectType.analogValue, 11);
ServiceFuture send = localDevice.send(remoteDevice, new WritePropertyRequest(mode, PropertyIdentifier.presentValue, null, new Real(2), null));
System.out.println(send.getClass());
System.out.println(send.get().getClass());
} catch (ErrorAPDUException e) {
System.out.println("Could not read value " + e.getApdu().getError() + " " + e);
} catch (BACnetException e) {
e.printStackTrace();
}
}
}).start();
}
#Override
public void iHaveReceived(RemoteDevice device, RemoteObject object) {
System.out.println("Value reported " + device + " " + object);
}
});
localDevice.initialize();
localDevice.sendGlobalBroadcast(new WhoIsRequest());
List<RemoteDevice> remoteDevices = localDevice.getRemoteDevices();
for (RemoteDevice device : remoteDevices) {
System.out.println("Remote dev " + device);
}
System.in.read();
localDevice.terminate();
}
}
But i am getting this error.
Exception in thread "main" java.lang.NoClassDefFoundError: org/slf4j/LoggerFactory
at com.serotonin.bacnet4j.npdu.Network.<clinit>(Network.java:43)
at bacnet_4_j_test.Bacnet_4_j_test.main(Bacnet_4_j_test.java:43)
Caused by: java.lang.ClassNotFoundException: org.slf4j.LoggerFactory
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:338)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 2 more
If anybody has any tutorial please provide.
You are missing slf4j dependency. Add slf4j to your class path and it should work.
Related
How can I create a dead letter queue and test it out? I have a producer and consumer. I also have producer configs like acks, retries.
Producer.java
package org.timothy.producer;
import org.apache.kafka.clients.producer.*;
import org.timothy.producer.common.AppConfigs;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.timothy.producer.common.PropConfigs;
import java.util.concurrent.ExecutionException;
public class Producer{
private static final Logger logger = LogManager.getLogger(Producer.class);
public static void main(String[] args) {
logger.info("Creating Kafka Producer...");
KafkaProducer<Integer, String> producer = PropConfigs.prodProps();
logger.info("Start sending messages...");
for (int i = 1; i <= AppConfigs.numEvents; i++) {
ProducerRecord<Integer, String> record = new ProducerRecord<>(AppConfigs.topicName, "This is Message: " + i);
try {
RecordMetadata metadata = producer.send(record).get();
System.out.println("Record sent with key " + i + " to partition " + metadata.partition()
+ " with offset " + metadata.offset());
}
catch (ExecutionException e) {
System.out.println("Error in sending record");
//System.out.println(e);
e.printStackTrace();
}
catch (InterruptedException e) {
System.out.println("Error in sending record");
//System.out.println(e);
}
}
producer.flush();
producer.close();
logger.info("Finished - Closing Kafka Producer.");
}
}
Consumer.java
package org.timothy.producer;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.timothy.producer.common.AppConfigs;
import org.timothy.producer.common.PropConfigs;
import java.time.Duration;
import java.util.Collections;
public class Consumer{
private static final Logger logger = LogManager.getLogger(Consumer.class);
public static void main(String[] args) {
KafkaConsumer<Integer, String> consumer = PropConfigs.consProps();
consumer.subscribe(Collections.singleton(AppConfigs.topicName));
int noMessageFound = 0;
while(true){
ConsumerRecords<Integer,String> records = consumer.poll(Duration.ofMillis(1000));
if (records.count() == 0) {
noMessageFound++;
if (noMessageFound > AppConfigs.MAX_NO_MESSAGE_FOUND_COUNT)
break;
else
continue;
}
records.forEach(record -> logger.info("Received new record: " +
" Key: " + record.key() +
", Value: " + record.value() +
", Topic: " + record.topic() +
", Partition: " + record.partition() +
", Offset: " + record.offset() + "\n"
));
consumer.commitAsync();
}
}
}
How do I implement DLQ in my code? How to test the retries, when I run my program I don't encounter errors that's why I don't know if the program retries or not.
when I run my program I don't encounter errors
Then introduce them. Create a counter, when it hits a certain value, throw a RuntimeException. In the catch block, use your producer instance to send an event to a new topic.
If you want to test retries, shutdown the broker or introduce some other network exception
Please find below code, which runs fine on Windows 10 System and is able to discover remote devices across the network. On Linux we are creating a jar out of the code and running it using java -jar test.jar
package main;
import java.util.ArrayList;
import java.util.List;
import com.serotonin.bacnet4j.LocalDevice;
import com.serotonin.bacnet4j.RemoteDevice;
import com.serotonin.bacnet4j.RemoteObject;
import com.serotonin.bacnet4j.ServiceFuture;
import com.serotonin.bacnet4j.event.DeviceEventAdapter;
import com.serotonin.bacnet4j.exception.BACnetException;
import com.serotonin.bacnet4j.exception.ErrorAPDUException;
import com.serotonin.bacnet4j.npdu.ip.IpNetwork;
import com.serotonin.bacnet4j.npdu.ip.IpNetworkBuilder;
import com.serotonin.bacnet4j.service.acknowledgement.ReadPropertyAck;
import com.serotonin.bacnet4j.service.acknowledgement.ReadPropertyMultipleAck;
import com.serotonin.bacnet4j.service.confirmed.*;
import com.serotonin.bacnet4j.service.unconfirmed.WhoIsRequest;
import com.serotonin.bacnet4j.transport.DefaultTransport;
import com.serotonin.bacnet4j.transport.Transport;
import com.serotonin.bacnet4j.type.constructed.ReadAccessResult;
import com.serotonin.bacnet4j.type.constructed.ReadAccessSpecification;
import com.serotonin.bacnet4j.type.constructed.SequenceOf;
import com.serotonin.bacnet4j.type.enumerated.ObjectType;
import com.serotonin.bacnet4j.type.enumerated.PropertyIdentifier;
import com.serotonin.bacnet4j.type.enumerated.Segmentation;
import com.serotonin.bacnet4j.type.primitive.ObjectIdentifier;
import com.serotonin.bacnet4j.type.primitive.Real;
import com.serotonin.bacnet4j.util.DiscoveryUtils;
public class test {
public static void main(String[] args) throws Exception {
IpNetwork network = new IpNetworkBuilder().broadcastIp("192.168.1.255").localBindAddress("192.168.1.164").port(47808).build();
Transport transport = new DefaultTransport(network);
transport.setTimeout(500000);
transport.setSegTimeout(15000);
LocalDevice localDevice = new LocalDevice(21312, transport);
localDevice.getEventHandler().addListener(new DeviceEventAdapter() {
#Override
public void iAmReceived(RemoteDevice device) {
System.out.println("Discovered device " + device);
System.out.println("device Address" + device.getAddress().getMacAddress().getDescription());
localDevice.addRemoteDevice(device);
final RemoteDevice remoteDevice = localDevice.getRemoteDevice(device.getAddress());
remoteDevice.setSegmentationSupported(Segmentation.segmentedBoth);
new Thread(new Runnable() {
#Override
public void run() {
try {
try {
DiscoveryUtils.getExtendedDeviceInformation(localDevice, remoteDevice);
} catch (BACnetException e) {
e.printStackTrace();
}
System.out.println(remoteDevice.getName() + " " + remoteDevice.getVendorName() + " " + remoteDevice.getModelName() + " " + remoteDevice.getAddress() + " " + remoteDevice.getProtocolRevision() + " " + remoteDevice.getProtocolVersion());
ReadPropertyAck ack = localDevice.send(remoteDevice, new ReadPropertyRequest(remoteDevice.getObjectIdentifier(), PropertyIdentifier.objectList)).get();
SequenceOf<ObjectIdentifier> value = ack.getValue();
for (ObjectIdentifier id : value) {
List<ReadAccessSpecification> specs = new ArrayList<ReadAccessSpecification>();
specs.add(new ReadAccessSpecification(id, PropertyIdentifier.presentValue));
specs.add(new ReadAccessSpecification(id, PropertyIdentifier.units));
specs.add(new ReadAccessSpecification(id, PropertyIdentifier.objectName));
specs.add(new ReadAccessSpecification(id, PropertyIdentifier.description));
specs.add(new ReadAccessSpecification(id, PropertyIdentifier.objectType));
ReadPropertyMultipleRequest multipleRequest = new ReadPropertyMultipleRequest(new SequenceOf<ReadAccessSpecification>(specs));
ReadPropertyMultipleAck send = localDevice.send(remoteDevice, multipleRequest).get();
SequenceOf<ReadAccessResult> readAccessResults = send.getListOfReadAccessResults();
System.out.print(id.getInstanceNumber() + " " + id.getObjectType() + ", ");
for (ReadAccessResult result : readAccessResults) {
for (ReadAccessResult.Result r : result.getListOfResults()) {
System.out.print(r.getReadResult() + ", ");
}
}
System.out.println();
}
ObjectIdentifier mode = new ObjectIdentifier(ObjectType.analogValue, 11);
ServiceFuture send = localDevice.send(remoteDevice, new WritePropertyRequest(mode, PropertyIdentifier.presentValue, null, new Real(2), null));
System.out.println(send.getClass());
} catch (ErrorAPDUException e) {
System.out.println("Could not read value " + e.getApdu().getError() + " " + e);
} catch (BACnetException e) {
e.printStackTrace();
}
}
}).start();
}
#Override
public void iHaveReceived(RemoteDevice device, RemoteObject object) {
System.out.println("Value reported " + device + " " + object);
}
});
localDevice.initialize();
localDevice.sendGlobalBroadcast(new WhoIsRequest());
System.in.read();
localDevice.terminate();
}
}
On Linux we are unable to discover the devices that are running on Windows OS but the application that is running on Windows is able to discover Linux BacNet localDevice. Code is same but still unable to discover BacNet devices on Linux.
Please help us find any solution.
Issues like this (partial visibility) are often caused my a 'mismatch' of IP parameters. I notice you have hardcoded "192.168.1.255". Is this really the broadcast IP address from the PI's perspective?
Resolved the problem by removing the broadcast and LocalBindAddress.
I try to create an FTP server with java to test an other aplication, but when i try to start the server, it's crashes. It's the code:
Imports:
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.ftpserver.FtpServer;
import org.apache.ftpserver.FtpServerFactory;
import org.apache.ftpserver.ftplet.Authority;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.ftplet.FtpReply;
import org.apache.ftpserver.ftplet.FtpRequest;
import org.apache.ftpserver.ftplet.FtpSession;
import org.apache.ftpserver.ftplet.Ftplet;
import org.apache.ftpserver.ftplet.FtpletContext;
import org.apache.ftpserver.ftplet.FtpletResult;
import org.apache.ftpserver.ftplet.UserManager;
import org.apache.ftpserver.listener.ListenerFactory;
import org.apache.ftpserver.usermanager.PasswordEncryptor;
import org.apache.ftpserver.usermanager.PropertiesUserManagerFactory;
import org.apache.ftpserver.usermanager.impl.BaseUser;
import org.apache.ftpserver.usermanager.impl.WritePermission;
Code:
public class FTPServerTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
FtpServerFactory serverFactory = new FtpServerFactory();
ListenerFactory factory = new ListenerFactory();
factory.setPort(36000);
serverFactory.addListener("default", factory.createListener());
PropertiesUserManagerFactory userManagerFactory = new PropertiesUserManagerFactory();
userManagerFactory.setFile(new File("Z:\\Winteco98\\FTPUssers\\myusers.properties"));
userManagerFactory.setPasswordEncryptor(new PasswordEncryptor()
{//We store clear-text passwords in this example
#Override
public String encrypt(String password) {
return password;
}
#Override
public boolean matches(String passwordToCheck, String storedPassword) {
return passwordToCheck.equals(storedPassword);
}
});
//Let's add a user, since our myusers.properties files is empty on our first test run
BaseUser user = new BaseUser();
user.setName("ProdeWin");
user.setPassword("ProdeWinW98");
user.setHomeDirectory("Z:\\Winteco98\\FTPUssers");
List<Authority> authorities = new ArrayList<Authority>();
authorities.add(new WritePermission());
user.setAuthorities(authorities);
UserManager um = userManagerFactory.createUserManager();
try
{
um.save(user);//Save the user to the user list on the filesystem
}
catch (FtpException e1)
{
//Deal with exception as you need
}
serverFactory.setUserManager(um);
Map<String, Ftplet> m = new HashMap<String, Ftplet>();
m.put("miaFtplet", new Ftplet()
{
#Override
public void init(FtpletContext ftpletContext) throws FtpException {
//System.out.println("init");
//System.out.println("Thread #" + Thread.currentThread().getId());
}
#Override
public void destroy() {
//System.out.println("destroy");
//System.out.println("Thread #" + Thread.currentThread().getId());
}
#Override
public FtpletResult beforeCommand(FtpSession session, FtpRequest request) throws FtpException, IOException
{
//System.out.println("beforeCommand " + session.getUserArgument() + " : " + session.toString() + " | " + request.getArgument() + " : " + request.getCommand() + " : " + request.getRequestLine());
//System.out.println("Thread #" + Thread.currentThread().getId());
//do something
return FtpletResult.DEFAULT;//...or return accordingly
}
#Override
public FtpletResult afterCommand(FtpSession session, FtpRequest request, FtpReply reply) throws FtpException, IOException
{
//System.out.println("afterCommand " + session.getUserArgument() + " : " + session.toString() + " | " + request.getArgument() + " : " + request.getCommand() + " : " + request.getRequestLine() + " | " + reply.getMessage() + " : " + reply.toString());
//System.out.println("Thread #" + Thread.currentThread().getId());
//do something
return FtpletResult.DEFAULT;//...or return accordingly
}
#Override
public FtpletResult onConnect(FtpSession session) throws FtpException, IOException
{
//System.out.println("onConnect " + session.getUserArgument() + " : " + session.toString());
//System.out.println("Thread #" + Thread.currentThread().getId());
//do something
return FtpletResult.DEFAULT;//...or return accordingly
}
#Override
public FtpletResult onDisconnect(FtpSession session) throws FtpException, IOException
{
//System.out.println("onDisconnect " + session.getUserArgument() + " : " + session.toString());
//System.out.println("Thread #" + Thread.currentThread().getId());
//do something
return FtpletResult.DEFAULT;//...or return accordingly
}
});
serverFactory.setFtplets(m);
//Map<String, Ftplet> mappa = serverFactory.getFtplets();
//System.out.println(mappa.size());
//System.out.println("Thread #" + Thread.currentThread().getId());
//System.out.println(mappa.toString());
FtpServer server = serverFactory.createServer();
try
{
server.start();//Your FTP server starts listening for incoming FTP-connections, using the configuration options previously set
}
catch (FtpException ex)
{
//Deal with exception as you need
}
}
And, finaly, the error:
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/mina/filter/executor/OrderedThreadPoolExecutor
at org.apache.ftpserver.FtpServerFactory.<init>(FtpServerFactory.java:51)
at mainPackage.FTPServerTest.main(FTPServerTest.java:32)
Caused by: java.lang.ClassNotFoundException: org.apache.mina.filter.executor.OrderedThreadPoolExecutor
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 2 more
I haven't idea where does the error, please, help me.
You need to add mina jar file in your project library path. Find below download link for jar file.
Mina Jar file
Hello I am trying to develop my web application using jsp. I have 6 jsp pages in it. Pages are registration.jsp, login.jsp, r1.jsp, welcome.jsp, createroom.jsp and showroom.jsp respectivly. My goal is that when i login in login page, page should redirect in openmeeting server. For that i have created webservice like omRestService. For calling this Service i have created two java class omGateWay and OmPluginSettings respectivly. Everything works fine but error occurs in ompluginSetting class.error mention below.
import com.atlassian.sal.api.pluginsettings.PluginSettings;
import com.atlassian.sal.api.pluginsettings.PluginSettingsFactory;
(The import com.atlassian cannot be resolved)
Here I am Providing you my OmPluginSeeting.java file which has error. There are many errors occur at PluginSettingsFactory.
package restService;
import com.atlassian.sal.api.pluginsettings.PluginSettings;
import com.atlassian.sal.api.pluginsettings.PluginSettingsFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class OmPluginSettings
{
private static final Logger log = (Logger) LoggerFactory.getLogger(OmPluginSettings.class);
final PluginSettingsFactory pluginSettingsFactory;
public OmPluginSettings(PluginSettingsFactory pluginSettingsFactory)
{
this.pluginSettingsFactory = pluginSettingsFactory;
}
public void storeSomeInfo(String key, String value)
{
this.pluginSettingsFactory.createGlobalSettings().put("openmeetings:" + key, value);
}
public Object getSomeInfo(String key)
{
return this.pluginSettingsFactory.createGlobalSettings().get("openmeetings:" + key);
}
public void storeSomeInfo(String projectKey, String key, String value)
{
this.pluginSettingsFactory.createSettingsForKey(projectKey).put("openmeetings:" + key,
value);
}
public Object getSomeInfo(String projectKey, String key) {
return this.pluginSettingsFactory.createSettingsForKey(projectKey).get("openmeetings:"
+ key);
}
}
I also provide my restservice which is Given Below and totally error free.
package restService;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.util.Iterator;
import java.util.LinkedHashMap;
import javax.ws.rs.core.UriBuilder;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class omRestService
{
private static final Logger log = (Logger)
LoggerFactory.getLogger(omRestService.class);
private URI getURI(String url) {
return UriBuilder.fromUri(
url).build(new Object[0]);
}
private String getEncodetURI(String url) throws MalformedURLException
{
return new URL(url).toString().replaceAll(" ", "%20");
}
public LinkedHashMap<String, Element> call(String request, Object param)
throws Exception
{
HttpClient client = new HttpClient();
GetMethod method = null;
try
{
method = new GetMethod(getEncodetURI(request).toString());
}
catch (MalformedURLException e) {
e.printStackTrace();
}
int statusCode = 0;
try {
statusCode = client.executeMethod(method);
}
catch (HttpException e)
{
throw new Exception("Connection to OpenMeetings refused. Please check your
OpenMeetings configuration.");
}
catch (IOException e)
{
throw new Exception("Connection to OpenMeetings refused. Please check your
OpenMeetings configuration.");
}
switch (statusCode)
{
case 200:
break;
case 400:
throw new Exception("Bad request. The parameters passed to the service did
not match
as expected. The Message should tell you what was missing or incorrect.");
case 403:
throw new Exception("Forbidden. You do not have permission to access this
resource, or
are over your rate limit.");
case 503:
throw new Exception("Service unavailable. An internal problem prevented us
from
returning data to you.");
default:
throw new Exception("Your call to OpenMeetings! Web Services returned an
unexpected
HTTP status of: " + statusCode);
}
InputStream rstream = null;
try
{
rstream = method.getResponseBodyAsStream();
}
catch (IOException e) {
e.printStackTrace();
throw new Exception("No Response Body");
}
BufferedReader br = new BufferedReader(new InputStreamReader(rstream));
SAXReader reader = new SAXReader();
Document document = null;
String line;
try
{
// String line;
while ((line = br.readLine()) != null)
{
// String line;
document = reader.read(new ByteArrayInputStream(line.getBytes("UTF-8")));
}
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
throw new Exception("UnsupportedEncodingException by SAXReader");
}
catch (IOException e) {
e.printStackTrace();
throw new Exception("IOException by SAXReader in REST Service");
}
catch (DocumentException e) {
e.printStackTrace();
throw new Exception("DocumentException by SAXReader in REST Service");
} finally {
br.close();
}
Element root = document.getRootElement();
LinkedHashMap elementMap = new LinkedHashMap();
for (Iterator i = root.elementIterator(); i.hasNext(); )
{
Element item = (Element)i.next();
if (item.getNamespacePrefix() == "soapenv") {
throw new Exception(item.getData().toString());
}
String nodeVal = item.getName();
elementMap.put(nodeVal, item);
}
return elementMap;
}
}
After This RestService i have make OmGateWay class which has many method for integrate with openmeetings. which is given below:
package org.openmeetings.jira.plugin.gateway;
import java.util.LinkedHashMap;
import org.dom j.Element;
import org.openmeetings.jira.plugin.ao.adminconfiguration.OmPluginSettings;
import org.slf j.Logger;
import org.slf j.LoggerFactory;
public class OmGateway
{
private static final Logger log =
LoggerFactory.getLogger(OmGateway.class);
private OmRestService omRestService;
private OmPluginSettings omPluginSettings;
private String sessionId;
public OmGateway(OmRestService omRestService, OmPluginSettings omPluginSettings)
{
this.omRestService = omRestService;
this.omPluginSettings = omPluginSettings;
}
public Boolean loginUser() throws Exception
{
LinkedHashMap result = null;
String url = (String)this.omPluginSettings.getSomeInfo("url");
String port = (String)this.omPluginSettings.getSomeInfo("port");
String userpass = (String)this.omPluginSettings.getSomeInfo("userpass");
String omusername =
(String)this.omPluginSettings.getSomeInfo("username");
String sessionURL = "http://" + url + ":" + port + "/openmeetings
/services/
UserService/getSession";
LinkedHashMap elementMap = this.omRestService.call(sessionURL, null);
Element item = (Element)elementMap.get("return");
setSessionId(item.elementText("session_id"));
log.info(item.elementText("session_id"));
result = this.omRestService.call("http://" + url + ":" + port +
"/openmeetings/
services/UserService/loginUser?SID=" + getSessionId() + "&username=" +
omusername
+ "&userpass=" + userpass, null);
if
(Integer.valueOf(((Element)result.get("return")).getStringValue()).intValue() >
) {
return Boolean.valueOf(true);
}
return Boolean.valueOf(false);
}
public Long addRoomWithModerationExternalTypeAndTopBarOption(Boolean
isAllowedRecording,
Boolean isAudioOnly, Boolean isModeratedRoom, String name, Long
numberOfParticipent, Long
roomType, String externalRoomType)
throws Exception
{
String url = (String)this.omPluginSettings.getSomeInfo("url");
String port = (String)this.omPluginSettings.getSomeInfo("port");
String roomId = "";
String restURL = "http://" + url + ":" + port + "/openmeetings/services/
RoomService/addRoomWithModerationExternalTypeAndTopBarOption?" +
"SID=" + getSessionId() +
"&name=" + name +
"&roomtypes_id=" + roomType.toString() +
"&comment=jira" +
"&numberOfPartizipants=" + numberOfParticipent.toString() +
"&ispublic=false" +
"&appointment=false" +
"&isDemoRoom=false" +
"&demoTime=" +
"&isModeratedRoom=" + isModeratedRoom.toString() +
"&externalRoomType=" + externalRoomType +
"&allowUserQuestions=" +
"&isAudioOnly=" + isAudioOnly.toString() +
"&waitForRecording=false" +
"&allowRecording=" + isAllowedRecording.toString() +
"&hideTopBar=false";
LinkedHashMap result = this.omRestService.call(restURL, null);
roomId = ((Element)result.get("return")).getStringValue();
return Long.valueOf(roomId);
}
public Long updateRoomWithModerationAndQuestions(Boolean isAllowedRecording,
Boolean
isAudioOnly, Boolean isModeratedRoom, String roomname, Long
numberOfParticipent, Long
roomType, Long roomId)
throws Exception
{
String url = (String)this.omPluginSettings.getSomeInfo("url");
String port = (String)this.omPluginSettings.getSomeInfo("port");
String updateRoomId = "";
String restURL = "http://" + url + ":" + port + "/openmeetings/services
/RoomService/
updateRoomWithModerationAndQuestions?" +
"SID=" + getSessionId() +
"&room_id=" + roomId.toString() +
"&name=" + roomname.toString() +
"&roomtypes_id=" + roomType.toString() +
"&comment=" +
"&numberOfPartizipants=" + numberOfParticipent.toString() +
"&ispublic=false" +
"&appointment=false" +
"&isDemoRoom=false" +
"&demoTime=" +
"&isModeratedRoom=" + isModeratedRoom.toString() +
"&allowUserQuestions=";
LinkedHashMap result = this.omRestService.call(restURL, null);
log.info("addRoomWithModerationExternalTypeAndTopBarOption with ID: ",
((Element)result.get("return")).getStringValue());
updateRoomId = ((Element)result.get("return")).getStringValue();
return Long.valueOf(updateRoomId);
}
public String setUserObjectAndGenerateRoomHash(String username, String
firstname, String
lastname, String profilePictureUrl, String email, String externalUserId, String
externalUserType, Long room_id, int becomeModeratorAsInt, int
showAudioVideoTestAsInt)
throws Exception
{
String url = (String)this.omPluginSettings.getSomeInfo("url");
String port = (String)this.omPluginSettings.getSomeInfo("port");
String roomHash = null;
String restURL = "http://" + url + ":" + port + "/openmeetings/services
/UserService/
setUserObjectAndGenerateRoomHash?" +
"SID=" + getSessionId() +
"&username=" + username +
"&firstname=" + firstname +
"&lastname=" + lastname +
"&profilePictureUrl=" + profilePictureUrl +
"&email=" + email +
"&externalUserId=" + externalUserId +
"&externalUserType=" + externalUserType +
"&room_id=" + room_id +
"&becomeModeratorAsInt=" + becomeModeratorAsInt +
"&showAudioVideoTestAsInt=" + showAudioVideoTestAsInt;
LinkedHashMap result = this.omRestService.call(restURL, null);
roomHash = ((Element)result.get("return")).getStringValue();
return roomHash;
}
public String getSessionId() {
return this.sessionId;
}
public void setSessionId(String sessionId) {
this.sessionId = sessionId;
}
}
I want to call loginuser method from OmGateway class on Jsp Button Click Event. Kindly help me to solve this Error. And Help To Redirect and Integrate to openmeetings. Thank you In Advance.
Visit Atlassian Developers for help
Have you ever tried the Jira Plugin from the website:
http://openmeetings.apache.org/JiraPlugin.html
or is this actually the plugin code that you are posting here?
How to implement SCTP protocol between a gateway and a server with java ?
If your target is Java 7 never try to implement it. As Andrew and Tom stated its already implemented as a core feature.
No need, just use sctp:
https://github.com/RestComm/sctp
Handles most needs, works great.
Windows cannot support SCTP. if want to does with windows plz install sctp driver.Other wise use linux am adding simple client server example
Client.java
package mai;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import com.sun.nio.sctp.MessageInfo;
import com.sun.nio.sctp.SctpChannel;
public class Client
{
public static void main(String[] args)
{
try {
//SocketAddress socketAddress = new InetSocketAddress( 6050);
InetSocketAddress socketAddress = new InetSocketAddress("192.9.200.193", 4444);
System.out.println("open connection for socket [" + socketAddress + "]");
SctpChannel sctpChannel = SctpChannel.open(socketAddress, 1,1); //(socketAddress, 1 ,1 );
sctpChannel.bind(new InetSocketAddress(4444)); //6060
sctpChannel.connect(socketAddress, 1 ,1);
System.out.println("sctpChannel.getRemoteAddresses() = " + sctpChannel.getRemoteAddresses());
System.out.println("sctpChannel.getAllLocalAddresses() = " + sctpChannel.getAllLocalAddresses());
System.out.println("sctpChannel.isConnectionPending() = " + sctpChannel.isConnectionPending());
System.out.println("sctpChannel.isOpen() = " + sctpChannel.isOpen());
System.out.println("sctpChannel.isRegistered() = " + sctpChannel.isRegistered());
System.out.println("sctpChannel.provider() = " + sctpChannel.provider());
System.out.println("sctpChannel.association() = " + sctpChannel.association());
System.out.println("send bytes");
final ByteBuffer byteBuffer = ByteBuffer.allocate(64000);
//Simple M3ua ASP_Up message
byte [] message = new byte []{1,0,3,1,0,0,0,24,0,17,0,8,0,0,0,1,0,4,0,8,84,101,115,116};
final MessageInfo messageInfo = MessageInfo.createOutgoing(null, 0);
System.out.println("messageInfo = " + messageInfo);
System.out.println("messageInfo.streamNumber() = " + messageInfo.streamNumber());
byteBuffer.put(message);
byteBuffer.flip();
sctpChannel.send(byteBuffer, messageInfo);
System.out.println("close connection");
sctpChannel.close();
System.in.read();
} catch (Exception e) {
e.printStackTrace();
try {
System.in.read();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
}
Server.java
package mai;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.util.Arrays;
import com.sun.nio.sctp.MessageInfo;
import com.sun.nio.sctp.SctpChannel;
import com.sun.nio.sctp.SctpServerChannel;
public class Server {
static ByteBuffer rxBuffer;
public static void main(String[] args)throws Exception {
rxBuffer = ByteBuffer.allocateDirect(64000);
rxBuffer.clear();
rxBuffer.rewind();
rxBuffer.flip();
// SctpChannel xx=SctpChannel.open();
com.sun.nio.sctp.SctpChannel sc = com.sun.nio.sctp.SctpChannel.open();
SocketAddress serverSocketAddress = new InetSocketAddress(4444);
System.out.println("create and bind for sctp address");
SctpServerChannel sctpServerChannel = SctpServerChannel.open().bind(serverSocketAddress);
System.out.println("address bind process finished successfully");
SctpChannel sctpChannel;
while ((sctpChannel = sctpServerChannel.accept()) != null) {
System.out.println("client connection received");
System.out.println("sctpChannel.getRemoteAddresses() = " + sctpChannel.getRemoteAddresses());
System.out.println("sctpChannel.association() = " + sctpChannel.association());
MessageInfo messageInfo = sctpChannel.receive(rxBuffer=ByteBuffer.allocateDirect(64000) , null, null);
int len= messageInfo.bytes();
System.out.println("Server... Total bytes recived "+len);
System.out.println("Server... "+messageInfo);
rxBuffer.flip();
byte[] data = new byte[len];
rxBuffer.get(data);
rxBuffer.clear();
System.out.println("Server..... data "+Arrays.toString(data));
System.out.println("Server..... close connection");
}
}
}