Trying to delete from the grid under certain condition - java

private void delete() {
if(customer.getStatus() == status.toString("Not Contacted")) {
service.delete(customer);
myUI.updateList();
setVisible(false);
}else {
Notification.show("you cannot delete this");
}
The error I get says "The method toString() in the type object is not applicable for the arguments (string)"
What I want to do is to let the delete function work only if the status is NotContacted.

What you want is
if(customer.getStatus() == status.toString().equals("Not Contacted")) {...}
Though you should want to give status a proper type to make a type-safe comparison. I suggest looking up on Enums (https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html) so that your code becomes something like
if(customer.getStatus() == Status.NOT_CONTACTED)) {...}

Related

Find all Java methods using only one specific property of a specific type of parameter

We're in the process of trying to identify everywhere that a specific type of object is used only to get a specific property from it, and pass that property into the method instead.
I'm thinking IntelliJ IDEA's "Structural Search" might be a good tool for this, but I'm not sure how to formulate the search template.
A concrete example:
public class MyClass {
public Long getId() {...}
public void setSomethingElse(int se) {...}
}
public class SomeOtherClasses {
public void shouldBeMatched(MyClass mc) {
doSomething();
mc.getId();
doSomethingElse();
}
public void shouldNotBeMatched(MyClass mc) {
doSomething();
mc.getId();
mc.setSomethingElse(14);
doSomethingElse();
}
public void alsoShouldNotBeMatched(MyClass mc) {
shouldBeMatched(mc);
}
}
In the above example, if I'm looking for methods that only use getId, then I should find shouldBeMatched, but not be bothered with shoudNotBeMatched and alsoShouldNotBeMatched, because they do something with the mc object other than call getId().
I'm thinking IntelliJ IDEA's "Structural Search" might be a good tool for this
And it is indeed. The documentation can be tough though.
Let's check Search templates, filters, and script constraints page. It goes as follows.
Let's say, you have a variable that matches a method, a toString()
method. Then this variable is actually a PsiMethod node. Retrieving
variable.parent will produce a PsiClass node, and so forth.
variable.text then will give you the entire text of the method. If you
just need the name of the method, you can use variable.name.
It seems that the task can be done by choosing the right template and writing a corresponding Groovy script.
The template is called methods of the class and can be found under Existing templates. They provide __context__variable to be used with a script.
We have to be sure matched methods have parameters. It is simple enough, just put a count filter on a $Parameter$ variable.
Then we need to extract the name of a parameter of desired type and see if it is called in the body of the method. The following script will do.
def parameters = __context__.getParameterList().getParameters();
def parameter = parameters.find { p -> p.getType().getName().equals('MyClass') };
if (parameter == null) return false;
String parameterName = parameter.getName();
String methodText = __context__.getText();
String occurrence = "${parameterName}.";
String methodCall = "${parameterName}.getId()";
return methodText.count(occurrence) > 0 && methodText.count(occurrence) == methodText.count(methodCall);
Put it in the $Method$ variable filter and verify the results.

#SuppressWarnings ArrayList<X> may not contain objects of type Y

I have a class called CompressedCardInfo that has an MtgCard as a member of it, and CompressedCardInfo's (or classes extending it) have overloaded the equals method to take into account checking if a CompressedCardInfo equals an MtgCard.
Now this isn't extremely important, as they are only warnings (they bother me however), but when I have CompressedCardInfo in an ArrayList and call ArrayList.contains or .indexOf I get the warning telling me that the list might not have objects of type MtgCard in it.
How do I suppress this specific warning about this List? Or is there a better way of handling that kind of comparison?
Thanks.
for (Pair<MtgCard, Boolean> card : decklist) {
/* Translate the set code to TCG name of course it's not saved */
card.first.setName = CardDbAdapter.getSetNameFromCode(card.first.setCode, database);
if (changedCardName == null || changedCardName.equals(card.first.mName)) {
if (mCompressedDecklist.contains(card.first)) {
CompressedDecklistInfo existingCard = mCompressedDecklist.get(mCompressedDecklist.indexOf(card.first));
if (existingCard.mIsSideboard == card.second) {
mCompressedDecklist.get(mCompressedDecklist.indexOf(card.first)).add(card.first);
} else {
mCompressedDecklist.add(new CompressedDecklistInfo(card.first, card.second));
}
} else {
mCompressedDecklist.add(new CompressedDecklistInfo(card.first, card.second));
}
if (mShowTotalDecklistPrice) {
loadPrice(card.first.mName, card.first.setCode, card.first.mNumber);
}
}
}
The calls on lines 5 (contains), 6 (indexOf), and 8 (indexOf). I get warnings there because the ArrayList is of type CompressedDecklistInfo (which is extended from CompressedCardInfo. This also happens in other places.
So I'm just going to follow best practices and fix these issues properly.

How do I get those 2 errors to go away? in and valueOf methods - Java

I have struggling a bit with those 2 small errors because Eclipse IDE "said so." I will point out the errors. To be honest, I don't know how to explain deeply about those errors. I thought they were simple and I cannot get the errors to go away.
ScheduledExecutorService timer = Executors.newScheduledThreadPool (1);
timer.scheduleAtFixedRate(new Runnable()
{
public void run()
{
if (lists. size ()> 0)
{
boolean lighted = Lamp.valueOf(Road.this.name).isLighted(); //According to Eclipse, "The method valueOf(Class<T>, String) in the type Enum<Lamp> is not applicable for the arguments (String)"
if (lighted)
{
System.out.println(lists.remove(0) + "is traversing!");
}
}
}
}, 1,1, TimeUnit. SECONDS);
and another error in my different class my package
public Lamp Blackout()
{
this.lighted = false;
if (opposite != null)
{
Lamp.valueOf(opposite).in.Blackout(); //in cannot be resolved or is not a field. It suggests me to create enum constant, which I did and it wouldn't work either.
}
Lamp nextLamp = null;
if (next != null)
{
nextLamp = Lamp.valueOf(next);
System.out.println("Green" + name () + "--------> switch to" + next);
nextLamp.light();
}
return nextLamp;
}
Your first error
Lamp.valueOf(Road.this.name).isLighted();
//According to Eclipse, "The method valueOf(Class, String) in the
type Enum is not applicable for the arguments (String)"
The method Lamp.valueOf() expects two arguments, first a class argument & then a String argument. You have just passed a String argument in the method that's why eclipse is throwing the error.
You Second error
Lamp.valueOf(opposite).in.Blackout();
//in cannot be resolved or is not a field.
It looks like an incorrect syntax to me. Check your code thoroughly. In your code methods are being chained. in should not be there. Or it may be a method in()
Shooting in the dark, because you haven't disclosed all relevant code, but you could try adding the missing parameter for valueOf here:
boolean lighted = Lamp.valueOf(Lamp.class, Road.this.name).isLighted();
and calling the in() method here:
Lamp.valueOf(Lamp.class, opposite).in(Blackout());
Please follow Java code style conventions; method names should start with a lowercase letter, so the blackout method signature should look like this instead:
public Lamp blackout()
Without seeing the code for the Lamp enum, it's impossible to know what the exact problem in the latter case is.

How to find ArrayList containing Object

I have a method from which i am returning object like
public static Object login(DataManager dataManager, String userName, String password)
ArrayList<LoginCredentialsBean> loginCredentialsList = new ArrayList<LoginCredentialsBean>();
String authenticated = "false";
Connection connection = null;
try {
connection = dataManager.getConnection();
} catch (Exception e) {
return ("Having problem in connectiong to databaste: " + e.getMessage());
}
if (connection != null) {
try {
...
try {
ResultSet rs = prepStatement.executeQuery();
try {
while (rs.next()) {
...
loginCredentialsList.add(new LoginCredentialsBean(roleId, orgaCode, passwordExpiryDate, date, status, language));
authenticated = "true";
} //end of while()
} finally {
rs.close();
}
} finally {
prepStatement.close();
}
if (authenticated.equals("true")) {
updateUserLogByInserting(connection, userName);
}
} catch(SQLException e) {
System.out.println("Could not login from dataabse:" + e.getMessage());
} finally {
dataManager.putConnection(connection);
}
}
if (authenticated.equals("true")) {
return loginCredentialsList;
} else {
return authenticated;
}
} //end of login()
Now i am testing it like
public static void main(String... args) {
MoneyTreeServices moneyTreeServices = new MoneyTreeServices();
Object result = moneyTreeServices.login("Admin", "cbas1234");
if (result instanceof ArrayList<?>) {
System.out.println("ArrayList instance");
}
System.out.println(result);
}
It returns me result like
ArrayList instance
[pk.mazars.moneyTree.bean.LoginCredentialsBean#b7ec5d]
I want to ask i am using condition like ArrayList<?>. How can i check that ArrayList that contain LoginCredentialsBean object. Like when i use
if (result instanceof ArrayList<LoginCredentialsBean>) {
}
i get error that
Can not perform instanceof check against parameterized type ArrayList<LoginCredentialsBean>. Use the form ArrayList<?>
I want to check instanceof ArrayList and arraylist has LoginCredentialsBean ?
Thank you.
The short answer is that you can't. Generics are implemented via type erasure - they're effectively a compile-time syntactic sugar to ensure you don't put an Integer into a List<String>.
The runtime objects themselves, however, are just the raw types. An instance of ArrayList doesn't know that it's an ArrayList<String> (or rather, that it was assigned to a variable with that generic type). So when you interrogate it with reflection, you cannot get any generic type info.
There are two broad types of solution I can think of. One is to iterate over the list contents and check their dynamic type - if the first element is a LoginCredentialsBean, for example, then it's reasonable to assume that you have a List<LoginCredentialsBean>. This won't work for empty lists though, which could be a problem, and can potentially give false positives (e.g. a List<Object> allParameters might happen to have a LoginCredentialsBean as its first element...)
The other is to explicitly pass metadata objects around - so in this case you'd return the Object from the login method, along with a token which describes what type of object it is. This could be a simple enum constant; or going to the other extreme you could make the tokens generically typed, such that the compiler can check this against the type of what you're returning and ensure that the tokens are type-correct.
But in any case, instanceof is too little (information), too late.
Mind you, your login method looks... odd. I don't think it should return an Object at all, as that's just lazy and completely subverting the static type system which would help you here. Rather, I think it should just return a List<LoginCredentialsBean> containing the credentials that pertain to the given login.
You have three different paths where you return. The first is if an exception is encountered when connecting to the database - in which case you should throw an exception! Returning a string with the error details is very atypical and confusing - an exceptional condition should be handled as an Exception, that's what they're for.
The other two situations are ones where you're able to look up definitive results. For the failed login case, I would just return an empty list (i.e. this username/password has no credentials whatsoever), while returning the populated list during a successful login.
If you strongly want to be able to distinguish between a login failure, and a successful login (with no credentials), then perhaps return a compound object instead, such as:
class LoginStatus {
final boolean authenticated;
final List<LoginCredentialsBean> credentials;
}
Either way, the caller knows exactly what they're getting back, and can call methods on it appropriately without having to call instanceof and typecast.
Parameterized type info is erased at compile time and instanceof is resolved at (fanfare) runtime - that is why you get that error.
What you could do is iterate over the elements in the List and instanceof them.
Cheers,
You have to check it twice.
if (result instanceof ArrayList<?>) {
System.out.println("ArrayList instance");
//cast
ArrayList<LoginCredentialsBean> list = (ArrayList<LoginCredentialsBean>) result;
///..check if list contains LoginCredentialsBean
for(int i=0; i<list.size(); i++){
if(list.get(i) instanceof LoginCredentialsBean){
System.out.println("LoginCredentialsBean instance");
}
}
}
There is no such thing like "ArrayList that contain LoginCredentialsBean"
ArrayList contains Objects, all the time.
you must iterate over the list and check each object:
for (Object o: result) {
if (!(o instanceof LoginCredentialsBean)) {
//Fail
}
}
you can use the contains(Object o) to check whether the ArrayList contains your object. With the instanceof List to check whether the given object is a List. Because of type erasure at runtime the generic type of the List wont be available
If your login method returns an Object type there is no way to check this the way you try.
Type parameters exist only on compile-time due to type erasure. You need to check if retuned object is a List or Collection or just Iterable, then iterate throuh it and check every item, if it is a instance of LoginCredentialsBean.
However, your code is an example of bad design. A method that returns a String or a list is just wrong. To make it right:
make it return List<LoginCredentialsBean>
throw a checked exception if authentication fails
public static List<LoginCredentialsBean> login(DataManager dataManager, String userName, String password) throws AuthenticationException {...}
Note: Use boolean to keep logical data instead of "true" or "false" strings.

How to disabled a combobox according to the selection in another combobox?

I have this block of code that is giving me results for a combo box, I would like it to ignore the combo box and disable it when the value "SDO/OD" is selected in the one above under the combo box for ROLE aka fcbRole. The following enables the box from the first part, but the second part does not fire off. And it gives me a warning: "This field is required"...Have you seen something like this before?
I have been tinkering with:
fcbRole.addSelectionChangedListener(new SelectionChangedListener<ModelData>()
{
#Override
public void selectionChanged(SelectionChangedEvent<ModelData> se)
{
if ("SDO/OD".equals(this.toString()))
{
fcbOfficeRegion.enable();
} else
{
fcbOfficeRegion.disable();
}
}
});
Don't use == and != to compare Strings, instead use:
if("SDO/OD".equals(this.getStringName()) // or make sure you override toString()
// enable
else
// disable
For String value equality, use equals() method and not operators. Operators does reference equality check.
So, change your code to:
if ("SDO/OD".equals(this.toString()))
{
fcbOfficeRegion.enable();
} else
{
fcbOfficeRegion.disable();
}

Categories