Java: Using TreeSet with a Class type - treeset

I am having problems using the TreeSet to sort my HashMap. Following is the code that I have:
private static HashMap<OddMove, Integer> sortHashMap(
HashMap<OddMove, Integer> hm) {
Map<OddMove, Integer> tempMap = new HashMap<OddMove, Integer>();
for (OddMove wsState : hm.keySet()) {
tempMap.put(wsState, hm.get(wsState));
}
List<OddMove> mapKeys = new ArrayList<OddMove>(tempMap.keySet());
List<Integer> mapValues = new ArrayList<Integer>(tempMap.values());
HashMap<OddMove, Integer> sortedMap = new LinkedHashMap<OddMove, Integer>();
TreeSet<OddMove> sortedSet = new TreeSet<OddMove>(mapKeys);
Object[] sortedArray = sortedSet.toArray();
int size = sortedArray.length;
for (int i = 0; i < size; i++) {
sortedMap.put(mapKeys.get(mapValues.indexOf(sortedArray[i])),
(Integer) sortedArray[i]);
}
return sortedMap;
}
Following is the error that i am getting:
ABORTING: Exception in odd.UEPlayer3.choseMove()
java.lang.ClassCastException: odd.OddMove cannot be cast to java.lang.Comparable
at java.util.TreeMap.compare(TreeMap.java:1188)
at java.util.TreeMap.put(TreeMap.java:531)
at java.util.TreeSet.add(TreeSet.java:255)
at java.util.AbstractCollection.addAll(AbstractCollection.java:334)
at java.util.TreeSet.addAll(TreeSet.java:312)
at java.util.TreeSet.<init>(TreeSet.java:160)
at odd.UEPlayer3.sortHashMap(UEPlayer3.java:196)
at odd.UEPlayer3.chooseMove(UEPlayer3.java:101)
at boardgame.Client.playMove(Client.java:109)
at boardgame.Client.processMessage(Client.java:86)
at boardgame.Client.clientLoop(Client.java:177)
at boardgame.Client.run(Client.java:73)
at java.lang.Thread.run(Thread.java:722)
Would really appreciate some help

I'm guessing OddMove is a custom class you've written. If that's the case, you'll need to update it in order to implement Comparable Interface.

Related

groupby with spark java

i can read data from csv with spark, but i don't know how to groupBy with specific array. I want to groupBy 'Name'. This is my code :
public class readspark {
public static void main(String[] args) {
final ObjectMapper om = new ObjectMapper();
System.setProperty("hadoop.home.dir", "D:\\Task\\winutils-master\\hadoop-3.0.0");
SparkConf conf = new SparkConf()
.setMaster("local[3]")
.setAppName("Read Spark CSV")
.set("spark.driver.host", "localhost");
JavaSparkContext jsc = new JavaSparkContext(conf);
JavaRDD<String> lines = jsc.textFile("D:\\Task\\data.csv");
JavaRDD<DataModel> rdd = lines.map(new Function<String, DataModel>() {
#Override
public DataModel call(String s) throws Exception {
String[] dataArray = s.split(",");
DataModel dataModel = new DataModel();
dataModel.Name(dataArray[0]);
dataModel.ID(dataArray[1]);
dataModel.Addres(dataArray[2]);
dataModel.Salary(dataArray[3]);
return dataModel;
}
});
rdd.foreach(new VoidFunction<DataModel>() {
#Override
public void call(DataModel stringObjectMap) throws Exception {
System.out.println(om.writeValueAsString(stringObjectMap));
}
}
);
}
Spark provides the group by functionality directly:
JavaPairRDD<String, Iterable<DataModel>> groupedRdd = rdd.groupBy(dataModel -> dataModel.getName());
This returns a pair rdd where the key is the Name (determined by the lambda provided to group by) and the value is data models with that name.
If you want to change the group by logic, all you need to do is provide corresponding lambda.

Lifecycle of #After method

I am trying to gather some information after every test method, and would like to analyze the gathered information after the test class completes. So, I have a private member variable, a list which I would like to add to after every test method completes. However, at the end of the day, the member variable always remains null.
Note: My test class implements Callable interface.
Here is my code snippet:
{
private List<String statisticsCollector;
private JUnitCore core = null;
private int x = 0;
public MyLoadTest() {
this.core = new JUnitCore();
this.statisticsCollector = new ArrayList<String>();
}
#Override
public List<String> call() {
log.info("Starting a new thread of execution with Thread# -" + Thread.currentThread().getName());
core.run(this.getClass());
return getStatisticsCollector(); // this is always returing a list of size 0
}
#After
public void gatherSomeStatistics() {
x = x+1;
String sb = new String("Currently executing ----" + x);
log.info("Currently executing ----" + x);
addToStatisticsCollector(sb);
}
#Test
#FileParameters(value = "classpath:folder/testB.json", mapper = MyMapper.class)
public void testB(MarsTestDefinition testDefinition) {
runTests(testDefinition);
}
#Test
#FileParameters(value = "classpath:folder/testA.json", mapper = MyMapper.class)
public void testA(MyDefinition testDefinition) {
runTests(testDefinition);
}
public List<String> getStatisticsCollector() {
return this.statisticsCollector;
}
public void addToStatisticsCollector(String sb) {
this.statisticsCollector.add(sb);
}
}
So, why is it always getting reset, even though I am appending to the list in my #After annotated method?
Any help will be highly appreciated. Thanks
Try with following code, is it working ?
private static List<String> statisticsCollector = new ArrayList<String>();
private JUnitCore core = null;
private int x = 0;
public MyLoadTest() {
this.core = new JUnitCore();
}
public List<String> getStatisticsCollector() {
return statisticsCollector;
}

.NET Core Configuration Serialization

Is there a way to serialize an object so that it could then be rehydrated by .Net Core Configuration Binder?
Basically, I'd like to get this Test to pass:
[Test]
public void Can_Serialize_And_Rehydrate()
{
var foo = new Foo{ Prop1 = 42; Prop2 = "Test" }
Dictionary<string, string> serialized = Serialize(Foo);
var deserializedFoo = new Foo();
new ConfigurationBuilder()
.AddInMemoryCollection(serialized)
.Build()
.Bind(deserializedFoo);
Assert.AreEqual(deserializedFoo.Prop1, 42);
Assert.AreEqual(deserializedFoo.Prop2, "Test");
}
Is there a Serializer out-of-the-box, or am I'm going to need to write my own Serialize() method?
AddInMemoryCollection's signature is like below, so why are you trying to serialize your dictionary here? You could just use it as it is.
public static IConfigurationBuilder AddInMemoryCollection(
this IConfigurationBuilder configurationBuilder,
IEnumerable<KeyValuePair<string, string>> initialData)
If you like to know more about how to test your custom configurations, I would suggest to look here:
https://github.com/aspnet/Configuration/blob/1.0.0/test/Microsoft.Extensions.Configuration.Binder.Test/ConfigurationBinderTests.cs
I was able to get this working by "hijacking" a JsonConfigurationProvider and plugging serialized Json directly into it. Not sure if this is the best way, but it does work:
public class ConfigurationSerializer
{
private class CustomJsonProvider : JsonConfigurationProvider
{
public CustomJsonProvider() : base(new JsonConfigurationSource())
{
}
public IDictionary<string, string> GetData(Stream s)
{
Load(s);
// Return the Configuration Dictionary
return Data;
}
}
public Dictionary<string, string> Serialize(object o)
{
var serialized =
JsonConvert.SerializeObject(
o,
new JsonSerializerSettings {NullValueHandling = NullValueHandling.Ignore});
using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(serialized)))
{
var jsonProvider = new CustomJsonProvider();
return jsonProvider
.GetData(ms)
.ToDictionary(key => key.Key, value => value.Value);
}
}
}

Java Reflection Problem

Hi I am currently doing my final year project; I need to develop an algorithm visualization tool. I need to cater for user-defined algo; that is animate the algorithm the user types in a text-editor provided in my tool.
I am using the Java Compiler API to compile the code that the user has typed and saved. My tool offers a set of classes that the user can use in his/her algo.
For example:
myArray(this class is provided by my tool)
import java.awt.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.accessibility.AccessibleContext;
import javax.swing.*;
public class myArray extends JComponent {
int size = 0;
int count = 0;
int[]hold;
Thread th;
public myArray(int[]arr)//pass user array as parameter
{
//th = new Thread();
size=arr.length;
hold = arr;//make a copy of the array so as to use later in swap operation
}
public int length()
{
return hold.length;
}
public void setAccessibleContext(AccessibleContext accessibleContext) {
this.accessibleContext = accessibleContext;
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
this.setPreferredSize(new Dimension(360,100));
for(int i=1; i<=size; i++)
{
g2d.drawRect((i*30), 30, 30, 50);
}
for(int i=1; i<=size; i++)
{
g2d.drawString(Integer.toString(hold[i-1]), (i*30)+15, 30+25);
}
}
public void set(int i, int j)//position of the two elements to swap in the array
{
try {
th.sleep(2000);//sleep before swapping because else user won't see original array since it would swap and then sleep
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int temp = hold[i];
hold[i] = hold[j];
hold[j] = temp;
hold[i]=j;
this.repaint();//can use eapint with a class that extends JPanel
}
public void swap(int i, int j)//position of the two elements to swap in the array
{
try {
th.sleep(2000);//sleep before swapping because else user won't see original array since it would swap and then sleep
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int temp = hold[i];
hold[i] = hold[j];
hold[j] = temp;
this.repaint();//can use eapint with a class that extends JPanel
}
public int get(int pos)
{
return hold[pos];
}
}
This is a portion of my GUI that will cause the compilation:
JavaCompiler jc = null;
StandardJavaFileManager sjfm = null;
File javaFile = null;
String[] options = null;
File outputDir = null;
URL[] urls = null;
URLClassLoader ucl = null;
Class clazz = null;
Method method = null;
Object object = null;
try
{
jc = ToolProvider.getSystemJavaCompiler();
sjfm = jc.getStandardFileManager(null, null, null);
File[] files = new File[1];
//files[0] = new File("C:/Users/user/Documents/NetBeansProjects/My_Final_Year_Project/myArray.java");
//files[1] = new File("C:/Users/user/Documents/NetBeansProjects/My_Final_Year_Project/Tool.java");
files[0] = new File("C:/Users/user/Documents/NetBeansProjects/My_Final_Year_Project/userDefined.java");
// getJavaFileObjects’ param is a vararg
Iterable fileObjects = sjfm.getJavaFileObjects(files);
jc.getTask(null, sjfm, null, null, null, fileObjects).call();
// Add more compilation tasks
sjfm.close();
options = new String[]{"-d", "C:/Users/user/Documents/NetBeansProjects/My_Final_Year_Project"};
jc.getTask(null, sjfm, null, Arrays.asList(options), null, fileObjects).call();
outputDir = new File("C:/Users/user/Documents/NetBeansProjects/My_Final_Year_Project");
urls = new URL[]{outputDir.toURL()};
ucl = new URLClassLoader(urls);
clazz = ucl.loadClass("userDefined");
method = clazz.getMethod("user", null);
object = clazz.newInstance();
Object ob = method.invoke(object, null);
}
This is an example of a user-defined algo(userDefined.java):
import java.awt.*;
import javax.swing.*;
public class userDefined
{
public void user()
{
int [] numArr = {1,3,1,-1,5,-5,0,7,12,-36};
myArray myArray = new myArray(numArr);
JFrame frame = new JFrame("Rectangles");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setSize(360, 300);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.add(myArray);
for (int i=myArray.length(); i>1; i--)
{
for (int j=0; j<i-1; j++)
{
if (myArray.get(j) > myArray.get(j+1))
{
myArray.swap(j, j+1);
}
}
}
}
}
The problem I am getting is that if I try to use reflection like above; I only get a white window which does not show the animation) but just displays the result at the very end.
However if I use this instead of reflection(and change the method void user() to static void main(string args) in userDefined.java):
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
if(compiler.run(null, null, null, "userDefined.java") != 0) {
System.err.println("Could not compile.");
System.exit(0);
}
try {
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec("java "+"userDefined");
BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line=null;
while((line=input.readLine()) != null) {
System.out.println(line);
}
} catch(Exception e) {
System.out.println(e.toString());
e.printStackTrace();
it woks provided that after first compilation I place the myArray class in the same folder as the userDefined.java. In this case I can see the animation take place correctly.
How do I use reflection to invoke the main method instead of using an instance of the class.
Please I really need some help with this. Thanks!
You a violating / missusing the first rule of swing: acces swing components only in the EDT (Event Dispatch Thread).
When you start your program using the main method, you are violating that rule. This happens to work, but might have all kinds of weird effects. This is not a theoretic warning, it happend to me and it is not nice.
When you run it using reflection from your code, you are most likely in the EDT, so your algorithm runs completely before the GUI gets updated again (which also happens on the EDT). Thats why you see only the final result of the algorithm.
The correct way to do this would be:
Run the algorithm in a seperate thread and make sure all changes to your myArray Component happen in the EDT, using SwingUtilities.invokeAndWait or SwingUtilities.invokeLater

exception in java

private String getEmailTemplateWithActualValueForAccount(String template, Account account) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
Map<String,String> map = new HashMap<String, String>();
List<String> listTags = new ArrayList<String>();
Map<Method, String> methodList = new HashMap<Method, String>();
int startIndex=0;
int endIndex=0;
for(int i=0; i<template.length(); i++)
{
char ch = template.charAt(i);
if(ch=='$')
startIndex = i+1;
if(ch=='#')
{
endIndex = i+1;
listTags.add(template.substring(startIndex,endIndex));
}
}
Method[] methods = Account.class.getMethods();
for (Method method : methods) {
String methodName = method.getName();
if(method.getName().startsWith("get"))
{
methodList.put(method, methodName.substring(3,methodName.length()).toUpperCase()+"#");
}
}
Set<Method> methodKeySet = methodList.keySet();
for (Method method : methodKeySet) {
for (String string : listTags) {
if(methodList.get(method).equals(string))
{
try{
Object obj = method.invoke(account, null);
if(obj!=null)
map.put(string, obj.toString());
}catch(NullPointerException e){
}
}
}
}
final StringBuilder list = new StringBuilder( "\\$(" );
for( final String key: map.keySet() )
{
list.append( key );
list.append( "|" );
}
list.append( "[^\\s\\S])" );
Pattern pattern = Pattern.compile( list.toString() );
Matcher matcher = pattern.matcher( template );
final StringBuffer stringBuffer = new StringBuffer();
while( matcher.find() ){
final String string = matcher.group( 1 );
matcher.appendReplacement( stringBuffer, map.get( string ));
}
matcher.appendTail( stringBuffer );
return stringBuffer.toString();
}
I got an exception at line of code "Object obj = method.invoke(account, null);"
Code is perfectly working but as this code is in scheduler it will create an log at every 20 second on jboss server.
The invoke method of Method throws an InvocationTargetException "if the underlying method throws an exception", according to the Javadoc. So you better look into the method that you are invoking to find out why it's throwing an exception. Check the exception stack trace for the root cause.
Instead of catching NullPointerException, you should catch InvocationTargetException, and check the wrapped exception.