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 was trying a mapreduce program in hadoop (Java version) , to find the mutual friends list from a json file . The json file content has the following pattern :
{"name":"abc","id":123} [{"name":"xyz","id":124},{"name":"def","id":125},{"name":"cxf","id":155}]
{"name":"cxf","id":155} [{"name":"xyz","id":124},{"name":"abc","id":123},{"name":"yyy","id":129}]
Pattern to be interpreted as follows :
friend json tab separated by array of related friends json's
Hence abc has xyz , def and cxf as friends
cxf has xyz abc and yyy as friends .
Given the above the mutual friends between abc and cxf is xyz .
tried to implement the same using mapreduce by creating custom writables , with the mapper emitting following key values , key being pair of friends and value being related friends of the first friend in the key (ie , pair of friends)
K->V
(abc,xyz) -> [xyz,def,cxf]
(abc,def) -> [xyz,def,cxf]
(abc,cxf) -> [xyz,def,cxf]
(cxf,xyz) -> [xyz,abc,yyy]
(cxf,abc) -> [xyz,abc,yyy]
(cxf,yyy) -> [xyz,abc,yyy]
The key here is actually a Custom writable , created a class which extends WritableComparable and i have overridden the compareTo method so that both these pairs (a,b) and (b,a) are same . But the problem i am facing is that the compareTo method is not invoked for all combinations of pairs and hence the reducer logic is failing.
Based on the above example , there are 6 K, V pairs emitted by the mapper . But compareTo is invoked only 5 times key1.compareTo(key2) , key2.compareTo(key3), key3.compareTo(key4),key4.compareTo(key5),,key5.compareTo(key6) .
Any idea why this is happening ?
Below is the code as per the logic suggested by f11ler
Driver class :
package com.facebook.updated;
import java.io.IOException;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.apache.log4j.Logger;
public class FacebookMain extends Configured implements Tool
{
Logger logger = Logger.getLogger(FacebookMain.class);
public static void main(String[] args) throws Exception {
System.exit(ToolRunner.run(new FacebookMain(), args));
}
#Override
public int run(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
logger.info("Running======>");
Job job = Job.getInstance();
job.setJarByClass(FacebookMain.class);
job.setJobName("FBApp");
job.setMapOutputKeyClass(Friend.class);
job.setMapOutputValueClass(Friend.class);
job.setOutputKeyClass(FriendPair.class);
job.setOutputValueClass(Friend.class);
job.setMapperClass(FacebookMapper.class);
job.setReducerClass(FacebookReducer.class);
job.setInputFormatClass(org.apache.hadoop.mapreduce.lib.input.TextInputFormat.class);
job.setOutputFormatClass(SequenceFileOutputFormat.class);
FileInputFormat.setInputPaths(job, new Path(args[0]));
FileOutputFormat.setOutputPath(job, new Path(args[1]));
boolean val = job.waitForCompletion(true);
return val ? 0 : 1;
}
}
The customWritables (used to represent a friend and friendpair)
package com.facebook.updated;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import lombok.Getter;
import lombok.Setter;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.WritableComparable;
import org.apache.log4j.Logger;
#Getter
#Setter
public class Friend implements WritableComparable<Friend> {
Logger logger = Logger.getLogger(Friend.class);
private IntWritable id;
private Text name;
public Friend() {
this.id = new IntWritable();
this.name = new Text();
}
#Override
public int compareTo(Friend arg0) {
int val = getId().compareTo(arg0.getId());
logger.info("compareTo Friend ======> " + arg0 + " and " + this + " compare is " + val);
return val;
}
#Override
public void readFields(DataInput in) throws IOException {
id.readFields(in);
name.readFields(in);
}
#Override
public void write(DataOutput out) throws IOException {
id.write(out);
name.write(out);
}
#Override
public boolean equals(Object obj) {
Friend f2 = (Friend) obj;
boolean val = this.getId().equals(f2.getId());
//logger.info("equals Friend ======> " + obj + " and " + this);
return val;
}
#Override
public String toString() {
return id + ":" + name + " ";
}
}
package com.facebook.updated;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import lombok.Getter;
import lombok.Setter;
import org.apache.hadoop.io.WritableComparable;
import org.apache.log4j.Logger;
#Getter
#Setter
public class FriendPair implements WritableComparable<FriendPair> {
Logger logger = Logger.getLogger(FriendPair.class);
private Friend first;
private Friend second;
public FriendPair() {
this.first = new Friend();
this.second = new Friend();
}
public FriendPair(Friend f1, Friend f2) {
this.first = f1;
this.second = f2;
}
#Override
public int compareTo(FriendPair o) {
logger.info("compareTo FriendPair ======> " + o + " and " + this);
FriendPair pair2 = o;
int cmp = -1;
if (getFirst().compareTo(pair2.getFirst()) == 0 || getFirst().compareTo(pair2.getSecond()) == 0) {
cmp = 0;
}
if (cmp != 0) {
// logger.info("compareTo FriendPair ======> " + o + " and " + this
// + " comparison is " + cmp);
return cmp;
}
cmp = -1;
if (getSecond().compareTo(pair2.getFirst()) == 0 || getSecond().compareTo(pair2.getSecond()) == 0) {
cmp = 0;
}
// logger.info("compareTo FriendPair ======> " + o + " and " + this +
// " comparison is " + cmp);
// logger.info("getFirst() " + getFirst());
// logger.info("pair2.getFirst() " + pair2.getFirst());
// logger.info("getFirst().compareTo(pair2.getFirst()) " +
// getFirst().compareTo(pair2.getFirst()));
// logger.info("getFirst().compareTo(pair2.getSecond()) " +
// getFirst().compareTo(pair2.getSecond()));
// logger.info("getSecond().compareTo(pair2.getFirst()) " +
// getSecond().compareTo(pair2.getFirst()));
// logger.info("getSecond().compareTo(pair2.getSecond()) " +
// getSecond().compareTo(pair2.getSecond()));
// logger.info("pair2.getSecond() " + pair2.getSecond());
// logger.info("getSecond() " + getSecond());
// logger.info("pair2.getFirst() " + pair2.getFirst());
// logger.info("pair2.getSecond() " + pair2.getSecond());
return cmp;
}
#Override
public boolean equals(Object obj) {
FriendPair pair1 = this;
FriendPair pair2 = (FriendPair) obj;
boolean eq = false;
logger.info("equals FriendPair ======> " + obj + " and " + this);
if (pair1.getFirst().equals(pair2.getFirst()) || pair1.getFirst().equals(pair2.getSecond()))
eq = true;
if (!eq) {
// logger.info("equals FriendPair ======> " + obj + " and " + this +
// " equality is " + eq);
return false;
}
if (pair1.getSecond().equals(pair2.getFirst()) || pair1.getSecond().equals(pair2.getSecond()))
eq = true;
// logger.info("equals FriendPair ======> " + obj + " and " + this +
// " equality is " + eq);
return eq;
}
#Override
public void readFields(DataInput in) throws IOException {
first.readFields(in);
second.readFields(in);
}
#Override
public void write(DataOutput out) throws IOException {
first.write(out);
second.write(out);
}
#Override
public String toString() {
return "[" + first + ";" + second + "]";
}
#Override
public int hashCode() {
logger.info("hashCode FriendPair ======> " + this);
return first.getId().hashCode() + second.getId().hashCode();
}
}
Mapper and Reducer
package com.facebook.updated;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.log4j.Logger;
import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
import com.mongodb.util.JSON;
public class FacebookMapper extends Mapper<LongWritable, Text, Friend, Friend> {
Logger log = Logger.getLogger(FacebookMapper.class);
#Override
protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, Friend, Friend>.Context context)
throws IOException, InterruptedException {
String line = value.toString();
StringTokenizer st = new StringTokenizer(line, "\t");
String person = st.nextToken();
String friends = st.nextToken();
BasicDBObject personObj = (BasicDBObject) JSON.parse(person);
BasicDBList friendsList = (BasicDBList) JSON.parse(friends);
List<Friend> frndJavaList = new ArrayList<>();
for (Object frndObj : friendsList) {
frndJavaList.add(getFriend((BasicDBObject) frndObj));
}
Friend frnd = getFriend(personObj);
Friend[] array = frndJavaList.toArray(new Friend[frndJavaList.size()]);
for (Friend f : array) {
log.info("Map output is " + f + " and " + frnd);
context.write(f, frnd);
}
}
private static Friend getFriend(BasicDBObject personObj) {
Friend frnd = new Friend();
frnd.setId(new IntWritable(personObj.getInt("id")));
frnd.setName(new Text(personObj.getString("name")));
frnd.setHomeTown(new Text(personObj.getString("homeTown")));
return frnd;
}
}
package com.facebook.updated;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.log4j.Logger;
public class FacebookReducer extends Reducer<Friend, Friend, FriendPair, Friend> {
Logger log = Logger.getLogger(FacebookReducer.class);
#Override
protected void reduce(Friend friend, Iterable<Friend> vals,
Reducer<Friend, Friend, FriendPair, Friend>.Context context) throws IOException, InterruptedException {
List<Friend> friends = new ArrayList<>();
for (Friend frnd : vals) {
friends.add(frnd);
}
log.info("Reducer output is " + friend + " and values are " + friends);
if (friends.size() == 2) {
FriendPair key = new FriendPair(friends.get(0), friends.get(1));
context.write(key, friend);
} else {
//log.info("Size of friends is not 2 key is " + friend + " and values are " + friends);
}
}
}
Input json file containing 2 lines
{"name":"abc","id":123} [{"name":"xyz","id":124},{"name":"def","id":125},{"name":"cxf","id":155}]
{"name":"cxf","id":155} [{"name":"xyz","id":124},{"name":"abc","id":123},{"name":"yyy","id":129}]
Output of reducer
(abc,abc)->xyz
compareTo method is required for sorting, this relation should be transitive. This mean that if a > b and b > c then a > c. Probably this is not true for your implementation.
Why you generate this kind of records in mapper?
If "being a friend" is a symmetric relation you can simply do a mapper-only job with this logic (pseudo-code):
for(int i = 0; i < values.length; ++i)
for(int j = 0; j < values.length; ++j)
if (i ==j)
continue
emmit (values[i], values[j]), key
Update:
If this is not symmetric (which means that "xyz has friend abc" not follows from "abc has friend xyz") then we need reverse records:
Mapper:
for(int i = 0; i < values.length; ++i)
emmit values[i], key
Reducer (same as mapper before):
for(int i = 0; i < values.length; ++i)
for(int j = 0; j < values.length; ++j)
if (i ==j)
continue
emmit (values[i], values[j]), key
Update2:
Lets see how this algorithm works with your example:
The result of mapper:
xyz -> abc
def -> abc
cxf -> abc
xyz -> cxf
abc -> cxf
yyy -> cxf
Mapreduce wiil group this values by key, so the input of reducer:
xyz -> [abc,cxf]
def -> [abc]
cxf -> [abc]
abc -> [cxf]
yyy -> [cxf]
In reducer we do a nested loop by values, but skip comparing with self. Result:
(abc, cxf) -> xyz
This is what we want to get.
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
I am making a bukkit plugin that uses a config to store data, but when I use plugin.getConfig() I get a NullPointer. I think is it because of the reference to plugin, but how can I fix that?
The error is in the Storage class where I use the plugin. Instance
Main: http://pastebin.com/d3bFXbiR
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.block.Block;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.plugin.java.JavaPlugin;
public class Main extends JavaPlugin {
public void onEnable() {
final FileConfiguration config = this.getConfig();
config.options().copyDefaults(true);
saveConfig();
}
#Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if (cmd.getName().equalsIgnoreCase("BlockCmd")) {
if (sender.isOp()) {
if (args.length < 1) {
sender.sendMessage(ChatColor.RED + "/BlockCmd [command] | Kijk naar het blok dat je wilt cmd'en");
} else {
Block block = ((LivingEntity) sender).getTargetBlock(null, 100);
Location bl = block.getLocation();
StringBuilder sb = new StringBuilder();
for (int i = 1; i < args.length; i++) {
sb.append(args[i]).append(" ");
}
String allArgs = sb.toString().trim();
Storage.addClickCmd(bl, allArgs);
sender.sendMessage(ChatColor.GRAY + "[BlockCommand] " + ChatColor.BLUE + "Successfully added a command to the block");
sender.sendMessage(ChatColor.GRAY + "[BlockCommand] " + ChatColor.BLUE + "Command: " + ChatColor.GREEN + allArgs);
}
} else {
sender.sendMessage(ChatColor.RED + "Dit is alleen voor operators");
}
}
return true;
}
#EventHandler
public void onRightClick(PlayerInteractEvent event) {
Player p = event.getPlayer();
if ((event.getAction() == Action.RIGHT_CLICK_BLOCK) || (event.getAction() == Action.LEFT_CLICK_BLOCK)) {
Location loc = event.getClickedBlock().getLocation();
int x = loc.getBlockX();
int y = loc.getBlockY();
int z = loc.getBlockZ();
String w = p.getWorld().getName();
String cCc = "Click.Cmd." + w + "." + x + "." + y + "." + z;
if (Storage.getClickCmd(w, x, y, z) != null) {
String cCc2 = Storage.getString(cCc);
p.performCommand(cCc2);
}
}
}
}
Storage: http://pastebin.com/wvQS3n57
import org.bukkit.Location;
import org.bukkit.event.Listener;
public class Storage implements Listener {
static Main plugin;
public Storage(Main instance) {
plugin = instance;
}
public static void addClickCmd(Location loc, String text) {
int x = loc.getBlockX();
int y = loc.getBlockY();
int z = loc.getBlockZ();
String w = loc.getWorld().getName();
if (plugin != null && plugin.getConfig() != null) {
System.out.println("Check");
}
//if(plugin.getConfig() !=null){}
//plugin.getConfig().set("Click.Cmd." + w + "." + x + "." + y + "." + z, text);
}
public static String getClickCmd(String w, int x, int y, int z) {
return plugin.getConfig().getString("Click.Cmd." + w + "." + x + "." + y + "." + z);
}
public static String getString(String path) {
return plugin.getConfig().getString(path);
}
}
You use static Main plugin; but it is never initialized, since you never instantiate a Storage object, only use its static functions.
In your plugin class create a Storage object, and initialize it in the onEnable method, passing the plugin for its constructor. For example:
public class Main extends JavaPlugin {
Storage myStorage = null;
public void onEnable() {
final FileConfiguration config = this.getConfig();
config.options().copyDefaults(true);
saveConfig();
myStorage = new Storage(this);
}
Later in your plugin class use this object instead - and best to make your static methods in Storage (as well as the plugin member) non-static, since you will always need to create an instance to use the plugin set in the constructor.
I think this article gives a nice, basic overview about class members.
i want to create a simple java code that display all the security Providers with :
Name
info
service Type
Algorithm
Main Activity.java
import java.io.ObjectInputStream.GetField;
import java.security.Provider;
import java.security.Provider.Service;
import java.security.Security;
public class MainActivity {
public static void main(String[] args) {
System.out.println("Availble Providers are:");
Provider[] providerList = Security.getProviders();
for (int i = 0; i < providerList.length; i++) {
System.out.println("[" + (i + 1) + "] - Name: "
+ providerList[i].getName());
System.out.println("Information:\n" + providerList[i].getInfo());
System.out
.print("Here are all providers with types of service and algorithm provided:\n");
}
for (int i = 0; i < serviceList.length; i++) {
System.out.println("- Name: " + providerList[i].getName() + "\n");
System.out.print("Service Type: " + serviceList[i].getType()
+ "Algorithm: " + serviceList[i].getAlgorithm());
}
}
}
before the second for loop i need to initialize the services to be able to call the service type and Algorithm.
You need your second loop to be inside the first loop as you need the current provider so you can call its getServices method. Something like:
import java.security.Provider;
import java.security.Provider.Service;
import java.security.Security;
import java.util.Set;
public class MainActivity
{
public static void main(String[] args)
{
Provider [] providerList = Security.getProviders();
for (Provider provider : providerList)
{
System.out.println("Name: " + provider.getName());
System.out.println("Information:\n" + provider.getInfo());
Set<Service> serviceList = provider.getServices();
for (Service service : serviceList)
{
System.out.println("Service Type: " + service.getType() + " Algorithm " + service.getAlgorithm());
}
}
}
}