I'm using JUnit in a relatively simple workflow
JUnitCore runner = new JUnitCore();
m_junitResult = runner.run(m_junitRequest);
What I want to achieve is once the execution is over to get the list of all tests executed and their descriptions
i did it with the help of Junit's RunListner
while running your Junit suites or individual classes make sure you add the listener to it.
// AutomationTestSuites - contains my all Junit test classes
Class cls= AutomationTestSuites.class;
JUnitCore jUnitCore = new JUnitCore();
CustomRunListener customRunListener = new CustomRunListener();
jUnitCore.addListener(customRunListener);
Request request = Request.aClass(cls);
Result result = jUnitCore.run(request);
below is my listener
import org.junit.runner.Description;
import org.junit.runner.notification.Failure;
import org.junit.runner.notification.RunListener;
import com.dto.TestSuiteDetails;
import java.util.Map;
import java.util.LinkedHashMap;
import java.util.concurrent.TimeUnit;
import java.lang.Exception;
public class CustomRunListener extends RunListener{
private Map<String,TestSuiteDetails> map = new LinkedHashMap<>();
private long testSuiteStartTime;
private long testSuiteElapsedTime;
private int ignoredCount;
public void testRunStarted(Description description) throws Exception {
testSuiteStartTime = System.currentTimeMillis();
}
public void testStarted(Description description) throws Exception {
TestSuiteDetails testSuiteDetails = new TestSuiteDetails();
testSuiteDetails.setTestCaseName(description.getMethodName());
String[] arr = description.getTestClass().getName().split("\\.");
String name = arr[arr.length-1];
testSuiteDetails.setTestClassName(name);
String[] arr1 = name.split("_");
String testSuite = arr1[0];
testSuiteDetails.setTestSuiteNmae(testSuite);
testSuiteDetails.setTestStatus("Passed");
testSuiteDetails.setStartTime(System.currentTimeMillis());
map.put(description.getMethodName(),testSuiteDetails);
}
public void testFinished(Description description) throws Exception {
TestSuiteDetails testSuiteDetails= null;
if(map.containsKey(description.getMethodName())){
testSuiteDetails = map.get(description.getMethodName());
testSuiteDetails.setElaspsedTime(TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()-testSuiteDetails.getStartTime()));
}
map.put(description.getMethodName(),testSuiteDetails);
}
public void testRunFinished(org.junit.runner.Result result) throws Exception {
testSuiteElapsedTime = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()-testSuiteStartTime);
}
public void testFailure(Failure failure) throws Exception {
TestSuiteDetails testSuiteDetails= null;
if(map.containsKey(failure.getDescription().getMethodName())){
testSuiteDetails = map.get(failure.getDescription().getMethodName());
}else{
testSuiteDetails = new TestSuiteDetails();
}
testSuiteDetails.setTestCaseName(failure.getDescription().getMethodName());
testSuiteDetails.setTestDescription(failure.getException().toString());
testSuiteDetails.setTestStatus("Failed");
map.put(failure.getDescription().getMethodName(),testSuiteDetails);
}
public void testIgnored(Description description) throws Exception {
TestSuiteDetails testSuiteDetails= null;
if(map.containsKey(description.getMethodName())){
testSuiteDetails = map.get(description.getMethodName());
}else{
testSuiteDetails = new TestSuiteDetails();
testSuiteDetails.setTestCaseName(description.getMethodName());
String[] arr = description.getTestClass().getName().split("\\.");
String name = arr[arr.length-1];
testSuiteDetails.setTestClassName(name);
String[] arr1 = name.split("_");
String testSuite = arr1[0];
testSuiteDetails.setTestSuiteNmae(testSuite);
ignoredCount++;
}
testSuiteDetails.setTestStatus("Ignored");
map.put(description.getMethodName(),testSuiteDetails);
}
public int getIgnoredCount() {
return ignoredCount;
}
public void setIgnoredCount(int ignoredCount) {
this.ignoredCount = ignoredCount;
}
public Map<String, TestSuiteDetails> getMap() {
return map;
}
public long getTestSuiteStartTime() {
return testSuiteStartTime;
}
public long getTestSuiteElapsedTime() {
return testSuiteElapsedTime;
}
}
am using this pojo for holding test suite details
public class TestSuiteDetails {
private String testClassName;
private String testSuiteNmae;
private String testCaseName;
private String testStatus;
private String testDescription;
private long startTime;
private long elaspsedTime;
public String getTestClassName() {
return testClassName;
}
public void setTestClassName(String testClassName) {
this.testClassName = testClassName;
}
public String getTestCaseName() {
return testCaseName;
}
public void setTestCaseName(String testCaseName) {
this.testCaseName = testCaseName;
}
public String getTestStatus() {
return testStatus;
}
public void setTestStatus(String testStatus) {
this.testStatus = testStatus;
}
public String getTestDescription() {
return testDescription;
}
public void setTestDescription(String testDescription) {
this.testDescription = testDescription;
}
public long getStartTime() {
return startTime;
}
public void setStartTime(long startTime) {
this.startTime = startTime;
}
public long getElaspsedTime() {
return elaspsedTime;
}
public void setElaspsedTime(long elaspsedTime) {
this.elaspsedTime = elaspsedTime;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TestSuiteDetails that = (TestSuiteDetails) o;
if (testClassName != null ? !testClassName.equals(that.testClassName) : that.testClassName != null)
return false;
return testCaseName != null ? testCaseName.equals(that.testCaseName) : that.testCaseName == null;
}
#Override
public int hashCode() {
int result = testClassName != null ? testClassName.hashCode() : 0;
result = 31 * result + (testCaseName != null ? testCaseName.hashCode() : 0);
return result;
}
public String getTestSuiteNmae() {
return testSuiteNmae;
}
public void setTestSuiteNmae(String testSuiteNmae) {
this.testSuiteNmae = testSuiteNmae;
}
}
now after adding the listener - you can simple utilize it later
HashMap<String, TestSuiteDetails> myTestResultMap = customRunListener.getMap();
You can use org.junit.runner.Resultto get the count of successful test runs.
From doc
A Result collects and summarizes information from running multiple tests. Since tests are expected to run correctly, successful tests are only noted in the count of tests that ran.
If there are any test failures then you can get description for failures using org.junit.runner.notification.Failure
From doc
A Failure holds a description of the failed test and the exception that was thrown while running it. In most cases the Description will be of a single test. However, if problems are encountered while constructing the test (for example, if a BeforeClass method is not static), it may describe something other than a single test.
Example code
// From http://www.tutorialspoint.com/
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(TestJunit.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
System.out.println(result.getRunCount());
}
}
Related
So I'm trying to use Executor execute the Dao's in my android app, but when I created the Executor, it said it required the method being run to have a Runnable return type?
So I made them all return Runnable, but now Android Studio gives me the error:
/database/TripDao.java:28: error: Not sure how to handle insert method's return type.
Runnable insertTrip(Trip trip);
^
Dao:
import androidx.lifecycle.LiveData;
import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.Query;
import androidx.room.Update;
import java.util.List;
import java.util.UUID;
#Dao
public interface TripDao {
#Query("DELETE FROM trip")
public void deleteTrips();
#Query("SELECT * FROM trip")
LiveData<List<Trip>> getAll();
#Query("SELECT * FROM trip WHERE uuid=:id")
public LiveData<Trip> getTrip(UUID id);
#Delete
Runnable delete(Trip trip);
#Insert
Runnable insertTrip(Trip trip);
#Update
Runnable updateTrip(Trip trip);
}
Repository:
package com.example.csc202assignment.database;
import android.content.Context;
import androidx.lifecycle.LiveData;
import androidx.room.Room;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
public class TripRepository {
private static TripRepository INSTANCE = null;
private final String DATABASE_NAME = "trip-database";
private Context context;
TripDatabase database;
static TripDao tripDao;
Executor executor = Executors.newSingleThreadExecutor();
private TripRepository(Context context) {
this.context = context;
this.database = Room.databaseBuilder(
context.getApplicationContext(),
TripDatabase.class,DATABASE_NAME).build();
tripDao = database.tripDao();
}
void deleteTrips(){
tripDao.deleteTrips();
}
void delete(Trip trip){
executor.execute(tripDao.delete(trip));
}
void insertTrip(Trip trip){
executor.execute(tripDao.insertTrip(trip));
}
void updateTrip(Trip trip){
executor.execute(tripDao.updateTrip(trip));
}
public LiveData<List<Trip>> getAll(){ return tripDao.getAll();
}
public static LiveData<Trip> getTrip(UUID id){
return tripDao.getTrip(id);
}
public static void initialise(Context context){
if(INSTANCE==null){
INSTANCE = new TripRepository(context);
}
}
public static TripRepository get() throws IllegalStateException {
try {
return INSTANCE;
} catch (IllegalStateException e) {
System.out.println("TripRepository must be initialised");
}
return INSTANCE;
}
}
Dao_Impl
package com.example.csc202assignment.database;
import android.database.Cursor;
import androidx.lifecycle.LiveData;
import androidx.room.EntityDeletionOrUpdateAdapter;
import androidx.room.EntityInsertionAdapter;
import androidx.room.RoomDatabase;
import androidx.room.RoomSQLiteQuery;
import androidx.room.SharedSQLiteStatement;
import androidx.room.util.CursorUtil;
import androidx.room.util.DBUtil;
import androidx.sqlite.db.SupportSQLiteStatement;
import java.lang.Class;
import java.lang.Exception;
import java.lang.Override;
import java.lang.Runnable;
import java.lang.String;
import java.lang.SuppressWarnings;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.Callable;
#SuppressWarnings({"unchecked", "deprecation"})
public final class TripDao_Impl implements TripDao {
private final RoomDatabase __db;
private final EntityInsertionAdapter<Trip> __insertionAdapterOfTrip;
private final TripTypeConverter __tripTypeConverter = new TripTypeConverter();
private final EntityDeletionOrUpdateAdapter<Trip> __deletionAdapterOfTrip;
private final EntityDeletionOrUpdateAdapter<Trip> __updateAdapterOfTrip;
private final SharedSQLiteStatement __preparedStmtOfDeleteTrips;
public TripDao_Impl(RoomDatabase __db) {
this.__db = __db;
this.__insertionAdapterOfTrip = new EntityInsertionAdapter<Trip>(__db) {
#Override
public String createQuery() {
return "INSERT OR ABORT INTO `Trip` (`uuid`,`title`,`destination`,`date`,`duration`) VALUES (?,?,?,?,?)";
}
#Override
public void bind(SupportSQLiteStatement stmt, Trip value) {
final String _tmp;
_tmp = __tripTypeConverter.fromUUID(value.uuid);
if (_tmp == null) {
stmt.bindNull(1);
} else {
stmt.bindString(1, _tmp);
}
if (value.title == null) {
stmt.bindNull(2);
} else {
stmt.bindString(2, value.title);
}
if (value.destination == null) {
stmt.bindNull(3);
} else {
stmt.bindString(3, value.destination);
}
if (value.date == null) {
stmt.bindNull(4);
} else {
stmt.bindString(4, value.date);
}
if (value.duration == null) {
stmt.bindNull(5);
} else {
stmt.bindString(5, value.duration);
}
}
};
this.__deletionAdapterOfTrip = new EntityDeletionOrUpdateAdapter<Trip>(__db) {
#Override
public String createQuery() {
return "DELETE FROM `Trip` WHERE `uuid` = ?";
}
#Override
public void bind(SupportSQLiteStatement stmt, Trip value) {
final String _tmp;
_tmp = __tripTypeConverter.fromUUID(value.uuid);
if (_tmp == null) {
stmt.bindNull(1);
} else {
stmt.bindString(1, _tmp);
}
}
};
this.__updateAdapterOfTrip = new EntityDeletionOrUpdateAdapter<Trip>(__db) {
#Override
public String createQuery() {
return "UPDATE OR ABORT `Trip` SET `uuid` = ?,`title` = ?,`destination` = ?,`date` = ?,`duration` = ? WHERE `uuid` = ?";
}
#Override
public void bind(SupportSQLiteStatement stmt, Trip value) {
final String _tmp;
_tmp = __tripTypeConverter.fromUUID(value.uuid);
if (_tmp == null) {
stmt.bindNull(1);
} else {
stmt.bindString(1, _tmp);
}
if (value.title == null) {
stmt.bindNull(2);
} else {
stmt.bindString(2, value.title);
}
if (value.destination == null) {
stmt.bindNull(3);
} else {
stmt.bindString(3, value.destination);
}
if (value.date == null) {
stmt.bindNull(4);
} else {
stmt.bindString(4, value.date);
}
if (value.duration == null) {
stmt.bindNull(5);
} else {
stmt.bindString(5, value.duration);
}
final String _tmp_1;
_tmp_1 = __tripTypeConverter.fromUUID(value.uuid);
if (_tmp_1 == null) {
stmt.bindNull(6);
} else {
stmt.bindString(6, _tmp_1);
}
}
};
this.__preparedStmtOfDeleteTrips = new SharedSQLiteStatement(__db) {
#Override
public String createQuery() {
final String _query = "DELETE FROM trip";
return _query;
}
};
}
#Override
public Runnable insertTrip(final Trip trip) {
__db.assertNotSuspendingTransaction();
}
#Override
public Runnable delete(final Trip trip) {
__db.assertNotSuspendingTransaction();
}
#Override
public Runnable updateTrip(final Trip trip) {
__db.assertNotSuspendingTransaction();
}
#Override
public void deleteTrips() {
__db.assertNotSuspendingTransaction();
final SupportSQLiteStatement _stmt = __preparedStmtOfDeleteTrips.acquire();
__db.beginTransaction();
try {
_stmt.executeUpdateDelete();
__db.setTransactionSuccessful();
} finally {
__db.endTransaction();
__preparedStmtOfDeleteTrips.release(_stmt);
}
}
#Override
public LiveData<List<Trip>> getAll() {
final String _sql = "SELECT * FROM trip";
final RoomSQLiteQuery _statement = RoomSQLiteQuery.acquire(_sql, 0);
return __db.getInvalidationTracker().createLiveData(new String[]{"trip"}, false, new Callable<List<Trip>>() {
#Override
public List<Trip> call() throws Exception {
final Cursor _cursor = DBUtil.query(__db, _statement, false, null);
try {
final int _cursorIndexOfUuid = CursorUtil.getColumnIndexOrThrow(_cursor, "uuid");
final int _cursorIndexOfTitle = CursorUtil.getColumnIndexOrThrow(_cursor, "title");
final int _cursorIndexOfDestination = CursorUtil.getColumnIndexOrThrow(_cursor, "destination");
final int _cursorIndexOfDate = CursorUtil.getColumnIndexOrThrow(_cursor, "date");
final int _cursorIndexOfDuration = CursorUtil.getColumnIndexOrThrow(_cursor, "duration");
final List<Trip> _result = new ArrayList<Trip>(_cursor.getCount());
while(_cursor.moveToNext()) {
final Trip _item;
_item = new Trip();
final String _tmp;
if (_cursor.isNull(_cursorIndexOfUuid)) {
_tmp = null;
} else {
_tmp = _cursor.getString(_cursorIndexOfUuid);
}
_item.uuid = __tripTypeConverter.toUUID(_tmp);
if (_cursor.isNull(_cursorIndexOfTitle)) {
_item.title = null;
} else {
_item.title = _cursor.getString(_cursorIndexOfTitle);
}
if (_cursor.isNull(_cursorIndexOfDestination)) {
_item.destination = null;
} else {
_item.destination = _cursor.getString(_cursorIndexOfDestination);
}
if (_cursor.isNull(_cursorIndexOfDate)) {
_item.date = null;
} else {
_item.date = _cursor.getString(_cursorIndexOfDate);
}
if (_cursor.isNull(_cursorIndexOfDuration)) {
_item.duration = null;
} else {
_item.duration = _cursor.getString(_cursorIndexOfDuration);
}
_result.add(_item);
}
return _result;
} finally {
_cursor.close();
}
}
#Override
protected void finalize() {
_statement.release();
}
});
}
#Override
public LiveData<Trip> getTrip(final UUID id) {
final String _sql = "SELECT * FROM trip WHERE uuid=?";
final RoomSQLiteQuery _statement = RoomSQLiteQuery.acquire(_sql, 1);
int _argIndex = 1;
final String _tmp;
_tmp = __tripTypeConverter.fromUUID(id);
if (_tmp == null) {
_statement.bindNull(_argIndex);
} else {
_statement.bindString(_argIndex, _tmp);
}
return __db.getInvalidationTracker().createLiveData(new String[]{"trip"}, false, new Callable<Trip>() {
#Override
public Trip call() throws Exception {
final Cursor _cursor = DBUtil.query(__db, _statement, false, null);
try {
final int _cursorIndexOfUuid = CursorUtil.getColumnIndexOrThrow(_cursor, "uuid");
final int _cursorIndexOfTitle = CursorUtil.getColumnIndexOrThrow(_cursor, "title");
final int _cursorIndexOfDestination = CursorUtil.getColumnIndexOrThrow(_cursor, "destination");
final int _cursorIndexOfDate = CursorUtil.getColumnIndexOrThrow(_cursor, "date");
final int _cursorIndexOfDuration = CursorUtil.getColumnIndexOrThrow(_cursor, "duration");
final Trip _result;
if(_cursor.moveToFirst()) {
_result = new Trip();
final String _tmp_1;
if (_cursor.isNull(_cursorIndexOfUuid)) {
_tmp_1 = null;
} else {
_tmp_1 = _cursor.getString(_cursorIndexOfUuid);
}
_result.uuid = __tripTypeConverter.toUUID(_tmp_1);
if (_cursor.isNull(_cursorIndexOfTitle)) {
_result.title = null;
} else {
_result.title = _cursor.getString(_cursorIndexOfTitle);
}
if (_cursor.isNull(_cursorIndexOfDestination)) {
_result.destination = null;
} else {
_result.destination = _cursor.getString(_cursorIndexOfDestination);
}
if (_cursor.isNull(_cursorIndexOfDate)) {
_result.date = null;
} else {
_result.date = _cursor.getString(_cursorIndexOfDate);
}
if (_cursor.isNull(_cursorIndexOfDuration)) {
_result.duration = null;
} else {
_result.duration = _cursor.getString(_cursorIndexOfDuration);
}
} else {
_result = null;
}
return _result;
} finally {
_cursor.close();
}
}
#Override
protected void finalize() {
_statement.release();
}
});
}
public static List<Class<?>> getRequiredConverters() {
return Collections.emptyList();
}
}
I've been told I need to use Executor for INSERT, UPDATE and DELETE so they don't get block the main thread, so I'm not sure how to fix this without just removing the executors.
As far as I can figure, there's no actual Runnable object to return, so it doesn't know what to do? If I've got that wrong please correct me.
But yeah, I just can't figure out how to get around the executor wanting a Runnable return type, but there being no Runnable to return. Any help would be appreciated
You are trying to tell room to return a Runnable from the insert. Room knows that an #Insert can only return void or Long/long (the rowid of the inserted row).
if the #Insert inserts multiple rows then it can return void, long[] or Long[].
if you were look at the Build log, then the
You can't have :-
#Insert
Runnable insertTrip(Trip trip);
It must be one of the following:-
#Insert
void insertTrip(Trip trip);
or
#Insert
long insertTrip(Trip trip);
or
#Insert
Long insertTrip(Trip trip);
Similar for #Update and #Delete except they return int (the number or affected rows)
To get/use the Runnable you could use :-
void insertTrip(Trip trip){
executor.execute(new Runnable() {
#Override
public void run() {
tripDao.insertTrip(trip);
}
});
}
obviously likewise for the others.
Working example
Using (note with a simple Trip class but all other classes as per your question bar the changes above) :-
TripRepository.initialise(this);
Trip atrip = new Trip();
atrip.tripName = "My Trip";
TripRepository.get().insertTrip(atrip);
Results in :-
I am trying to write an unbounded ping pipeline that takes output from a ping command and parses it to determine some statistics about the RTT (avg/min/max) and for now, just print the results.
I have already written an unbounded ping source that outputs each line as it comes in. The results are windowed every second for every 5 seconds of pings. The windowed data is fed to a Combine.globally call to statefully process the string outputs. The problem is that the accumulators are never merged and the output is never extracted. This means that the pipeline never continues past this point. What am I doing wrong here?
public class TestPingIPs {
public static void main(String[] args)
{
PipelineOptions options = PipelineOptionsFactory.create();
Pipeline pipeline = Pipeline.create(options);
String destination = "8.8.8.8";
PCollection<PingResult> res =
/*
Run the unbounded ping command. Only the lines where the result of the ping command are returned.
No statistics or first startup lines are returned here.
*/
pipeline.apply("Ping command",
PingCmd.read()
.withPingArguments(PingCmd.PingArguments.create(destination, -1)))
/*
Window the ping command strings into 5 second sliding windows produced every 1 second
*/
.apply("Window strings",
Window.into(SlidingWindows.of(Duration.standardSeconds(5))
.every(Duration.standardSeconds(1))))
/*
Parse and aggregate the strings into a PingResult object using stateful processing.
*/
.apply("Combine the pings",
Combine.globally(new ProcessPings()).withoutDefaults())
/*
Test our output to see what we get here
*/
.apply("Test output",
ParDo.of(new DoFn<PingResult, PingResult>() {
#ProcessElement
public void processElement(ProcessContext c)
{
System.out.println(c.element().getAvgRTT());
System.out.println(c.element().getPacketLoss());
c.output(c.element());
}
}));
pipeline.run().waitUntilFinish();
}
static class ProcessPings extends Combine.CombineFn<String, RttStats, PingResult> {
private long getRTTFromLine(String line){
long rtt = Long.parseLong(line.split("time=")[1].split("ms")[0]);
return rtt;
}
#Override
public RttStats createAccumulator()
{
return new RttStats();
}
#Override
public RttStats addInput(RttStats mutableAccumulator, String input)
{
mutableAccumulator.incTotal();
if (input.contains("unreachable")) {
_unreachableCount.inc();
mutableAccumulator.incPacketLoss();
}
else if (input.contains("General failure")) {
_transmitFailureCount.inc();
mutableAccumulator.incPacketLoss();
}
else if (input.contains("timed out")) {
_timeoutCount.inc();
mutableAccumulator.incPacketLoss();
}
else if (input.contains("could not find")) {
_unknownHostCount.inc();
mutableAccumulator.incPacketLoss();
}
else {
_successfulCount.inc();
mutableAccumulator.add(getRTTFromLine(input));
}
return mutableAccumulator;
}
#Override
public RttStats mergeAccumulators(Iterable<RttStats> accumulators)
{
Iterator<RttStats> iter = accumulators.iterator();
if (!iter.hasNext()){
return createAccumulator();
}
RttStats running = iter.next();
while (iter.hasNext()){
RttStats next = iter.next();
running.addAll(next.getVals());
running.addLostPackets(next.getLostPackets());
}
return running;
}
#Override
public PingResult extractOutput(RttStats stats)
{
stats.calculate();
boolean connected = stats.getPacketLoss() != 1;
return new PingResult(connected, stats.getAvg(), stats.getMin(), stats.getMax(), stats.getPacketLoss());
}
private final Counter _successfulCount = Metrics.counter(ProcessPings.class, "Successful pings");
private final Counter _unknownHostCount = Metrics.counter(ProcessPings.class, "Unknown hosts");
private final Counter _transmitFailureCount = Metrics.counter(ProcessPings.class, "Transmit failures");
private final Counter _timeoutCount = Metrics.counter(ProcessPings.class, "Timeouts");
private final Counter _unreachableCount = Metrics.counter(ProcessPings.class, "Unreachable host");
}
I would guess that there are some issues with the CombineFn that I wrote, but I can't seem to figure out what's going wrong here! I tried following the example here, but there's still something I must be missing.
EDIT: I added the ping command implementation below. This is running on a Direct Runner while I test.
PingCmd.java:
public class PingCmd {
public static Read read(){
if (System.getProperty("os.name").startsWith("Windows")) {
return WindowsPingCmd.read();
}
else{
return null;
}
}
WindowsPingCmd.java:
public class WindowsPingCmd extends PingCmd {
private WindowsPingCmd()
{
}
public static PingCmd.Read read()
{
return new WindowsRead.Builder().build();
}
static class PingCheckpointMark implements UnboundedSource.CheckpointMark, Serializable {
#VisibleForTesting
Instant oldestMessageTimestamp = Instant.now();
#VisibleForTesting
transient List<String> outputs = new ArrayList<>();
public PingCheckpointMark()
{
}
public void add(String message, Instant timestamp)
{
if (timestamp.isBefore(oldestMessageTimestamp)) {
oldestMessageTimestamp = timestamp;
}
outputs.add(message);
}
#Override
public void finalizeCheckpoint()
{
oldestMessageTimestamp = Instant.now();
outputs.clear();
}
// set an empty list to messages when deserialize
private void readObject(java.io.ObjectInputStream stream)
throws IOException, ClassNotFoundException
{
stream.defaultReadObject();
outputs = new ArrayList<>();
}
#Override
public boolean equals(#Nullable Object other)
{
if (other instanceof PingCheckpointMark) {
PingCheckpointMark that = (PingCheckpointMark) other;
return Objects.equals(this.oldestMessageTimestamp, that.oldestMessageTimestamp)
&& Objects.deepEquals(this.outputs, that.outputs);
}
else {
return false;
}
}
}
#VisibleForTesting
static class UnboundedPingSource extends UnboundedSource<String, PingCheckpointMark> {
private final WindowsRead spec;
public UnboundedPingSource(WindowsRead spec)
{
this.spec = spec;
}
#Override
public UnboundedReader<String> createReader(
PipelineOptions options, PingCheckpointMark checkpointMark)
{
return new UnboundedPingReader(this, checkpointMark);
}
#Override
public List<UnboundedPingSource> split(int desiredNumSplits, PipelineOptions options)
{
// Don't really need to ever split the ping source, so we should just have one per destination
return Collections.singletonList(new UnboundedPingSource(spec));
}
#Override
public void populateDisplayData(DisplayData.Builder builder)
{
spec.populateDisplayData(builder);
}
#Override
public Coder<PingCheckpointMark> getCheckpointMarkCoder()
{
return SerializableCoder.of(PingCheckpointMark.class);
}
#Override
public Coder<String> getOutputCoder()
{
return StringUtf8Coder.of();
}
}
#VisibleForTesting
static class UnboundedPingReader extends UnboundedSource.UnboundedReader<String> {
private final UnboundedPingSource source;
private String current;
private Instant currentTimestamp;
private final PingCheckpointMark checkpointMark;
private BufferedReader processOutput;
private Process process;
private boolean finishedPings;
private int maxCount = 5;
private static AtomicInteger currCount = new AtomicInteger(0);
public UnboundedPingReader(UnboundedPingSource source, PingCheckpointMark checkpointMark)
{
this.finishedPings = false;
this.source = source;
this.current = null;
if (checkpointMark != null) {
this.checkpointMark = checkpointMark;
}
else {
this.checkpointMark = new PingCheckpointMark();
}
}
#Override
public boolean start() throws IOException
{
WindowsRead spec = source.spec;
String cmd = createCommand(spec.pingConfiguration().getPingCount(), spec.pingConfiguration().getDestination());
try {
ProcessBuilder builder = new ProcessBuilder(cmd.split(" "));
builder.redirectErrorStream(true);
process = builder.start();
processOutput = new BufferedReader(new InputStreamReader(process.getInputStream()));
return advance();
} catch (Exception e) {
throw new IOException(e);
}
}
private String createCommand(int count, String dest){
StringBuilder builder = new StringBuilder("ping");
String countParam = "";
if (count <= 0){
countParam = "-t";
}
else{
countParam += "-n " + count;
}
return builder.append(" ").append(countParam).append(" ").append(dest).toString();
}
#Override
public boolean advance() throws IOException
{
String line = processOutput.readLine();
// Ignore empty/null lines
if (line == null || line.isEmpty()) {
line = processOutput.readLine();
}
// Ignore the 'Pinging <dest> with 32 bytes of data' line
if (line.contains("Pinging " + source.spec.pingConfiguration().getDestination())) {
line = processOutput.readLine();
}
// If the pings have finished, ignore
if (finishedPings) {
return false;
}
// If this is the start of the statistics, the pings are done and we can just exit
if (line.contains("statistics")) {
finishedPings = true;
}
current = line;
currentTimestamp = Instant.now();
checkpointMark.add(current, currentTimestamp);
if (currCount.incrementAndGet() == maxCount){
currCount.set(0);
return false;
}
return true;
}
#Override
public void close() throws IOException
{
if (process != null) {
process.destroy();
if (process.isAlive()) {
process.destroyForcibly();
}
}
}
#Override
public Instant getWatermark()
{
return checkpointMark.oldestMessageTimestamp;
}
#Override
public UnboundedSource.CheckpointMark getCheckpointMark()
{
return checkpointMark;
}
#Override
public String getCurrent()
{
if (current == null) {
throw new NoSuchElementException();
}
return current;
}
#Override
public Instant getCurrentTimestamp()
{
if (current == null) {
throw new NoSuchElementException();
}
return currentTimestamp;
}
#Override
public UnboundedPingSource getCurrentSource()
{
return source;
}
}
public static class WindowsRead extends PingCmd.Read {
private final PingArguments pingConfig;
private WindowsRead(PingArguments pingConfig)
{
this.pingConfig = pingConfig;
}
public Builder builder()
{
return new WindowsRead.Builder(this);
}
PingArguments pingConfiguration()
{
return pingConfig;
}
public WindowsRead withPingArguments(PingArguments configuration)
{
checkArgument(configuration != null, "configuration can not be null");
return builder().setPingArguments(configuration).build();
}
#Override
public PCollection<String> expand(PBegin input)
{
org.apache.beam.sdk.io.Read.Unbounded<String> unbounded =
org.apache.beam.sdk.io.Read.from(new UnboundedPingSource(this));
return input.getPipeline().apply(unbounded);
}
#Override
public void populateDisplayData(DisplayData.Builder builder)
{
super.populateDisplayData(builder);
pingConfiguration().populateDisplayData(builder);
}
static class Builder {
private PingArguments config;
Builder()
{
}
private Builder(WindowsRead source)
{
this.config = source.pingConfiguration();
}
WindowsRead.Builder setPingArguments(PingArguments config)
{
this.config = config;
return this;
}
WindowsRead build()
{
return new WindowsRead(this.config);
}
}
#Override
public int hashCode()
{
return Objects.hash(pingConfig);
}
}
One thing I notice in your code is that advance() always returns True. The watermark only advances on bundle completion, and I think it's runner-dependent whether a runner will ever complete a bundle if advance ever never returns False. You could try returning False after a bounded amount of time/number of pings.
You could also consider re-writing this as an SDF.
I am working on modeling several java objects that manage entities in a mySQL database using the JDBCTemplate.
I have run Add/Get JUnit tests on two other objects and I am not getting any errors, but I cannot figure out what is causing this error for my 'Organization' object.
Here is my 'Organization' dto code:
package com.sg.superherosightings.model;
import java.util.Objects;
public class Organization {
private int orgId;
private String orgName;
private String orgDescription;
private String orgPhone;
private String orgEmail;
private String orgStreetAddress;
private String orgCity;
private String orgState;
private String orgZipCode;
public int getOrgId() {
return orgId;
}
public void setOrgId(int orgId) {
this.orgId = orgId;
}
public String getOrgName() {
return orgName;
}
public void setOrgName(String orgName) {
this.orgName = orgName;
}
public String getOrgDescription() {
return orgDescription;
}
public void setOrgDescription(String orgDescription) {
this.orgDescription = orgDescription;
}
public String getOrgPhone() {
return orgPhone;
}
public void setOrgPhone(String orgPhone) {
this.orgPhone = orgPhone;
}
public String getOrgEmail() {
return orgEmail;
}
public void setOrgEmail(String orgEmail) {
this.orgEmail = orgEmail;
}
public String getOrgStreetAddress() {
return orgStreetAddress;
}
public void setOrgStreetAddress(String orgStreetAddress) {
this.orgStreetAddress = orgStreetAddress;
}
public String getOrgCity() {
return orgCity;
}
public void setOrgCity(String orgCity) {
this.orgCity = orgCity;
}
public String getOrgState() {
return orgState;
}
public void setOrgState(String orgState) {
this.orgState = orgState;
}
public String getOrgZipCode() {
return orgZipCode;
}
public void setOrgZipCode(String orgZipCode) {
this.orgZipCode = orgZipCode;
}
#Override
public int hashCode() {
int hash = 7;
hash = 89 * hash + this.orgId;
hash = 89 * hash + Objects.hashCode(this.orgName);
hash = 89 * hash + Objects.hashCode(this.orgDescription);
hash = 89 * hash + Objects.hashCode(this.orgPhone);
hash = 89 * hash + Objects.hashCode(this.orgEmail);
hash = 89 * hash + Objects.hashCode(this.orgStreetAddress);
hash = 89 * hash + Objects.hashCode(this.orgCity);
hash = 89 * hash + Objects.hashCode(this.orgState);
hash = 89 * hash + Objects.hashCode(this.orgZipCode);
return hash;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Organization other = (Organization) obj;
if (this.orgId != other.orgId) {
return false;
}
if (!Objects.equals(this.orgName, other.orgName)) {
return false;
}
if (!Objects.equals(this.orgDescription, other.orgDescription)) {
return false;
}
if (!Objects.equals(this.orgPhone, other.orgPhone)) {
return false;
}
if (!Objects.equals(this.orgEmail, other.orgEmail)) {
return false;
}
if (!Objects.equals(this.orgStreetAddress, other.orgStreetAddress)) {
return false;
}
if (!Objects.equals(this.orgCity, other.orgCity)) {
return false;
}
if (!Objects.equals(this.orgState, other.orgState)) {
return false;
}
if (!Objects.equals(this.orgZipCode, other.orgZipCode)) {
return false;
}
return true;
}
}
Here is my Mapper Method in my DaoDBImpl:
img of OrgMapper Method before fix
This is my SuperSightings_DaoTest method causing the error:
package com.sg.superherosightings.dao;
import com.sg.superherosightings.model.Location;
import com.sg.superherosightings.model.Organization;
import com.sg.superherosightings.model.Power;
import com.sg.superherosightings.model.Sighting;
import com.sg.superherosightings.model.Supe;
import java.util.List;
import org.junit.After;
import org.junit.AfterClass;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SuperSightings_DaoTest {
SuperSightings_Dao dao;
public SuperSightings_DaoTest() {
}
#BeforeClass
public static void setUpClass() {
}
#AfterClass
public static void tearDownClass() {
}
#Before
public void setUp() {
ApplicationContext ctx
= new ClassPathXmlApplicationContext("test-applicationContext.xml");
dao = ctx.getBean("SuperSightings_Dao", SuperSightings_Dao.class);
// delete all supes
List<Supe> supes = dao.getAllSupes(); for (Supe currentSupe : supes) {
dao.deleteSupe(currentSupe.getSupeId());
}
// delete all powers
List<Power> powers = dao.getAllPowers(); for (Power currentPower : powers) {
dao.deletePower(currentPower.getPowerId());
}
//delete all organizations
List<Organization> orgs = dao.getAllOrganizations(); for (Organization currentOrg : orgs) {
dao.deleteOrganization(currentOrg.getOrgId());
}
// delete all locations
List<Location> locations = dao.getAllLocations(); for (Location currentLocation : locations) {
dao.deleteLocation(currentLocation.getLocationId());
}
// delete all sightings
List<Sighting> sightings = dao.getAllSightings(); for (Sighting currentSighting : sightings) {
dao.deleteSighting(currentSighting.getSightingId());
}
}
#After
public void tearDown() {
}
/**
* Test of addPower method, of class SuperSightings_Dao.
*/
#Test
public void testAddGetPower() {
Power power = new Power();
power.setPowerType("Fire");
power.setPowerDescription("Shoots fire from hands");
dao.addPower(power);
Power fromDao = dao.getPowerById(power.getPowerId());
assertEquals(fromDao, power);
}
/**
* Test of deletePower method, of class SuperSightings_Dao.
*/
#Test
public void testDeletePower() {
Power power = new Power();
power.setPowerType("Fire");
power.setPowerDescription("Shoots fire from hands");
dao.addPower(power);
Power fromDao = dao.getPowerById(power.getPowerId());
assertEquals(fromDao, power);
dao.deletePower(power.getPowerId());
assertNull(dao.getPowerById(power.getPowerId()));
}
/**
* Test of getAllPowersBySupeId method, of class SuperSightings_Dao.
*/
#Test
public void testGetAllPowersBySupeId() {
}
/**
* Test of addOrganization method, of class SuperSightings_Dao.
*/
#Test
public void testAddGetOrganization() {
Organization org = new Organization();
org.setOrgName("Legion of Doom");
org.setOrgDescription("evil organization");
org.setOrgPhone("333-444-5678");
org.setOrgEmail("lod#evil.org");
org.setOrgStreetAddress("344 Lowland Blvd.");
org.setOrgCity("Quahog");
org.setOrgState("RI");
org.setOrgZipCode("09678");
dao.addOrganization(org);
Organization fromDao = dao.getOrganizationById(org.getOrgId());
assertEquals(fromDao, org); //this is the line causing the error
}
This is the error I am getting:
testAddGetOrganization(com.sg.superherosightings.dao.SuperSightings_DaoTest)
Time elapsed: 0.107 sec <<< FAILURE! java.lang.AssertionError:
expected:com.sg.superherosightings.model.Organization#ae511546 but
was:com.sg.superherosightings.model.Organization#15fabf0f
Please let me know if I need to provide further information. i am trying to get better at how i post questions here. I searched for a long time before asking but all I can find is that it might be something with my equals/hash code. I'm just not sure what is getting changed when the comparison is made because it is not happening with my other objects.
Thank you for any hints, and please don't bite my head off!
It seems some fields are not equal. try to compare all fields one by one to identify non-equal fields: assertEquals(fromDao.getOrgId(), org.getOrgId() and all the rest of organization's fields)
Thank you all for your assistance! I was able to convert my org and fromDao objects to string to see them in the test window. The problem was with my Mapper method for the Organization object. See original and the fix below:
Original Version
private static final class OrgMapper implements RowMapper<Organization> {
#Override
public Organization mapRow(ResultSet rs, int i) throws SQLException {
Organization org = new Organization();
org.setOrgId(rs.getInt("org_id"));
org.setOrgName(rs.getString("org_name"));
org.setOrgDescription(rs.getString("org_description"));
org.setOrgPhone(rs.getString("org_phone"));
org.setOrgEmail(rs.getString("org_street_address")); //wrong field
org.setOrgCity(rs.getString("org_city"));
org.setOrgState(rs.getString("org_state"));
org.setOrgZipCode(rs.getString("org_zip_code"));
return org;
}
}
Fixed OrgMapper:
private static final class OrgMapper implements RowMapper<Organization> {
#Override
public Organization mapRow(ResultSet rs, int i) throws SQLException {
Organization org = new Organization();
org.setOrgId(rs.getInt("org_id"));
org.setOrgName(rs.getString("org_name"));
org.setOrgDescription(rs.getString("org_description"));
org.setOrgPhone(rs.getString("org_phone"));
org.setOrgEmail(rs.getString("org_email"));
org.setOrgStreetAddress(rs.getString("org_street_address"));
org.setOrgCity(rs.getString("org_city"));
org.setOrgState(rs.getString("org_state"));
org.setOrgZipCode(rs.getString("org_zip_code"));
return org;
}
I need to get list of all the tests in my package... I want to use maven but so far I haven't found appropriate call to do it. I've tried reflection in Java but it did not list all of the #Test methods. Some of un-annotated methods were listed as well..
public static void main(String[] args) {
Reflections reflections = new Reflections(new ConfigurationBuilder()
.setUrls(ClasspathHelper.forPackage("com.mypackage"))
.setScanners(new MethodAnnotationsScanner()));
Set<Method> methods = reflections.getMethodsAnnotatedWith(Test.class);
System.out.println(methods);
}
Any help or pointer in right direction would be much appreciated.
i was able to track it by making use of Junit's RunListner
when you run your Junit suites or individual classes make sure you add the listener to it.
// AutomationTestSuites - contains my all Junit test classes
Class cls= AutomationTestSuites.class;
JUnitCore jUnitCore = new JUnitCore();
CustomRunListener customRunListener = new CustomRunListener();
jUnitCore.addListener(customRunListener);
Request request = Request.aClass(cls);
Result result = jUnitCore.run(request);
below is my listener
import org.junit.runner.Description;
import org.junit.runner.notification.Failure;
import org.junit.runner.notification.RunListener;
import com.dto.TestSuiteDetails;
import java.util.Map;
import java.util.LinkedHashMap;
import java.util.concurrent.TimeUnit;
import java.lang.Exception;
public class CustomRunListener extends RunListener{
private Map<String,TestSuiteDetails> map = new LinkedHashMap<>();
private long testSuiteStartTime;
private long testSuiteElapsedTime;
private int ignoredCount;
public void testRunStarted(Description description) throws Exception {
testSuiteStartTime = System.currentTimeMillis();
}
public void testStarted(Description description) throws Exception {
TestSuiteDetails testSuiteDetails = new TestSuiteDetails();
testSuiteDetails.setTestCaseName(description.getMethodName());
String[] arr = description.getTestClass().getName().split("\\.");
String name = arr[arr.length-1];
testSuiteDetails.setTestClassName(name);
String[] arr1 = name.split("_");
String testSuite = arr1[0];
testSuiteDetails.setTestSuiteNmae(testSuite);
testSuiteDetails.setTestStatus("Passed");
testSuiteDetails.setStartTime(System.currentTimeMillis());
map.put(description.getMethodName(),testSuiteDetails);
}
public void testFinished(Description description) throws Exception {
TestSuiteDetails testSuiteDetails= null;
if(map.containsKey(description.getMethodName())){
testSuiteDetails = map.get(description.getMethodName());
testSuiteDetails.setElaspsedTime(TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()-testSuiteDetails.getStartTime()));
}
map.put(description.getMethodName(),testSuiteDetails);
}
public void testRunFinished(org.junit.runner.Result result) throws Exception {
testSuiteElapsedTime = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()-testSuiteStartTime);
}
public void testFailure(Failure failure) throws Exception {
TestSuiteDetails testSuiteDetails= null;
if(map.containsKey(failure.getDescription().getMethodName())){
testSuiteDetails = map.get(failure.getDescription().getMethodName());
}else{
testSuiteDetails = new TestSuiteDetails();
}
testSuiteDetails.setTestCaseName(failure.getDescription().getMethodName());
testSuiteDetails.setTestDescription(failure.getException().toString());
testSuiteDetails.setTestStatus("Failed");
map.put(failure.getDescription().getMethodName(),testSuiteDetails);
}
public void testIgnored(Description description) throws Exception {
TestSuiteDetails testSuiteDetails= null;
if(map.containsKey(description.getMethodName())){
testSuiteDetails = map.get(description.getMethodName());
}else{
testSuiteDetails = new TestSuiteDetails();
testSuiteDetails.setTestCaseName(description.getMethodName());
String[] arr = description.getTestClass().getName().split("\\.");
String name = arr[arr.length-1];
testSuiteDetails.setTestClassName(name);
String[] arr1 = name.split("_");
String testSuite = arr1[0];
testSuiteDetails.setTestSuiteNmae(testSuite);
ignoredCount++;
}
testSuiteDetails.setTestStatus("Ignored");
map.put(description.getMethodName(),testSuiteDetails);
}
public int getIgnoredCount() {
return ignoredCount;
}
public void setIgnoredCount(int ignoredCount) {
this.ignoredCount = ignoredCount;
}
public Map<String, TestSuiteDetails> getMap() {
return map;
}
public long getTestSuiteStartTime() {
return testSuiteStartTime;
}
public long getTestSuiteElapsedTime() {
return testSuiteElapsedTime;
}
}
am using this pojo for holding test suite details
public class TestSuiteDetails {
private String testClassName;
private String testSuiteNmae;
private String testCaseName;
private String testStatus;
private String testDescription;
private long startTime;
private long elaspsedTime;
public String getTestClassName() {
return testClassName;
}
public void setTestClassName(String testClassName) {
this.testClassName = testClassName;
}
public String getTestCaseName() {
return testCaseName;
}
public void setTestCaseName(String testCaseName) {
this.testCaseName = testCaseName;
}
public String getTestStatus() {
return testStatus;
}
public void setTestStatus(String testStatus) {
this.testStatus = testStatus;
}
public String getTestDescription() {
return testDescription;
}
public void setTestDescription(String testDescription) {
this.testDescription = testDescription;
}
public long getStartTime() {
return startTime;
}
public void setStartTime(long startTime) {
this.startTime = startTime;
}
public long getElaspsedTime() {
return elaspsedTime;
}
public void setElaspsedTime(long elaspsedTime) {
this.elaspsedTime = elaspsedTime;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TestSuiteDetails that = (TestSuiteDetails) o;
if (testClassName != null ? !testClassName.equals(that.testClassName) : that.testClassName != null)
return false;
return testCaseName != null ? testCaseName.equals(that.testCaseName) : that.testCaseName == null;
}
#Override
public int hashCode() {
int result = testClassName != null ? testClassName.hashCode() : 0;
result = 31 * result + (testCaseName != null ? testCaseName.hashCode() : 0);
return result;
}
public String getTestSuiteNmae() {
return testSuiteNmae;
}
public void setTestSuiteNmae(String testSuiteNmae) {
this.testSuiteNmae = testSuiteNmae;
}
}
now after adding the listener - you can simple utilize it later
HashMap<String, TestSuiteDetails> myTestResultMap = customRunListener.getMap();
I have created a method in which i have multiple if conditions. Now i want to refactor these if conditions. What would be the best design pattern/strategy to overcome multiple if conditions?
if
(
poConfiguration.strSampleLoaderPluginClass != null
&& poConfiguration.strSampleLoaderPluginClass.equals("") == false
)
{
setSampleLoaderPluginClass(poConfiguration.strSampleLoaderPluginClass);
}
if
(
poConfiguration.strPreprocessingPluginClass != null
&& poConfiguration.strPreprocessingPluginClass.equals("") == false
)
{
setPreprocessingPluginClass(poConfiguration.strPreprocessingPluginClass);
}
if
(
poConfiguration.strFeatureExtractionPluginClass != null
&& poConfiguration.strFeatureExtractionPluginClass.equals("") == false
)
{
setFeatureExtractionPluginClass(poConfiguration.strFeatureExtractionPluginClass);
}
if
(
poConfiguration.strClassificationPluginClass != null
&& poConfiguration.strClassificationPluginClass.equals("") == false
)
{
setClassificationPluginClass(poConfiguration.strClassificationPluginClass);
}
Please share your thoughts with implementations, if possible. Thanks in advance
My first idea would be the polymorphism (Click here for more info), it depends from the concrete situation:
interface MyInterface {
public boolean checkCondition(PoConfiguration poConfiguration);
public void process(PoConfiguration poConfiguration);
}
public class SampleLoader implements MyInterface {
public boolean checkCondition(PoConfiguration poConfiguration) {
return poConfiguration.strSampleLoaderPluginClass != null
&& !poConfiguration.strSampleLoaderPluginClass.isEmpty();
}
public void process(PoConfiguration poConfiguration) {
setSampleLoaderPluginClass(poConfiguration.strSampleLoaderPluginClass);
}
}
public class ClientAPI {
public void caller() {
for (MyInterface current : this.myInterfaces) {
if (current.checkCondition(current)) {
current.process();
}
}
}
You might try something like the following:
Create a Configuration class that contains ConfigurationItems
Each ConfigurationItem would have a name, value and a default value
As an improvement, you may want to create static values for the configuration items instead of using Strings.
TestConfig main Class
package com.example.config;
public class TestConfig {
static TestConfig me;
static String[][] confSettings = {{"sampleLoader","loaderDefault"}
,{"preProcessing","preProcessingDefualt"}
,{"featureExtraction","featureExtractionDefault"}
,{"classification","classificationDefault"}
};
// Object fields
Configuration configuration;
public static void main(String[] args) {
// TODO Auto-generated method stub
me = new TestConfig();
me.doWork();
}
private void doWork() {
configuration = new Configuration();
for (int i=0; i < confSettings.length; i++) {
configuration.addConfigurationItem(confSettings[i][0], confSettings[i][1], null);
}
configuration.setConfigurationItemDefault("classification", "newValue");
System.out.println("sampleLoader = " + configuration.getConfigurationItemValue("sampleLoader"));
System.out.println("classification = " + configuration.getConfigurationItemValue("classification"));
}
}
Configuration Class
package com.example.config;
import java.util.ArrayList;
import java.util.HashMap;
public class Configuration {
// Class fields
// Object fields
HashMap<String,Integer> itemNames;
ArrayList<ConfigurationItem> items;
public Configuration() {
items = new ArrayList<ConfigurationItem>();
itemNames = new HashMap<String,Integer>();
}
public Configuration addConfigurationItem(String name, String defaultValue, String value) {
if (itemNames.containsKey(name)) {
// handle duplicate configuration item
} else {
items.add(new ConfigurationItem(name, defaultValue, value));
Integer loc = new Integer(items.size()-1);
itemNames.put(name, loc);
}
return this;
}
public void setConfigurationItemDefault(String name, String defaultValue) {
int loc = getConfigurationItemIndex(name);
if (loc > -1) {
items.get(loc).setDefaultValue(defaultValue);
}
}
public String getConfigurationItemValue(String name) {
int loc = getConfigurationItemIndex(name);
if (loc > -1) {
return items.get(loc).getValue();
} else {
// handle unknown parameter
return null;
}
}
private int getConfigurationItemIndex(String name) {
if (itemNames.containsKey(name)) {
return itemNames.get(name);
} else {
// handle unknown parameter
return -1;
}
}
}
ConfigurationItem Class
package com.example.config;
public class ConfigurationItem {
// Object fields
String name;
String value;
String defaultValue;
public ConfigurationItem(){};
public ConfigurationItem(String name, String defaultValue, String value) {
this.setName(name).setDefaultValue(defaultValue).setValue(value);
}
public ConfigurationItem setName(String name) {
this.name = name;
return this;
}
public ConfigurationItem setValue(String value) {
this.value = value;
return this;
}
public ConfigurationItem setDefaultValue(String defaultValue) {
this.defaultValue = defaultValue;
return this;
}
public String getValue() {
if (value == null || value.length() == 0) {
return defaultValue;
} else {
return value;
}
}
}