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
Related
How to generate custom jvm-cucumber HTML, send it through Jenkins and also ftp the JSON results? This results generation should happen after the entire mvn cucumber suite execution so that I can capture passed / failed results from the json that will be generated after test execution is complete.
I used extended cucumber to achieve this -
Here is the extended cucumber code and create this class in your library -
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import com.github.mkolisnyk.cucumber.runner.AfterSuite;
import com.github.mkolisnyk.cucumber.runner.BeforeSuite;
import org.junit.runner.Description;
import org.junit.runner.Runner;
import org.junit.runner.notification.RunNotifier;
import cucumber.api.junit.Cucumber;
public class ExtendedCucumberRunner extends Runner {
private Class clazz;
private Cucumber cucumber;
public ExtendedCucumberRunner(Class clazzValue) throws Exception {
clazz = clazzValue;
cucumber = new Cucumber(clazzValue);
}
#Override
public Description getDescription() {
return cucumber.getDescription();
}
private void runPredefinedMethods(Class annotation) throws Exception {
if (!annotation.isAnnotation()) {
return;
}
Method[] methodList = this.clazz.getMethods();
for (Method method : methodList) {
Annotation[] annotations = method.getAnnotations();
for (Annotation item : annotations) {
if (item.annotationType().equals(annotation)) {
method.invoke(null);
break;
}
}
}
}
#Override
public void run(RunNotifier notifier) {
try {
runPredefinedMethods(BeforeSuite.class);
} catch (Exception e) {
e.printStackTrace();
}
cucumber.run(notifier);
try {
runPredefinedMethods(AfterSuite.class);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Here is runner class code that will be used to start with the mvn command and this will capture the summary based on the cucumber tags starting with #SUMMARY-
import libs.ExtendedCucumberRunner;
import libs.FTP;
import libs.RemoteSSH;
import com.github.mkolisnyk.cucumber.reporting.CucumberResultsOverview;
import com.github.mkolisnyk.cucumber.runner.AfterSuite;
import com.github.mkolisnyk.cucumber.runner.BeforeSuite;
import com.github.mkolisnyk.cucumber.runner.ExtendedCucumberOptions;
import cucumber.api.CucumberOptions;
import org.apache.commons.io.FileUtils;
import org.junit.runner.RunWith;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.*;
import static libs.BaseTest.tagCounts;
import static com.automation.steps.Common.failedCount;
#RunWith(ExtendedCucumberRunner.class)
#ExtendedCucumberOptions(jsonReport = "target/Destination/cucumber.json",
overviewReport = true,
outputFolder = "target/ext-cucumber-results"
,retryCount = 0)
#CucumberOptions(
plugin = {"pretty","html:target/Destination","json:target/Destination/cucumber.json"},
strict = true,
monochrome = true
)
public class Runner {
#BeforeSuite
public static void manageResults() throws IOException {
String directory=System.getProperty("user.dir");
if (new File("target/Destination/cucumber.json").exists()) {
String contents = new String(Files.readAllBytes(Paths.get("target/Destination/cucumber.json"))).toString().trim();
if (!contents.equals("")) {
long timestamp = System.currentTimeMillis() / 1000;
FileUtils.copyFile(new File("target/Destination/cucumber.json"), new File("target/Destination/cucumber_" + timestamp + ".json"));
}
}
}
#AfterSuite
public static void copy_json_generate_report() throws Exception {
String directory=System.getProperty("user.dir");
CucumberResultsOverview results = new CucumberResultsOverview();
results.setOutputDirectory("target/ext-cucumber-results");
results.setOutputName("cucumber-results");
results.setSourceFile(directory+"/target/Destination/cucumber.json");
results.execute();
String format_tag_name="";
if(System.getenv("TAG_NAME")==null){
format_tag_name="Local--";
}else {
format_tag_name = System.getenv("TAG_NAME").
replaceAll("#", "").replaceAll(",", "-")
.replaceAll("\\[", "")
.replaceAll("]", "");
}
String destination_path = "";
Date today = Calendar.getInstance().getTime();
SimpleDateFormat unix_format = new SimpleDateFormat("yyyyMMdd");
long timestamp = System.currentTimeMillis() / 1000;
if (failedCount==0) {
destination_path ="/tmp/QA_RESULTS/"+unix_format.format(today)+"/"+format_tag_name+"_" + timestamp + ".json";
}else{
destination_path ="/tmp/QA_RESULTS/"+unix_format.format(today)+"/"+format_tag_name+"_" + timestamp + "--F.json";
}
System.out.println("After class is being run now- to copy json files!!!");
if (new File(directory+"/target/Destination/cucumber.json").exists()) {
System.out.println(directory+"/target/Destination/cucumber.json --exits!");
// CommonUtils.createFile(GenerateHTMLReport(),"Destination/CucumberSummaryReport.html");
String contents = new String(Files.readAllBytes(Paths.get(directory+"/target/Destination/cucumber.json"))).toString().trim();
if (!contents.equals("")) {
RemoteSSH ssh = new RemoteSSH();
List<String> check_file_commands = Arrays.asList("mkdir -p /tmp/QA_RESULTS/"+unix_format.format(today) );
List<String> check_file_logs = ssh.SSHClient(check_file_commands);
String local_path = directory+"/target/Destination/cucumber.json";
System.out.println(local_path);
FTP ftp = new FTP();
ftp.SCPUpload(local_path,destination_path);
}else{
System.out.println("File is empty!");
}
}
try {
Runtime.getRuntime().exec("TASKKILL /F /IM xxx.exe");
} catch (IOException e) {
System.out.println("Killing xxxx.exe error out");
}
}
public static String GenerateHTMLReport(){
String html_string = "<!-- CSS Code: Place this code in the document's head (between the 'head' tags) -->\n" +
"<style>\n" +
"table.GeneratedTable {\n" +
" width: 100%;\n" +
" background-color: #ffffff;\n" +
" border-collapse: collapse;\n" +
" border-width: 2px;\n" +
" border-color: #ffcc00;\n" +
" border-style: solid;\n" +
" color: #000000;\n" +
"}\n" +
"\n" +
"table.GeneratedTable td, table.GeneratedTable th {\n" +
" border-width: 2px;\n" +
" border-color: #ffcc00;\n" +
" border-style: solid;\n" +
" padding: 3px;\n" +
"}\n" +
"\n" +
"table.GeneratedTable thead {\n" +
" background-color: #ffcc00;\n" +
"}\n" +
"</style>\n" +
"\n" +
"<!-- HTML Code: Place this code in the document's body (between the 'body' tags) where the table should appear -->\n" +
"<table class=\"GeneratedTable\">\n" +
" <thead>\n" +
" <tr>\n" +
" <th>Functionality Group</th>\n" +
" <th>Passed</th>\n" +
" <th>Passed With Warning</th>\n" +
" <th>Failed</th>\n" +
" <th>Script Issue</th>\n" +
" <th>Env Issue</th>\n" +
" <th>Warning</th>\n" +
" </tr>\n" +
" </thead>\n" +
" <tbody>\n" +
" <tr>\n";
System.out.println(tagCounts.size());
for (Map.Entry<String,List<Integer>> entry : tagCounts.entrySet()) {
html_string = html_string +
" <tr><td>" + entry.getKey() + "</td>\n" +
" <td>" + entry.getValue().get(0) + "</td>\n" +
" <td>" + entry.getValue().get(1) + "</td>\n" +
" <td>" + "Script Issue Value" + "</td>\n" +
" <td>" + "Env Issue Value" + "</td></tr>\n";
}
html_string = html_string +
" </tr>\n" +
" </tbody>\n" +
"</table>\n" +
"\n";
return html_string;
}
}
Now in the Jenkins configure, add the following to the content section of editable email configuration add-in-
<html>
<body>
<p>Pls refer the below results-</p>
${BUILD_URL}/cucumber-html-reports/overview-features.html
<p>Note: Copy and paste the above link in chrome or Firefox. The report won't work in IE.</p>
</body>
</html>
${FILE,path="target/CucumberSummaryReport.html"}
${FILE,path="target/ext-cucumber-results/cucumber-results-feature-overview.html"}
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.
I want to listen to chat and if a player says the random number it will broadcast saying the player won. I can't get it to recognise the int result (random number).
I think I have to make it a global static variable but have no idea how because if I try that says it's an illegal modifier.
Code:
package me.harry.learning;
import java.util.Random;
import java.util.logging.Logger;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.plugin.java.JavaPlugin;
public class pear extends JavaPlugin implements Listener
{
Logger myLogger = Bukkit.getLogger();
#Override
public void onEnable()
{
myLogger.info("Giveaway start-up has been successful!");
Bukkit.getServer().getPluginManager().registerEvents(this, this);
}
#Override
public void onDisable()
{
myLogger.info("Giveaway shut-down has been successful");
}
public boolean onCommand(CommandSender theSender, Command cmd, String commandLabel, String[] args)
{
if(theSender instanceof Player)
{
Player player = (Player) theSender;
//giveaway {start} {mxnumber}
if(player.hasPermission("giveaway.admin"))
{
if(commandLabel.equalsIgnoreCase("giveaway"))
{
if(args.length == 2)
{
if(args[0].equalsIgnoreCase("stop"))
{
theSender.sendMessage(ChatColor.GREEN + "[Giveaway] " + ChatColor.AQUA + "Giveaway has stopped!");
return false;
}
else if(args[0].equalsIgnoreCase("start"))
{
try
{
int numberStart = 0;
int numberEnd = (Integer.parseInt(args[1]));
Random random = new Random();
int result = numberStart + random.nextInt(numberEnd);
theSender.sendMessage(ChatColor.GREEN + "[Giveaway] " + ChatColor.AQUA + "Giveaway commencing...");
theSender.sendMessage(ChatColor.GREEN + "[Giveaway] " + ChatColor.AQUA + "The winning number is " + result);
Bukkit.broadcastMessage(ChatColor.GREEN + (ChatColor.BOLD + "A giveaway has begun ranging from 0 - " + numberEnd));
}
catch(NumberFormatException exception)
{
player.sendMessage(ChatColor.GREEN + "[Giveaway] " + ChatColor.RED + args[1] + ChatColor.AQUA + " is not a valid number!");
}
}
else player.sendMessage(ChatColor.GREEN + "[Giveaway] " + ChatColor.AQUA + "Unknown Arguments, try /giveaway help");
}
else player.sendMessage(ChatColor.GREEN + "[Giveaway] " + ChatColor.AQUA + "Unknown Arguments, try /giveaway help");
}
else player.sendMessage(ChatColor.GREEN + "[Giveaway] " + ChatColor.AQUA + "Giveaway 1.0 made by Herry");
}
else player.sendMessage(ChatColor.RED + "No Permission");
}
return true;
}
#EventHandler
public void onPlayerChat(AsyncPlayerChatEvent winningPlayer)
{
if(winningPlayer.getMessage().contains(result))
{
Bukkit.broadcastMessage(ChatColor.BOLD + (ChatColor.AQUA + "" + winningPlayer + ChatColor.GREEN + " has won the giveaway!"));
}
}
}
Does anyone know how I could possibly do this? Obviously I'm gonna need a stop command so maybe a loop that I can cancel with a command? Is it better to use seperate classes for sub-commands? Do I need a BukkitRunnable for the giveaway loop?
You can't make variables static inside of a function in Java like you can in C. If you want to make a variable static in Java, then it must be declared outside of a function.
If you want to access a variables outside of the function, you should do something like this:
public class MyClass {
public String myString;
public void a() {
myString = "aaa";
}
public void b() {
System.out.println(myString);
}
}
here is my program: basically i have an xml file and from that file i have to decode a base64 string but i keep getting NullPointerException..please help! code is as follows...
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import org.apache.commons.codec.binary.Base64;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Arrays;
public class main {
public static void main(String[] args) throws Exception {
SAXParserFactory parserFactor = SAXParserFactory.newInstance();
SAXParser parser = parserFactor.newSAXParser();
SAXHandler handler = new SAXHandler();
//parser.parse(ClassLoader.getSystemResourceAsStream("ATMSPopulateDMSData.xml"),
// handler);
parser.parse(new FileInputStream("C:\\Users\\qta6754\\workspace\\Java_Dev\\XML64_Decoded\\ATMSMessageData.xml"), handler);
for (NeededInfo emp : handler.empList) {
System.out.println(emp);
}
}
}
class SAXHandler extends DefaultHandler {
List<NeededInfo> empList = new ArrayList<>();
NeededInfo emp = null;
String content = null;
String did = null;
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
switch (qName) {
case "dMSDeviceStatus":
emp = new NeededInfo();
emp.id = attributes.getValue("id");
emp.Read();
break;
}
}
public void characters(char[] ch, int start, int length) throws SAXException {
content = String.copyValueOf(ch, start, length).trim();
}
}
class NeededInfo {
String id;
String firstName;
String lastName;
String location;
String organization_id;
String operator_id;
String device_id;
String dms_device_status;
String dms_current_message;
String last_comm_time;
String date;
String time;
public String toString() {
//return firstName + " " + lastName + "(" + id + ")" + location+date+time+device_name;
return "Organization id: " + organization_id + "\n" + "Operator id: " + operator_id + "\n" + "Device id: " + device_id + "\n"
+ "Dms Device Status: " + dms_device_status + "\n" + "Dms Current Message: " + dms_current_message + "\n" + "Last Comm Time" + "\n"
+ "Time: " + time + "\n" + "Date: " + date + "\n" + "decoded string is: " + "\n" + "-------------------------------------";
}
public void Read() {
byte[] byteArray = Base64.decodeBase64(dms_current_message.getBytes());
String decodedString = new String(byteArray);
System.out.print("The decoded message is: " + decodedString);
// return decodedString;
}
}
It's hard to guess where you're getting your error, but I'm assuming here:
byte[] byteArray = Base64.decodeBase64(dms_current_message.getBytes());
I don't see dms_current_message being initialized ever, yet you're calling a method on it, which would definitely result in the null pointer exception.
Your Read method accesses the dms_current_message which is never initialized in all the code you included in your question.
byte[] byteArray = Base64.decodeBase64(dms_current_message.getBytes());
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?