I have the following code:
sshCPList.add(new SSHParameter("ssh root#io1", "Password:", "(yes/no)?"));
sshCPList.add(new SSHParameter(rootpwd, rootPrompt, null));
sshCPList.add(new SSHParameter("ssh root#io1", "Password:", "(yes/no)?"));
sshCPList.add(new SSHParameter(rootpwd, rootPrompt, null));
if(!ssh2.sendSshShellCommandToUnknownHost(sshCPList)){
theLogger.error("Failed to Authorize the PMF function to login as root");
result = false;
}
I want to define the following:
when(ssh2.sendSshShellCommandToUnknownHost(*a specific List which contains the four SSHParameter object or has 4 items or sonmething*).thenReturn(false);
The problem is I can not define that List as a proper input.
Any advice or solution?
You can use eq(T value) where value is that specific list.
Something like:
List<SSHParameter> expectedList = prepareExpectedList();
when(ssh2.sendSshShellCommandToUnknownHost(eq(expectedList)).thenReturn(false)
prepareExpectedList(); returns a list that is equals to the input that you are going to supply in the test.
see http://docs.mockito.googlecode.com/hg/latest/org/mockito/Matchers.html
In order to generate a custom Matcher you can use:
private static class MyListMatcher extends ArgumentMatcher<List<SSHParameter>> {
private List<SSHParameter> expectedList;
private MyListMatcher (List<SSHParameter> expectedList) {
this.expectedList= expectedList;
}
#Override
public boolean matches(Object obj) {
List<SSHParameter> listToMatch = (List<SSHParameter>) obj;
boolean result = true;// check whatever you want between listToMatch and expectedList (size, elements etc.);
return result;
}
}
and use it:
when(ssh2.sendSshShellCommandToUnknownHost(argThat(new MyListMatcher(expectedList))).thenReturn(false);
Related
So I have to make two methods:
void setUnique( boolean value)
boolean getUnique()
setUnique allows the client to set whether or not to allow duplicates( true means no duplicates, false means duplicates allowed,
getUnique is to return the current setting for unique
My assignment is I have to create a SortedIntList. java and a SortedIntListTest.java and I have to have these two methods included for when I test my list.
This is what I have so far and I already know its not correct as it has errors all over it:
public void setUnique(boolean value)
{
if(!list.contains(value))
{
list.add(value);
return index == true;
}
else
{
return index == false;
}
}
public boolean getUnique()
{
//return value ;
}
Now I've seen people use the hashset method. However we havnt learn that in class yet so it most likely wont be allowed to be used. I am stuck on this and would really like some help on another way of now allowing duplicates into the arraylist without using the hashset method
first of all above method public void setUnique(boolean value) it's return type is void but you are returning some boolean value whichis wrong.
now as per me your requirement there will be one boolean flag which indicate whether client wants duplicate values or not.
so in your class take one boolean variable "flag" and implement setter and getter for that variable. client will change that flag whenever he want to change.
now create one method which return List.
public List<Integer> getList(List<Integer> inputList){
List<Integer> list=new ArrayList<Integer>();
if(flag){
for(Intger i:inputList){
if(!list.contains(i)){
list.add(i);
}
}
}
else{
list=inputList;
}
return list;
}
You can write SortedIntList.java like this
public class SortedIntList {
private boolean isUnique;
private ArrayList<Integer> arrayList = new ArrayList<>();
public boolean isUnique() {
return isUnique;
}
public void setIsUnique(boolean isUnique) {
this.isUnique = isUnique;
}
public void addElement(int element){
//While inserting element, it will check whether isUnique is set or not
if(isUnique){
//If set, then it will check whether the list contains that element, if Yes, then skip it.
if(arrayList.contains(element)){
return;
}
}
arrayList.add(element);
}
// Add your custom methods for sorting purpose
public List getArray(){
return arrayList;
}
}
And SortedIntListTest.java like this
public class SortedIntListTest {
public static void main(String[] args) {
SortedIntList list = new SortedIntList();
list.setIsUnique(true);
list.addElement(10);
list.addElement(5);
list.addElement(10);
list.addElement(8);
System.out.println(list.getArray());
}
}
Based on the inputs, here is the template code to fill in. To find duplicates in array list, use contains method on list
public class SortedIntList<Integer> extends AbstractList<Integer>{
private List<Integer> myList = new LinkedList<Integer>
private boolean isunique;
public void add(int value){
Case 1: if duplicates are allowed
//add value to myList
Case 2: duplicates are not allowed
while adding you need to traverse the list if there is any such value
//sort the list
}
public void setUnique(boolean unique){
//set isUnique
//if value is changing from non-unique to unique
//traverse the list if there is any duplicate values remove them
}
public boolean isUnique(){
return isUnique;
}
}
I have the following classes:
class ServiceSnapshot {
List<ExchangeSnapshot> exchangeSnapshots = ...
...
}
class ExchangeSnapshot{
Map<String, String> properties = ...
...
}
SayI have a collection of ServiceSnapshots, like so:
Collection<ServiceSnapshot> serviceSnapshots = ...
I'd like to filter the collection so that the resulting collection of ServiceSnapshots only contains ServiceSnapshots that contain ExchangeSnapshots where a property on the ExchangeSnapshots matches a given String.
I have the following untested code, just wondering is there a cleaner/more readable way to do this, using Java 7, and maybe Google Guava if necessary?
Updtae: Note also that the code sample I've provided below isn't suitable for my purposes, since I'm using iterator.remove() to filter the collection. It turns out I cannot do this as it is modifying the underlying collection , meaning subsequent calls to my method below result in fewer and fewer snashots due to previous calls removing them from the collection - this is not what I want.
public Collection<ServiceSnapshot> getServiceSnapshotsForComponent(final String serviceId, final String componentInstanceId) {
final Collection<ServiceSnapshot> serviceSnapshots = getServiceSnapshots(serviceId);
final Iterator<ServiceSnapshot> serviceSnapshotIterator = serviceSnapshots.iterator();
while (serviceSnapshotIterator.hasNext()) {
final ServiceSnapshot serviceSnapshot = (ServiceSnapshot) serviceSnapshotIterator.next();
final Iterator<ExchangeSnapshot> exchangeSnapshotIterator = serviceSnapshot.getExchangeSnapshots().iterator();
while (exchangeSnapshotIterator.hasNext()) {
final ExchangeSnapshot exchangeSnapshot = (ExchangeSnapshot) exchangeSnapshotIterator.next();
final String foundComponentInstanceId = exchangeSnapshot.getProperties().get("ComponentInstanceId");
if (foundComponentInstanceId == null || !foundComponentInstanceId.equals(componentInstanceId)) {
exchangeSnapshotIterator.remove();
}
}
if (serviceSnapshot.getExchangeSnapshots().isEmpty()) {
serviceSnapshotIterator.remove();
}
}
return serviceSnapshots;
}
Using Guava:
Iterables.removeIf(serviceSnapshots, new Predicate<ServiceSnapshot>() {
#Override
public boolean apply(ServiceSnapshot serviceSnapshot) {
return !Iterables.any(serviceSnapshot.getExchangeSnapshots(), new Predicate<ExchangeSnapshot>() {
#Override
public boolean apply(ExchangeSnapshot exchangeSnapshot) {
String foundComponentInstanceId = exchangeSnapshot.getProperties().get("ComponentInstanceId");
return foundComponentInstanceId != null && foundComponentInstanceId.equals(componentInstanceId);
}
});
}
});
I may have a ! missing or inverted somewhere, but the basic strategy is to remove any ServiceSnapshot objects that do not have any ExchangeSnapshot whose ID matches.
suppose I have defined a List as
private BlockingQueue<MyDelayed> DelayedIds = new DelayQueue<>();
class MyDelayed is like:
private class MyDelayed implements Delayed {
private String myId;
private Long creationTime;
MyDelayed (String myId) {
this.myId= myId;
this.creationTime = System.currentTimeMillis();
}
String getMyId() {
return this.myId;
}
#Override
public long getDelay(TimeUnit unit) {
//TODO
}
#Override
public int compareTo(Delayed o) {
//TODO
}
}
Now suppose that I want to add an Object of class MyDelayed in DelayedIds list.
I can do it by using add function.
But If I want to add obbject in list only if list does not contain an object of class MyDelayed which has the same myId attribute which I am trying to insert.
Obviously DelayedIds .contains(new MyDelayed(myId)) will not work.
Is there any easy way to check this thing ?
Am I missing something ?
You could write something like this and compare every element in the list to see if it contains your id. If at any point you find a matching one you return true, if the loop finished having found none it returns false.
public boolean contains(String id){
for (MyDelayed md : DelayedIds){
if(md.getMyId().equals(id)){
return true;
}
}
return false;
}
Now to check before adding you would do something like:
if(!contains(myNewObject.getMyId())){
DelayedIds.add(myNewObject)
}
Also, I'd suggest that you rename DelayedIds to delayedIds in order to follow coding standards (see Variables).
Can someone get me out of LambdaJ pit I fell into please?
let's assume I have a list of objects of this class:
private class TestObject {
private String A;
private String B;
//gettters and setters
}
Let's say I want to select the objects from the list where A.equals(B)
I tried this:
List<TestObject> theSameList = select(testList, having(on(TestObject.class).getA(), equalTo(on(TestObject.class).getB())));
but this returns an empty list
And this:
List<TestObject> theSameList = select(testList, having(on(TestObject.class).getA().equals(on(TestObject.class).getB())));
but that throws an exception [EDIT: due to known limitations of proxying final classes]
Note, One way of getting around this is to have a method that compares the two fields inside the TestObject, but let's assume I cannot do this for a reason of your choice.
What am I missing?
After poking and fiddling with LambdaJ to match on the fields of the same object, the only solution that is working for me is writing a custom matcher. Here's quick and dirty implementation of one that would do the job:
private Matcher<Object> hasPropertiesEqual(final String propA, final String propB) {
return new TypeSafeMatcher<Object>() {
public void describeTo(final Description description) {
description.appendText("The propeties are not equal");
}
#Override
protected boolean matchesSafely(final Object object) {
Object propAValue, propBValue;
try {
propAValue = PropertyUtils.getProperty(object, propA);
propBValue = PropertyUtils.getProperty(object, propB);
} catch(Exception e) {
return false;
}
return propAValue.equals(propBValue);
}
};
}
The PropertyUtils is the class from org.apache.commons.beanutils
The way to use this matcher:
List<TestObject> theSameList = select(testList, having(on(TestObject.class), hasPropertiesEqual("a", "b")));
I am relatively inexperienced with java & generics, so please excuse me if this is a stupid question.
I have 3 very similar helper methods called verifyTextualSort, verifyNumericSort and verifyDateSort.
The 3 methods follow the same pattern with only a slight difference in them:
private boolean verifyTextualSort(...) {
ArrayList<String> list = new ArrayList<String>();
// Do common stuff with the list
// Do textual-specific stuff
// Do common stuff with the list
}
private boolean verifyNumericSort(...) {
ArrayList<Integer> list = new ArrayList<Integer>();
// Do common stuff with the list
// Do Numeric-specific stuff
// Do common stuff with the list
}
Is there some way I can combine them into one method, passing somehow the type (Integer, String, Date) as a parameter? I have to be able to know which is the type from inside the method so that I can do the correct specific stuff.
You need three method for the specific stuff. However for the common stuff you can create a common method they both call.
private boolean verifyNumericSort(...) {
List<Integer> list = new ArrayList<Integer>();
commonStuff1(list);
// Do Numeric-specific stuff
commonStuff2(list);
}
You could pass a Class as a parameter, if that is what you want (as you said, passing the type as a parameter):
public <T> void test(List<T> l, T t, Class<T> c) {
System.out.println(c.getName());
System.out.println(l.get(0).getClass().getName());
System.out.println(t.getClass().getName());
}
All the sysouts above will print out the name of the class, so you'll be able to choose which one suits you the best.
You can't do that by introspection using the Generics because of type erasure. But if the list is not empty, you can check the type of the first element and then invoke appropriate method.
since you have 3 fields you can do this..
class A
{
private Date date = null;
private Integer int = null;
private String text = null;
//add getters and setters for these fields
}
and now pass this class Object as an arguement to that method
public boolean verify(A a){
a.getDate();
a.getInt()
//etc and do your stuff
}
You need generics and refactoring:
private boolean verifyTextualSort(List<String> strings) {
commonStuffA(strings);
// Do textual-specific stuff
commonStuffB(strings);
return true; // ?
}
private boolean verifyNumericSort(List<Integer> ints) {
commonStuffB(ints);
// Do Numeric-specific stuff
commonStuffB(ints);
return true; // ?
}
private void commonStuffA(List<?> things) { // This method accept a list of anything
// Do common stuff A with the list
}
private void commonStuffB(List<?> things) { // This method accept a list of anything
// Do common stuff B with the list
}
private void someCallingMethod() {
List<String> strings = new ArrayList<String>();
verifyTextualSort(strings);
List<Integer> ints = new ArrayList<Integer>();
verifyTextualSort(ints);
}
I think you could possibly do something similar to this:
public <T extends Object> boolean verify(T t)
{
if(!(t==null))
{
if(t instanceof Date)
{
//Do date verify routine
return true;
}
else if(t instanceof String)
{
//Do String verify routine
return true;
}
else
{
//Do default verify routine which could be Integer
return true;
}
}
return false;
}
NOTE:
This is not tested.
As others have mentioned, you can't do that with generics because of type erasure (see the other answers for a link to type erasure). I believe you can get a reasonable solution (without instanceof) with polymorphism. Here is an example:
public class VerifySort
{
public static void main(String[] args)
{
VerifySort verifySort = new VerifySort();
Date testDate = new Date();
Integer testInteger = 17;
String testString = "Blammy";
verifySort.verify(testString);
verifySort.verify(testInteger);
verifySort.verify(testDate);
}
private boolean verify(Date parameter)
{
SimpleDateFormat dateFormat = new SimpleDateFormat();
System.out.print("Date parameter: ");
System.out.println(dateFormat.format(parameter));
return true;
}
private boolean verify(Integer parameter)
{
System.out.print("Integer parameter: ");
System.out.println(parameter);
return true;
}
private boolean verify(String parameter)
{
System.out.print("String parameter: ");
System.out.println(parameter);
return true;
}