Java string comparison fails - java

I've been looking for a mistake in my code for hours now but I simply can't find it.
I could locate that the mistake is in this part of my code:
public String getType(File file)
{
String type = null;
try
{
type = URLConnection.guessContentTypeFromName(file.getAbsolutePath());
if (type.startsWith("image"))
{
Log.d(logTag, file.getAbsolutePath());
}
}
catch (Exception e){}
return type;
}
This works absolutely fine but when I do the string comparison directly before the return statement I don't get all types which start with "image".
The same thing happens when I don't use the exception handling block.
I've also displayed the integer values of the string and they do equal.
In case it matters: This is an Android project.
Edit:
E.g I get
/storage/emulated/0/WhatsApp/Media/WhatsApp Images/IMG-20150906-WA0000.jpg
in both cases whereas I receive
/storage/emulated/0/Profilbilder/18186367897.jpg
only when I use the code above. And no Exception is thrown for this file.
Edit:
I created a new project and it works as expected now. Since my new code is not exactly the same but almost, I can't tell whether it was a logical mistake or the compiler

When file is null or URLConnection throws some exception, type must be null, then there is a nullpointerException on type.startsWith("image")

Related

Mockito: No such instance method

I'm writing testcases for below given method.
Method:
#Override
public void removeAllConnections(String uuid, String userName, String oimId) {
customLogger.debug(Thread.currentThread().getStackTrace()[1].getMethodName(), userName, null, null, accessProviderBuilder.getUserName(), accessProviderBuilder.getUuid());
UserAccessBean userAccessBean = new UserAccessBean(userName);
userAccessBean.setOimid(oimId);
userAccessBean.setToken("");
log.info("removeAllConnections:oimid:"+userAccessBean.getOimId());
UserProfileDetailBean userProfileDetail = accessClient.getAccess(userAccessBean,applicationForCsr);
Set<AccountAccess> accountAccesses = userProfileDetail.getAccountAccessList();
try {
removeAllConnectionsExceptPrimary(oimId, userName, accountAccesses);
removePrimaryConnection(oimId, userName, accountAccesses);
} catch (ConnectionStateException e) {
throw new ConnectionStateException(ConnectionNameNotRemoved, CONNECTION_REMOVAL_FAILED_MSG);
} catch (InternalServerErrorException e) {
throw new InternalServerErrorException(INTERNAL_SERVER_ERROR, INTERNAL_SERVER_ERROR_MSG);
}
}
Below snippet is test case for given method.
Testcase:
#Test
public void testRemoveAllConnections() {
UserAccessBean userAccessBean = new UserAccessBean(userName);
when(accessClient.getAccess(userAccessBean,"CSR")).thenReturn(userProfileDetail);
when(userProfileDetail.getAccountAccessList()).thenReturn(accountAccesses);
String applicaionForCSR = "CSR";
ReflectionTestUtils.setField(service, "applicationForCsr", applicaionForCSR);
service.removeAllConnections(uuid, userName, oimId);
}
While debugging the code, my execution is failing at below given line as the value of userProfileDetail is null.
Set<AccountAccess> accountAccesses = userProfileDetail.getAccountAccessList();
While doing inspect element on accessClient.getAccess(userAccessBean,applicationForCsr) it is throwing below error. Pretty sure it is some silly mistake but unable to trace it.
Error:
No such instance method: 'UserProfileDetailBean
v1.AccessService$$EnhancerByMockitoWithCGLIB$$a852895d.getAccess
(UserAccessBean)'
Application: Spring Boot 1.5.0
Library: Mockito 2.7.X
I can suggest three possible solutions (or more like 2.5):
a) Override the equals method of UserAccessBean, so that two UserAccessBeans are equal if and only if their names are equal. Of course, this might interfere with your productive code and I would not change the equals method only for testing.
b) Since the username doesn't actually play a vital role in your test (the tests itself defines what the username is), you can simply ignore the details with...
when(accessClient.getAccess(Mockito.any(UserAccessBean.class),Mockito.eq("CSR"))).thenReturn(userProfileDetail);
This way, the userProfileDetail will be returned for any value of the first parameter. Of course, you lose detail here, so for example, the test would be correct if the username was somehow wrong, but chances are that this isn't possible in your test anyway.
Mockito.any(...) is a so called matcher that tells Mockito to "use" this rule no matter what value is given for the parameter in question. Anything you put there is ok for Mockito. Mockito.eq("CSR") tells it, that this parameter must be equal to "CSR". So, the whole rule is...
If someone calls accessClient.getAccess, no matter what the first parameter ist, but the 2nd must be equal to "CSR", then return userProfileDetail.
So, with this, the first parameter can be anything. So, for example, the following to calls will be accepted:
accessClient.getAccess(new UserAccessBean("correct name"), "CSR");
accessClient.getAccess(new UserAccessBean("totally wrong name"), "CSR");
...because it does not matter what the first parameter is, ANY value will be accepted. So, what you "lose" there is the ability to check if the UserAccessBean is the correct one (because any is accepted). But in your case, since you only define those UserAccessBeans in the test anyway, this should not be a problem.
But if it is, I can offer two workarounds...
c) Use either a customer Matcher (that checks the name of the UserAccessBean) or use the Mockito.any(...) as above and an ArgumentCaptor to check if the name was correct in the end...
ArgumentCaptor<UserAccessBean> captor = ArgumentCaptor.forClass(UserAccessBean.class);
Mockito.verify(accessClient).getAccess(captor.capture(),Mockito.eq("CSR"));
assertEquals(captor.getValue().getName(), "myName");

Is it acceptable to throw exceptions when not getting expected JSON data?

Working on an android app which gathers data from the Open Weather API as a JSON. However the JSON does not always contain the same keys (ie. sometimes cloud data or a weather description is included, sometimes it isn't).
Right now my code looks like (with some extra getters/setters I didn't include here):
public class WeatherDescrip {
private String weather;
private String weather_Desc;
private String icon;
public WeatherDescrip(JSONObject weatherObj) {
try {
weather = weatherObj.getString("main");
} catch (JSONException e) {
weather = null;
e.printStackTrace();
}
try {
weather_Desc = weatherObj.getString("description");
} catch (JSONException e) {
weather_Desc = null;
e.printStackTrace();
}
try {
icon = weatherObj.getString("icon");
} catch (JSONException e) {
icon = null;
e.printStackTrace();
}
}
}
Basically if the JSON I get from the API call doesn't have the necessary key I let the program throw an exception, which will usually happen with at least one piece of data each time the app is run (there is more done like this).
If anyone could please let me know whether this is an acceptable way to code, and possibly how to better implement this I would much appreciate it.
If you haven't noticed I'm also a total noob, sorry in advance if this is a terrible way of doing this.
Many Thanks
This is generally not the correct forum for asking opinions, as you're asking for subjective opinions, there's technically no way to gauge a 'correct' answer, although you're free to select whatever answer you choose, if any ;-)
But in the nature of good will, I'll give you a few of my opinions.
Firstly, Exceptions are for just that, exceptions. If you have a scenario where you are in control of the code, and are aware of a potential for something not to occur in an 'ideal' way (e.g. like this, you're receiving dodgy data), then code for it, i.e.
if (data.contains("somethingOfInterest")) {
consume(data);
} else {
getDataFromSomewhereElse();
}
Rather than throw an exception, and force your program to handle it somewhere else (or not). Here's some additional information on why it's not a good idea to use exceptions for control flow.
Also, and this is advice from personal experience; in most scenarios, it's a good idea to do as little as makes sense within an Object's constructor, as it's more ugly to recover if exceptions do occur inside a constructor's method body. Instead, it may be better to encapsulate the logic you have there in some other factory-esque class or method, passing only the gathered data to the constructor. Something like:
public class WeatherDescrip {
private String weather;
private String weather_Desc;
private String icon;
public WeatherDescrip(String weather, String weather_Desc, String icon) {
this.weather = weather;
this.weather_Desc = weather_Desc;
this.icon = icon;
}
}
...
public static WeatherDescrip createWeatherDescrip(JSONObject weatherObj) {
if (!weatherObj.containsKey("main")
|| !weatherObj.containsKey("description")
|| !weatherObj.containsKey("icon")) {
throw SomeNewMeaningfulException("That I understand and can explicitly handle");
or....
return getMyDataFromSomeWhereElse();
}
return new WeatherDescrip(
weatherObj.getString("main"),
weatherObj.getString("description"),
weatherObj.getString("icon")
);
}
I hope this helps.
It's acceptable to throw exceptions whenever you decide. You just need to play how you want to handle it.
Is it acceptable to crash the program and boot your user back to the home screen? Absolutely not. Ever
Just read your data and handle the exceptions gracefully - no icon? Display a default. No data? Tell the user there is a problem right now so they aren't misled by the old data being displayed.
An alternate to avoid the majority of exceptions is to use GSON and Retrofit (I've linked a useful set of tutorials, not the home of GSON or Retrofit). With GSON you can create a model object, automatically map the data and then on your getters always return a value even if the JSON was incomplete
Example:
class MyObj {
#SerializedName("main")
private String weather;
public String getWeather() {
String weatherResult = weather;
if (weatherResult == null || "".equals(weatherResult) {
weatherResult = getString(R.strings.weather_unavailable);
}
return weatherResult;
}
}
Throwing an exception is usually reserved for when an error occurs, rather than having it it being an expected result of running your code, since there is overhead in throwing an exception which can make your program execute (slightly) slower.
Realistically, it can be used whenever you like, however you like, but I might instead suggest using has() to check if the key exists before trying to access it. It's a more efficient way of achieving the same result, without having to throw or catch an exception.
if(weatherObj.has('description')) {
weather_Desc = weatherObj.getString("description");
} else {
weather_Desc = null;
}

Validate if the input in the setter method is double or String

The value in the setter comes from a JTextFeild. I have try different method but it isn't working. I want to print out my custom error message. It isn't working for double, the String variable print the error message in the stacktrace.
This is the String method.
public void setInventoryname(String inventoryname) throws Exception {
if(inventoryname.isEmpty()){
throw new Exception ("Medicine name cannot be empty");
}
else{
this.inventoryname = inventoryname;
}
}
result of the string method.
java.lang.Exception: Medicine name cannot be empty
This is the double method
public void setInventorydesc(double inventorydesc) throws Exception {
if(!Double.toString(inventorydesc).isEmpty()){
throw new Exception("Set a number in Inventory qunatity");
}
else
{
this.inventoryqty = inventorydesc;
}
}
The result of double
java.lang.NumberFormatException: For input string: "dfasdf"
I want to receive the same result as of string for double.
Use Validator api and put your message.
Check org.apache.commons.validator
Double variable can never be empty, it can be zero.
You'll have to initialize the double variable, otherwise compiler will throw error.
If the zero value is what you mean by empty then you can compare that with zero to check.
You can not keep double variable uninitialized, it's all right with string but not with double.
Maybe you should step back and ask yourself for a second: does that really make sense?
What I mean is: you have two different methods, that take completely different arguments; and that have completely semantics; and still you are asking that both give you the same error message?
Lets have a closer look. First of all, throwing Exception objects is really bad practice. If you want to use a checked exception, then you better create your own subclass and use that. If you prefer unchecked exceptions, then you could throw IllegalArgumentException.
And just for the record: when you receive a double argument, that thing is always a number. Somebody already took the incoming string and made it a number. So your method is absolutely pointless. In other words: besides the things I told you, you should have a look into the code calling your methods.
Finally: read java language style guides. You should use camelCase for your variable and method names. And there is absolutely no need to abbreviate, call the thing inventoryQuantity; then everybody knows what it is! And you know, it is absolutely wrong that a method called setInventoryDesc changes the value of a field called inventoryQuantity. This might sound like nitpicking, but be assured: being precise and disciplined is one of the core practices in programming!
Pass inventorydesc as a string first - and then work with it ...
public void setInventorydesc(String inventorydesc) throws Exception {
if(inventorydesc==null ||inventorydesc.isEmpty()){
throw new Exception("Set a number in Inventory qunatity");
}
else
{
try{
this.inventoryqty = Double.parseDouble(inventorydesc);
}catch (NumberFormatException e){
throw new Exception("Inventory qunatity must be double");
}
}
}
If the number comes from a text field first you must parse it to get the double.
public static void setInventorydesc(String inventorydesc) throws Exception {
try{
double convertedInventorydesc = Double.parseDouble(inventorydesc);
this.inventoryqty = convertedInventorydesc;
}
catch (NumberFormatException ex){
throw new Exception("Set a number in Inventory quantity",ex);
}
}
try using this method
Double.isNan(double d)
Use this method to verify if the value is numeric or not.Or try to type cast the the string to double if it goes into catch block then display error message to user

Getting method is undefined for the type String error while resolving IP

I am trying to convert IP to web address and vice versa in a tool which is created using Swing.
The action listener part is here
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==check1)
{
String ipresult,queryip=inputip.getText();
try
{
InetAddress ip1=InetAddress.getByName(queryip);
ipresult=queryip.getHostName();
outputweb.setText(ipresult);
}
catch(Exception e1)
{
outputweb.setText("Please check the IP address");
}
}
if(e.getSource()==check2)
{
String webresult,queryweb=inputweb.getText();
try
{
InetAddress web1=InetAddress.getByName(queryweb);
webresult=queryweb.getHostAddress();
outputip.setText(webresult);
}
catch(Exception e2)
{
}
}
}
I am doing this on Eclipse, so the error it says at
the line webresult=queryweb.getHostAddress(); and ipresult=queryip.getHostName();
is method is undefined for the type String
What is that I am doing wrong? I can post in the full code if anyone needs it.
Well this looks like the problem:
InetAddress ip1=InetAddress.getByName(queryip);
ipresult=queryip.getHostName();
I suspect you meant:
InetAddress ip1 = InetAddress.getByName(queryip);
ipresult = ip1.getHostName();
Basically you were calling getHostName on queryip, rather than on ip1. You then have the exact same mistake for the second piece of code - which looks sufficiently similar to the first piece that you should consider extracting a method which could be called in both cases.
However, you shouldn't just fix your code. You should take a step back and work out why you couldn't figure this out for yourself:
Did you read the error message carefully?
Did you look at the code carefully, to work out why the compiler was complaining about that line?
Do you actually understand (from a language perspective) every line of your code?
It's not a problem to not know things - it's a problem if you don't learn from your mistakes.
Below code will help in this case
String clientIp = request.getRemoteHost();
System.out.println(clientIp);
InetAddress Address =InetAddress.getByName(clientIp);
System.out.println("Testing client name:"+Address.getHostName());
getHostAddress() is not defined for the type String. It is a method of the classInetAddress but you are invoking it on queryweb which is a String
queryip is of string type as per
String ipresult,queryip=inputip.getText();
Your getting that error because string does not have a method getHostName(). Now if you were to have a object initialized that had such a method you could call it. Just guessing from your code you should make it:
ipresult=ip1.getHostName();
You should have some object that has a string field and has a method getHostName(). You may want to consider a static class with a method getHostName(String ip). This all depends on how much you need an InetAddress object

java. Method return Null. What exception I must generated?

I have this line code:
String name = Book.getName();
/*next lines of code*/
Next, variable name processing in other code without any checks.
In some cases, possible situation, when name=null and other code will exit with an error.
It is bad.
Also, I cant access to the other code.
So, what do you think, my next implementation is correct:
try
{
String name = Book.getName();
if(null== name)
throw new NullPointerException("method 'getName' return null");
/*next lines of code*/
}
catch(NullPointerException e)
{
System.out.print("Hey! Where book name? I exit!");
System.exit();
}
I have any other choose in this case?
It is possible to generate any other type of Exception or only NullPointerException?
Thanks.
Edit:
Ok,
String name = Book.getName();
it's imagine code line. In real case, I have more complex code:
List<Book> bookList= new ArrayList<Book>();
String name = null;
Iterator i = BookShop.getBooks.iterator(); //BookShop it is input parameter!
while(i.hasNext())
{
Book book = (Book) i.next;
name = book.getName();
nameList.add(name);
}
This example more full.
So, in this code input parameter BookShop Object.
What problem I can have with this Object?
BookShop can be NULL;
method BookShop.getBooks() can return NULL;
Also, getName() can return NULL too.
So, general problem next: there is no guarantee the correctness of input parameter BookShop!
And I must to consider every possible option (3 NULL)
For me, add General try-catch block and that all.
No?
You can create any exception you like by extending the Exception class, like a NoNameProvidedException for example. There are a lot of example one Google to help you do that.
I guess in your case just checking with an if if the name is null should be sufficient as you just want to do a System.exit().
Your code is a bit iffy, but I assume you're learning. You don't need to throw the NullPointerException explicitly, you can throw whatever Exceptions you like.
But you probably don't really need the Exception catching here, you can just check for the null and handle the situation appropriately if it's true.
Also, please avoid Yoda conditions. Your if statement should read
if name is null
so
if (name == null)
I would probably use IllegalStateException:
String name = Book.getName();
if (name == null) {
throw new IllegalStateException
("Method foo must not be called when the book has no name");
}
It really depends on where the state is coming from though - it's not really clear what's going wrong here.
I certainly wouldn't start catching NullPointerException - exceptions like that (and the illegal state one) shouldn't be explicitly caught. Let them bubble up, and if it's appropriate have some sort of top-level handler.
Exceptions should not be used for normal control flow. Just use the if block:
String name = Book.getName();
if (name == null) {
System.out.print("Hey! Where book name? I exit!");
System.exit();
}
/*next lines of code*/
Using try and catch in this case is unneeded. You can just write like this:
if(Book.getName() != null)
String name = Book.getName();
else
//handle the situation with null
You don't need to throw an Exception in this case - just handle the null value and you are fine.
It's more friendly for Java not to use exceptions, but just check the return value
String name = Book.getName();
if (name == null)
System.out.print("Hey! Where book name? I exit!");
else {
/*next lines of code*/
}

Categories

Resources