I have the following method and how can I do the JUnit testing on it?
Parser is my constructor, which I am also using as my return type of my following method.
As this method is splitting the string in three one, so for that I want to write a unit test case.
I am somehow familiar with JUnit but not that much. Any guidance/ link/ help will be appreciated.
public class Example {
public Parser thirdValueCleanup(String value) {
String thirdValueValue = value.trim();
System.out.println("TestData: "+thirdValueValue);
String firstValueRegex = "[A-z]\\d[A-z]";
String secondValueRegex = "\\d[A-z]\\d";
String thirdValueRegex = "[SK|sk]{2}";
Pattern firstValuePattern = Pattern.compile(".*\\W*("+firstValueRegex+")\\W*.*");
Pattern secondValuePattern = Pattern.compile(".*\\W*("+secondValueRegex+")\\W*.*");
Pattern thirdValuePattern = Pattern.compile(".*\\W*("+thirdValueRegex+")\\W*.*");
String firstValue = "";
String secondValue = "";
String thirdValue = "";
Matcher firstValueMatcher = firstValuePattern.matcher(thirdValueValue);
if(firstValueMatcher.matches()) {
firstValue = firstValueMatcher.group(1);
}
Matcher secondValueMatcher = secondValuePattern.matcher(thirdValueValue);
if(secondValueMatcher.matches()) {
secondValue = secondValueMatcher.group(1);
}
Matcher thirdValueMatcher = thirdValuePattern.matcher(thirdValueValue);
if(thirdValueMatcher.matches()) {
thirdValue = thirdValueMatcher.group(1);
}
String FirstValueName = firstValue + " " + secondValue;
String thirdValueName = thirdValue;
return new Parser(FirstValueName, thirdValueName);
}
public Parser(String firstValue, String secondValue) {
this.firstValue = firstValue;
this.secondValue = secondValue;
}
public String getFirstValue() {
return firstValue;
}
public String getSecondValue() {
return secondValue;
}
}
I tried in my test:
public final void testThirdValueCleanup() {
System.out.println("retrieve");
String factories = "SK S6V 7L4";
Parser parser = new Parser();
Parser expResult = SK S6V 7L4;
Parser result = parser.thirdValueCleanup(factories);
assertEquals(expResult, result);
}
I got this error:
junit.framework.AssertionFailedError: expected:<SK S6V 7L4> but was:<com.example.Parser#379619aa>
at junit.framework.Assert.fail(Assert.java:57)
at junit.framework.Assert.failNotEquals(Assert.java:329)
at junit.framework.Assert.assertEquals(Assert.java:78)
at junit.framework.Assert.assertEquals(Assert.java:86)
at junit.framework.TestCase.assertEquals(TestCase.java:253)
at com.example.ParserTest.testthirdValueCleanup(ParserTest.java:29)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at junit.framework.TestCase.runTest(TestCase.java:176)
at junit.framework.TestCase.runBare(TestCase.java:141)
at junit.framework.TestResult$1.protect(TestResult.java:122)
at junit.framework.TestResult.runProtected(TestResult.java:142)
at junit.framework.TestResult.run(TestResult.java:125)
at junit.framework.TestCase.run(TestCase.java:129)
at junit.framework.TestSuite.runTest(TestSuite.java:252)
at junit.framework.TestSuite.run(TestSuite.java:247)
at org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:86)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
try this
#Test
public final void testThirdValue() {
System.out.println("retrieve");
String factories = " BK M6B 7A4";
Parser parser = new Parser();
Parser province = parser.thirdValue(factories);
assertEquals("M6B 7A4", province.getFirstValue());
assertEquals("BK", province.getSecondValue());
}
Any guidance/ link/ help will be appreciated. thanks
As a simple approach, you might want to try out something within the following lines. As a first step create the test class:
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class ExampleTest {
Example example = new Example();
#Test
public void testThirdValueCleanup(){
//pass some inputs to your function
//by exclicitly calling
//example.thirdValueCleanup(input params...);
//a simple test case would be to check if it you get what your expect
Parser expected = new Parser("set this one as it should be");
assertEquals(example.thirdValueCleanup(some inputs...), expected);
}
/*
* Here you can define more test cases
*/
}
Next you can create a class to run your test:
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
public class TestRunner {
public static void main(String[] args) {
Result result = JUnitCore.runClasses(ExampleTest.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
System.out.println(result.wasSuccessful());
}
}
For more information you can consult either this tutorial or getting started by JUnit.
Related
I have a JPA repository method that is throwing an exception for a null value. I don't understand why its throwing the exception because it can be null in the database table. I don't believe its reaching the persistence stuff yet, but rather exception is be thrown before getting there.
Unfortunately I have to disguise a lot of the coding (plus I simplified by removing lots of params for readability). I would be grateful for any insights.
Here is key part of exception:
java.lang.IllegalArgumentException: Parameter a_e_mark in CMarkRepository.insertCMark must not be null!
at org.springframework.data.repository.core.support.MethodInvocationValidator.invoke(MethodInvocationValidator.java:93)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:215)
at com.sun.proxy.$Proxy142.insertCMark(Unknown Source)
at service.SMarkService.postCMark(SMarkService.java:213)
at controller.SMarkController.postCMark(SMarkController.java:259)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
.....
Here is the important part of calling code:
public int postCMark (CMark cMark) {
CMark cm = null;
int status = 0;
try {
status = cMarkRepository.insertCMark(cMark.getCFk(), stringListToStringArray(cMark.getAEMark())));
} catch ( Exception e) {
e.printStackTrace();
}
return status;
}
private String stringListToStringArray(List<String> stringList) {
StringListConverterCommaDelim stringListConverterCommaDelim = new StringListConverterCommaDelim();
return stringListConverterCommaDelim.convertToDatabaseColumn(stringList);
}
Here is the converter:
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import java.util.Arrays;
import java.util.List;
import static java.util.Collections.emptyList;
#Converter
public class StringListConverterCommaDelim implements AttributeConverter<List<String>, String>
{
private static final String SPLIT_CHAR = ",";
#Override
public String convertToDatabaseColumn(List<String> stringList) {
String splitString = null;
if(stringList != null) {
splitString = String.join(SPLIT_CHAR, stringList);
splitString = "{" + splitString + "}";
}
return splitString;
}
#Override
public List<String> convertToEntityAttribute(String string) {
return string != null ? Arrays.asList(string.split(SPLIT_CHAR)) : emptyList();
}
}
here is the repo:
public interface CMarkRepository extends JpaRepository <CMark, String> {
#Transactional
#Modifying
#Query(value = "INSERT INTO c_mark(c_fk, a_e_mark) values(:c_fk, :a_e_mark\\:\\:character varying[])", nativeQuery = true)
int insertClassMark(#Param("c_fk") String classification_fk, #Param("a_e_mark") String a_e_mark);
}
ok, figured it out. Just by adding #Nullable to each parameter directly its solved:
public interface CMarkRepository extends JpaRepository <CMark, String> {
#Transactional
#Modifying
#Query(value = "INSERT INTO c_mark(c_fk, a_e_mark) values(:c_fk, :a_e_mark\\:\\:character varying[])", nativeQuery = true)
int insertClassMark(#Param("c_fk") #Nullable String classification_fk, #Param("a_e_mark") #Nullable String a_e_mark);
}
I can't work out how to setup the expectation of a call to a mock class. Here is the JUnit test:
public class AfkTest extends TestCase {
private AfkPlayerManager manager;
private Player player;
private Set<AfkPlayer> afkPlayers;
public void setUp() throws Exception {
super.setUp();
manager = new AfkPlayerManager();
player = EasyMock.createMock(Player.class);
afkPlayers = new HashSet<AfkPlayer>();
}
public void tearDown() {
}
public void testNotifyOfAfkPlayerSuccess() {
AfkPlayer afkPlayer = new AfkPlayer();
afkPlayer.setPlayer(player);
afkPlayer.setReason("TEST REASON");
afkPlayers.add(afkPlayer);
List<Player> onlinePlayers = new ArrayList<Player>();
onlinePlayers.add(player);
onlinePlayers.add(player);
EasyMock.expect(player.getDisplayName()).andReturn("TEST PLAYER");
player.sendMessage("§9TEST PLAYER§b is AFK. [TEST REASON]");
EasyMock.expectLastCall().times(1);
//activate the mock
EasyMock.replay(player);
assertTrue(manager.notifyOfAfkPlayer(onlinePlayers, afkPlayer));
//verify call to sendMessage is made or not
EasyMock.verify(player);
}
}
And the method that I am testing:
public class AfkPlayerManager implements Manager {
public boolean notifyOfAfkPlayer(Collection<Player> onlinePlayers, AfkPlayer afkPlayer) {
if (afkPlayer == null) {
return false;
}
String message = ChatColor.BLUE + afkPlayer.getPlayer().getDisplayName();
message += ChatColor.AQUA + " is AFK.";
if (afkPlayer.getReason().length() > 0) {
message += " [" + afkPlayer.getReason() + "]";
}
if (onlinePlayers != null && onlinePlayers.size() > 1) {
int notified = 0;
for (Player onlinePlayer : onlinePlayers) {
onlinePlayer.sendMessage(message);
notified++;
}
if (notified > 0) {
return true;
}
}
return false;
}
}
Why is this giving me the AssertionError:
java.lang.AssertionError: Unexpected method call
Player.sendMessage("§9TEST PLAYER§b is AFK. [TEST REASON]"):
Player.sendMessage("§9TEST PLAYER§b is AFK. [TEST REASON]"): expected: 1, actual: 0 at
org.easymock.internal.MockInvocationHandler.invoke(MockInvocationHandler.java:44)
at
org.easymock.internal.ObjectMethodsFilter.invoke(ObjectMethodsFilter.java:94)
at com.sun.proxy.$Proxy3.sendMessage(Unknown Source) at
crm.afk.AfkPlayerManager.notifyOfAfkPlayer(AfkPlayerManager.java:33)
at crm.test.AfkTest.testNotifyOfAfkPlayerSuccess(AfkTest.java:84) at
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at
java.lang.reflect.Method.invoke(Unknown Source) at
junit.framework.TestCase.runTest(TestCase.java:176) at
junit.framework.TestCase.runBare(TestCase.java:141) at
junit.framework.TestResult$1.protect(TestResult.java:122) at
junit.framework.TestResult.runProtected(TestResult.java:142) at
junit.framework.TestResult.run(TestResult.java:125) at
junit.framework.TestCase.run(TestCase.java:129) at
junit.framework.TestSuite.runTest(TestSuite.java:252) at
junit.framework.TestSuite.run(TestSuite.java:247) at
org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:86)
at
org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at
org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
The expected and actual are different.
Expected: §9TEST PLAYER§b is AFK. [TEST REASON]
Actual: §9TEST PLAYER§b is AFK. [TEST REASON]
The  at the beginning is missing. So it fails as it should.
I am running into this error when I load my GWT page:
error com.google.gwt.user.client.rpc.SerializationException: Type 'com.summerbreezemotel.server.DBReservation' was not included in the set of types which can be serialized by this SerializationPolicy or its Class object could not be loaded.
I looked at the docs and seemed to follow all the constraints. I also have 3 other classes which do the same thing however this one seems to cause an issue. Any help would be appreciated.
the class which is failing:DBReservation
package com.summerbreezemotel.server;
import java.util.Date;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.summerbreezemotel.shared.DataReservation;
import com.summerbreezemotel.shared.SiteConstants;
public class DBReservation extends DataReservation
{
/**
*
*/
private static final long serialVersionUID = 146606067638056872L;
Date dateReserved;
String userEmail;
public DBReservation() {}
public DBReservation(DataReservation in) {
checkIn = in.checkIn;
checkOut = in.checkOut;
form_FirstName = in.form_FirstName;
form_LastName = in.form_LastName;
form_Addr1 = in.form_Addr1;
form_Addr2 = in.form_Addr2;
form_City = in.form_City;
form_State = in.form_State;
form_Zip = in.form_Zip;
form_Country = in.form_Country;
form_Phone = in.form_Phone;
form_Email = in.form_Email;
form_CardType = in.form_CardType;
form_CardMonth = in.form_CardMonth;
form_CardNumber = in.form_CardNumber;
form_CardYear = in.form_CardYear;
form_RoomType = in.form_RoomType;
form_isSmoking = in.form_isSmoking;
form_numRooms = in.form_numRooms;
ratePerNightPerRoom = in.ratePerNightPerRoom;
totalRate = in.totalRate;
}
DataReservation getData()
{
DataReservation out = new DataReservation();
out.checkIn = checkIn;
out.checkOut = checkOut;
out.form_FirstName = form_FirstName;
out.form_LastName = form_LastName;
out.form_Addr1 = form_Addr1;
out.form_Addr2 = form_Addr2;
out.form_City = form_City;
out.form_State = form_State;
out.form_Zip = form_Zip;
out.form_Country = form_Country;
out.form_Phone = form_Phone;
out.form_Email = form_Email;
out.form_CardType = form_CardType;
out.form_CardMonth = form_CardMonth;
out.form_CardNumber = form_CardNumber;
out.form_CardYear = form_CardYear;
out.form_RoomType = form_RoomType;
out.form_isSmoking = form_isSmoking;
out.form_numRooms = form_numRooms;
out.ratePerNightPerRoom = ratePerNightPerRoom;
out.totalRate = totalRate;
return out;
}
// gets item from DB and convertes it to this
void fillReservationFromEntity(Entity item)
{
userEmail = (String) item.getProperty(SiteConstants.USER_PROPERTY);
dateReserved = (Date) item.getProperty(SiteConstants.RESERVE_DATE_PROPERTY);
checkIn = (Date) item.getProperty(SiteConstants.IN_DATE_PROPERTY);
checkOut = (Date) item.getProperty(SiteConstants.OUT_DATE_PROPERTY);
form_FirstName = (String) item.getProperty(SiteConstants.FORM_FIRSTNAME_PROPERTY);
form_LastName = (String) item.getProperty(SiteConstants.FORM_LASTNAME_PROPERTY);
form_Addr1 = (String) item.getProperty(SiteConstants.FORM_ADDR1_PROPERTY);
form_Addr2 = (String) item.getProperty(SiteConstants.FORM_ADDR2_PROPERTY);
form_City = (String) item.getProperty(SiteConstants.FORM_CITY_PROPERTY);
form_State = (String) item.getProperty(SiteConstants.FORM_STATE_PROPERTY);
form_Zip = (String) item.getProperty(SiteConstants.FORM_ZIP_PROPERTY);
form_Country = (String)item.getProperty(SiteConstants.FORM_COUNTRY_PROPERTY);
form_Phone = (String) item.getProperty(SiteConstants.FORM_PHONE_PROPERTY);
form_Email = (String) item.getProperty(SiteConstants.FORM_EMAIL_PROPERTY);
form_CardType = (String) item.getProperty(SiteConstants.FORM_CARDTYPE_PROPERTY);
form_CardMonth = (String) item.getProperty(SiteConstants.FORM_CARDMONTH_PROPERTY);
form_CardNumber = (String) item.getProperty(SiteConstants.FORM_CARDNUMBER_PROPERTY);
form_CardYear = (Long) item.getProperty(SiteConstants.FORM_CARDYEAR_PROPERTY);
form_RoomType = (Long) item.getProperty(SiteConstants.FORM_ROOMTYPE_PROPERTY);
form_isSmoking = (Boolean) item.getProperty(SiteConstants.FORM_ISSMOKING_PROPERTY);
form_numRooms = (Long) item.getProperty(SiteConstants.FORM_NUMROOMS_PROPERTY);
ratePerNightPerRoom = (Double) item.getProperty(SiteConstants.RATEPERNIGHTPERROOM_PROPERTY);
totalRate = (Double) item.getProperty(SiteConstants.TOTALRATE_PROPERTY);
}
void addReservationsToEntity(Entity item)
{
item.setProperty(SiteConstants.USER_PROPERTY, userEmail);
item.setProperty(SiteConstants.RESERVE_DATE_PROPERTY, dateReserved);
item.setProperty(SiteConstants.IN_DATE_PROPERTY, checkIn);
item.setProperty(SiteConstants.OUT_DATE_PROPERTY, checkOut);
item.setProperty(SiteConstants.FORM_FIRSTNAME_PROPERTY,form_FirstName);
item.setProperty(SiteConstants.FORM_LASTNAME_PROPERTY,form_LastName);
item.setProperty(SiteConstants.FORM_ADDR1_PROPERTY,form_Addr1);
item.setProperty(SiteConstants.FORM_ADDR2_PROPERTY,form_Addr2);
item.setProperty(SiteConstants.FORM_CITY_PROPERTY,form_City);
item.setProperty(SiteConstants.FORM_STATE_PROPERTY,form_State);
item.setProperty(SiteConstants.FORM_ZIP_PROPERTY,form_Zip);
item.setProperty(SiteConstants.FORM_COUNTRY_PROPERTY,form_Country);
item.setProperty(SiteConstants.FORM_PHONE_PROPERTY,form_Phone);
item.setProperty(SiteConstants.FORM_EMAIL_PROPERTY,form_Email);
item.setProperty(SiteConstants.FORM_CARDTYPE_PROPERTY,form_CardType);
item.setProperty(SiteConstants.FORM_CARDMONTH_PROPERTY,form_CardMonth);
item.setProperty(SiteConstants.FORM_CARDNUMBER_PROPERTY,form_CardNumber);
item.setProperty(SiteConstants.FORM_CARDYEAR_PROPERTY,form_CardYear);
item.setProperty(SiteConstants.FORM_ROOMTYPE_PROPERTY,form_RoomType);
item.setProperty(SiteConstants.FORM_ISSMOKING_PROPERTY,form_isSmoking);
item.setProperty(SiteConstants.FORM_NUMROOMS_PROPERTY,form_numRooms);
item.setProperty(SiteConstants.RATEPERNIGHTPERROOM_PROPERTY,ratePerNightPerRoom);
item.setProperty(SiteConstants.TOTALRATE_PROPERTY,totalRate);
}
void store()
{
// UserService userService = UserServiceFactory.getUserService();
// User user = userService.getCurrentUser();
// if(user.getEmail() != null)
// userEmail = user.getEmail();
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
String SummerBreezeDateStoreName = new String(SiteConstants.KEY_NAME);
Key SummerBreezeDateStoreKey = KeyFactory.createKey(SiteConstants.KEY_KEY, SummerBreezeDateStoreName);
Entity reservationsEntry = new Entity(SiteConstants.DB_RESERVATIONS, SummerBreezeDateStoreKey);
addReservationsToEntity(reservationsEntry);
datastore.put(reservationsEntry);
// use this if writes get to high
// item.setProperty("testBlob",new Blob(toByte(roomResevationRequest)));
datastore.put(reservationsEntry);
}
}
my DataReservation
package com.summerbreezemotel.shared;
import java.io.Serializable;
import java.util.Date;
public class DataReservation implements Serializable
{
private static final long serialVersionUID = -7598404617383692994L;
public String form_FirstName;
public String form_LastName;
public String form_Addr1;
public String form_Addr2;
public String form_City;
public String form_State;
public String form_Zip;
public String form_Country;
public String form_Phone;
public String form_Email;
public String form_CardType;
public String form_CardMonth;
public String form_CardNumber;
public long form_CardYear;
public long form_RoomType;
public boolean form_isSmoking;
public Date checkIn;
public Date checkOut;
public long form_numRooms;
public double ratePerNightPerRoom;
public double totalRate;
public DataReservation()
{
}
}
I think this is a typical case of shooting yourself in the foot. By extending your server object with the logic from the shared class you made is somewhat easier to create a server side class including the database code, but if you by accident return the server side instead instead of calling getData() just before sending it to the client you get the server side class which can´t be send to the client of course. But the compiler won't warn you for it because it syntactical correct. So I believe the answer is not in the code given, that looks good, but in between the gwt servlet and the usage of DBReservation.
You are using a file in shared folder that implements Serializable and extending it on server side. Are you sure about this logic?? It usually will be a pojo/dto/model on the client/shared side implements IsSerializable and it is sent to the server. Then servers do the manipulation and returns it back.
It should implement the Serializable interface. You don't 'inherit' the implementation by extending the class.
This is a sample class
public class NewClass {
public String hello1(String txt) {
String a = "Hello " + txt + " !";
return a;
}
}
and this is a sample web service
#WebService(serviceName = "NewWebService2")
public class NewWebService2 {
private NewClass newess;
/**
* This is a sample web service operation
*/
#WebMethod(operationName = "hello")
public String hello(#WebParam(name = "name") String txt) {
return "Hello " + txt + " !";
}
#WebMethod(operationName = "hello11")
public String hello11(#WebParam(name = "name") String txt) {
String ess=newess.hello1(txt);
return ess;
}
}
The first method hello works exactly but the second method hello11 is not working. I don't understand the problem. The server shows this message:
SEVERE: java.lang.NullPointerException
at newpackage.NewWebService2.hello11(NewWebService2.java:31)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.glassfish.webservices.InstanceResolverImpl$1.invoke(InstanceResolverImpl.java:143)
at com.sun.xml.ws.server.InvokerTube$2.invoke(InvokerTube.java:149)
at com.sun.xml.ws.server.sei.SEIInvokerTube.processRequest(SEIInvokerTube.java:94)
at com.sun.xml.ws.api.pipe.Fiber.__doRun(Fiber.java:961)
.
.
.
please I need to understand this problem and how I can resolve it.
Initialize your NewClass newess. You are trying to access newess.hello1() without initializing your newess variable
Try it like this:
this.newess = new NewClass();
This isn't thread safe. The member variable is unnecessary.
Not good code, but I'm sure it's just a bad example.
I have this class below, i build it considering the examples given on the wiki and in a thesis, why can't SympleKMeans handle data? The class can print the Datasource dados, so its nothing wrong with processing file, the error is on the build.
package slcct;
import weka.clusterers.ClusterEvaluation;
import weka.clusterers.SimpleKMeans;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.converters.ConverterUtils.DataSource;
public class Cluster {
public String path;
public Instances dados;
public String[] options = new String[2];
public Cluster(String caminho, int nclusters, int seed ){
this.path = caminho;
this.options[0] = String.valueOf(nclusters);
this.options[1] = String.valueOf(seed);
}
public void ledados() throws Exception{
DataSource source = new DataSource(path);
dados = source.getDataSet();
System.out.println(dados)
if(dados.classIndex()==-1){
dados.setClassIndex(dados.numAttributes()-1);
}
}
public void imprimedados(){
for(int i=0; i<dados.numInstances();i++)
{
Instance actual = dados.instance(i);
System.out.println((i+1) + " : "+ actual);
}
}
public void clustering() throws Exception{
SimpleKMeans cluster = new SimpleKMeans();
cluster.setOptions(options);
cluster.setDisplayStdDevs(true);
cluster.getMaxIterations();
cluster.buildClusterer(dados);
Instances ClusterCenter = cluster.getClusterCentroids();
Instances SDev = cluster.getClusterStandardDevs();
int[] ClusterSize = cluster.getClusterSizes();
ClusterEvaluation eval = new ClusterEvaluation();
eval.setClusterer(cluster);
eval.evaluateClusterer(dados);
for(int i=0;i<ClusterCenter.numInstances();i++){
System.out.println("Cluster#"+( i +1)+ ": "+ClusterSize[i]+" dados .");
System.out.println("Centróide:"+ ClusterCenter.instance(i));
System.out.println("STDDEV:" + SDev.instance(i));
System.out.println("Cluster Evaluation:"+eval.clusterResultsToString());
}
}
}
The error:
weka.core.WekaException: weka.clusterers.SimpleKMeans: Cannot handle any class attribute!
at weka.core.Capabilities.test(Capabilities.java:1097)
at weka.core.Capabilities.test(Capabilities.java:1018)
at weka.core.Capabilities.testWithFail(Capabilities.java:1297)
at weka.clusterers.SimpleKMeans.buildClusterer(SimpleKMeans.java:228)
at slcct.Cluster.clustering(Cluster.java:53)//Here.
at slcct.Clustering.jButton1ActionPerformed(Clustering.java:104)
I believe you need not set the class index, as you are doing clustering and not classification. Try following this guide for programmatic Java clustering.
In your "ledados()" function just remove the code block given below. It will work. Because you have no defined class in your data.
if(dados.classIndex()==-1){
dados.setClassIndex(dados.numAttributes()-1);
}
Your new function:
public void ledados() throws Exception{
DataSource source = new DataSource(path);
dados = source.getDataSet();
System.out.println(dados) }
You would not need a class attribute in the data while doing k clustering