This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 9 months ago.
I have a com.google.cloud.storage.Blob object. I have been able to download and upload just fine with this object in my java code, but I wanted to check if something exists before starting a process.In a nutshell here is the part of my code giving me issues.
import com.google.cloud.storage.Blob;
import com.google.cloud.storage.BlobId;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
public class Function implements BackgroundFunction<GcsEvent> {
public void accept(GcsEvent event, Context context) {
String bucketname = "my_bucket";
String blob_path = "path/to/my/object.jpg";
Storage storage = StorageOptions.newBuilder().setProjectId("my_project_id").build().getService();
Blob b = storage.get(BlobId.of(bucketname, blob_path));
// this is where the null pointer exception occurs
boolean exists = b.exists();
if (exists) {
//do something
}
}
}
Eclipse doesn't seem to catch it in the IDE. and the examples seem to follow this layout as well. Would anyone know what is going on?
I am running on a Linux environment machine. (it failed in cloud function as well).
I am using the Java 11 runtime.
I feel silly. I found out that storage.get(BlobId.of(bucketname, blob_path)); will return null if it can't find the object. instead of using b.exists(), one should check if it is null with if (b != null) { //do stuff }.
Related
This question already has answers here:
java.lang.NullPointerException is thrown using a method-reference but not a lambda expression
(2 answers)
Closed 3 years ago.
I work with some legacy code that goes back decades and has a lot of objects where a field being null means "we don't have that information". As such, it has a lot of methods where it wants to do some math on fields, but only if they are not null. This leads to many ugly if statements that look like a procession of null checks, and happen multiple times per method for various length sets of things that can't be null if the contents are going to be used.
For example
public class Foo
{
public Bar getBar()
{
//returns a Bar object that may or may not be null
}
}
Then, elsewhere
if(foo1 != null && foo1.getBar() != null && foo2 != null && .... etc) {
//do math with foo1.getBar(), foo2.getBar(), etc...
}
Anywho, I made a utility to help make these look a little nicer (and also quiet down SonarQube about too many checks in an if) by making a utility class that looks like this:
public class NullCheckUtil
{
private NullCheckUtil()
{}
public static Boolean anyNull(Object... objects)
{
return Stream.of(objects).anyMatch(Objects::isNull);
}
}
Then realized that if foo1 is null, will get NullPointerException before even going in the anyNull.
Ok, lets make it a stream, so they are not evaluated on declaration:
public static Boolean anyNull(Supplier<Object>.... suppliers)
{
return Stream.of(suppliers).map(Supplier::get).anyMatch(Objects::isNull);
}
Then if check can be
if(!NullCheckUtil.anyNull(foo1, foo1::getBar, foo2, foo2::getBar,.... etc){//do the math}
And my IDE seemed happy with that, no problems. But when I ran from console, I'd get NPE with the error claiming to be on the if line again. Whaaaa?
So I did some digging and at first thought maybe this is the reason:
Does Java's ArrayList.stream().anyMatch() guarantee in-order processing?
So I changed the anyNull again to
public static Boolean anyNull(Supplier<Object>... suppliers)
{
for(Supplier<Object> supplier : suppliers)
{
if(supplier == null || supplier.get() == null)
{
return true;
}
}
return false;
}
NOPE, still doesn't fix it (for console).
Experimenting to see what could do it I changed the if to
if(!NullCheckUtil.anyNull(()->foo1, ()->foo1.getBar(), ()->foo2, ()->foo2.getBar(), etc...)
And that works fine in IDE and also in console. Tried both in Java 8.151 and Java 8.221, same behavior.
In other words
try
{
NullCheckUtil.anyNull(()->foo1, ()->foo2, ()->foo1.getBar(), ()->foo2.getBar());
}
catch(NullPointerException npe)
{
//does not happen
}
try
{
NullCheckUtil.anyNull(()->foo1, ()->foo2, foo1::getBar, foo2::getBar);
}
catch(NullPointerException npe)
{
// *DOES* happen. What tha….?
}
So there is some difference between ()->obj.method() and obj::method lambdas in that the latter gets interpreted right away on declaration? What is that?
If the Objects you want to check are always Foo, then you can rewrite the method to:
public static boolean isAnyFooNullOrReturnsAnyGetBarNull(final Foo... foos) {
return Stream.of(foos)
.map(foo -> Objects.IsNull(foo) || Objects.isNull(foo.getBar()))
.reduce(false, Boolean::logicalOr);
}
Ideone example
Notice that this example uses an immutable class Foo. This property is essential since this guarantees that Foo::getBar() for a certain instance will always return the same Bar. If this property is not given, then the problem is not solvable in a streamified solution.
This is also the reason why the attempt of using a Producer<Bar> will not work: the first call to a producer could return a non-null value, while the second call will return a null value. Some classes behave this way, i.e. they allow only a single consumption of a resource/property.
If the parameter of the method has to be Object..., then the problem is not solvable with Streams.
Found older 100% applicable and correct answer after modifying the search terms (i had tried earlier with no luck): java.lang.NullPointerException is thrown using a method-reference but not a lambda expression
It even answers why Eclipse is behaving "nice" (Eclipse bug).
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I've tried searching for this, but then I'm not sure when how to describe it.
I have a method that formats some data from a hashmap to go into a mySQL table:
private String valuesList() {
String valuesList = "";
HashMap<String,String> data = getData();
for(Map.Entry<String, String> entry : data.entrySet()) {
String value=entry.getValue();
valuesList+="'"+value+"',";
}
valuesList = valuesList.substring(0, valuesList.length() - 1);
return valuesList;
}
Most of the time that works fine, but in some cases one of the values has an apostrophe in, which leads to an output like this:
'4577314','18-02-2017','null','4566974','null','Overseas Domestic Workers' Rights Bill','1124','null'
Note the 'Overseas Domestic Workers' Rights Bill' bit at the end. I thought that would be easy to fix by changing
valuesList+="'"+entry.getValue()+"',";
to
valuesList+="'"+entry.getValue().replace("'","")+"',";
but the method now throws a null pointer exception at that line. In fact any kind of change to that string such as .trim() does the same, throwing a null.
I'm completely stumped now
You can escape quotes from value like this
value = value.replaceAll("'","''");
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I tried making a ticket using:
Ticket ticket = ForgeChunkManager.requestTicket(this, this.minecraftServer.entityWorld, ForgeChunkManager.Type.NORMAL);
The above code is in my main mod class. I get a NullPointerException when I try to run my mod.
in this case, either this.minecraftServer or this.minecraftServer.entityWorldis null.
try surrounding it with a if statement.
if (this.minecraftServer != null && this.minecraftServer.entityWorld != null){
Ticket ticket = ForgeChunkManager.requestTicket(this,
this.minecraftServer.entityWorld,
ForgeChunkManager.Type.NORMAL);
}
and for the purpose of debugging, I would suggest you separate it in two conditions:
if (this.minecraftServer == null) {
System.out.println("minecraftServer is null");
//or do anything can to warn you
} else if(this.minecraftServer.entityWorld == null) {
System.out.println("entityWorld is null");
//or do anything can to warn you
} else {
Ticket ticket = ForgeChunkManager.requestTicket(this,
this.minecraftServer.entityWorld,
ForgeChunkManager.Type.NORMAL);
}
Unless you can use a debugger to check the values.
But without the full code, it's impossible to know if there's any other error.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I have a method that return an array of files in a given directory that is giving me a null pointer exception when executed. I can't figure out why.
private ArrayList<File> getFiles(String path) {
File f = new File(path);
ArrayList<File> files = new ArrayList<>(Arrays.asList(f.listFiles()));
return files;
}
thanks for your help
This NullPointerException is thrown when the path specified while initializing the file is incorrect (doesn't exist).
In such cases it is always advisable to add some null checks(protective code) in your method.
eg:
if( f != null) { //get the list of files }
may be casue by f.listFiles() return one null array.you can watch the variables in debug model
This question already has answers here:
Getting hold of the outer class object from the inner class object
(7 answers)
Closed 6 years ago.
I'm trying to modify the behavior of JToolBar to allow it to dock to more than one JPanel. As part of this exercise, I need to override the method getDockingConstraint which I tried to do with an anonymous class using a definition very similar to the original.
The problem is that the original implementation references this several times which I thought would be fine, but I must be missing something because the IDE reports that this.dockingSensitivity is not visible to the anonymous class.
Is there a simple change here, or should I skip this approach and just create a full subclass of BasicToolBarUI? Or maybe there is a better approach entirely to modifying JToolBar's docking capability?
public MultiDockToolBar() {
setUI(new BasicToolBarUI(){
#Override
private String getDockingConstraint(Component var1, Point var2) {
if(var2 == null) {
return this.constraintBeforeFloating;
} else {
if(var1.contains(var2)) {
// Breaks here when using this.:
this.dockingSensitivity = this.toolBar.getOrientation() == 0?this.toolBar.getSize().height:this.toolBar.getSize().width;
if(var2.y < this.dockingSensitivity && !this.isBlocked(var1, "North")) {
return "North";
}
// Check East
// Check West
// Check South
}
return null;
}
}
});
}
dockingSensitivity is a private field inside BasicToolBarUI class. You will not be able to directly alter this. If you still want to edit and face the potential consequences, you can use Java Reflections library.