user177800
user177800

Reputation:

Testing that an Object exists in a Bucket?

I am trying to figure out what the most efficient way to test of the existence of an Object in a Bucket in Google Cloud Store.

This is what I am doing now:

try
{
    final GcsFileMetadata md = GCS_SERVICE.getMetadata(bm.getFilename());
    if (md == null)
    {
        // do what I need to do here!
    }
}
catch (IOException e)
{
    L.error(e.getMessage());
}

Because according to the documentation it returns null if the GcsFilename does not exist.

.

/**
   * @param filename The name of the file that you wish to read the metadata of.
   * @return The metadata associated with the file, or null if the file does not exist.
   * @throws IOException If for any reason the file can't be read.
   */
  GcsFileMetadata getMetadata(GcsFilename filename) throws IOException;

Using .list() on a Bucket and checking for .contains() sounds expensive but is explicit in its intention.

Personally I think testing for null to check if something exists is inelegant and not as direct as GCS_SERVICE.objectExists(fileName); but I guess I don't get to design the GCS Client API. I will just create a method to do this test in my API.

Is there a more efficient ( as in time ) or more self documenting way to do this test?

Upvotes: 3

Views: 2384

Answers (2)

Lex
Lex

Reputation: 184

They added the file.exists() method.

const fileExists = _=>{
    return file.exists().then((data)=>{ console.log(data[0]); });
}

fileExists();
//logs a boolean to the console;
//true if the file exists;
//false if the file doesn't exist.

Upvotes: 0

user177800
user177800

Reputation:

Solution

Here is the working solution I ended up with:

@Nonnull
protected Class<T> getEntityType() { (Class<T>) new TypeToken<T>(getClass()) {}.getRawType(); }

/**
 * purge ObjectMetadata records that don't have matching Objects in the GCS anymore.
 */
public void purgeOrphans()
{
    ofy().transact(new Work<VoidWork>()
    {
        @Override
        public VoidWork run()
        {
            try
            {
                for (final T bm : ofy().load().type(ObjectMetadataEntityService.this.getEntityType()).iterable())
                {
                    final GcsFileMetadata md = GCS_SERVICE.getMetadata(bm.getFilename());
                    if (md == null)
                    {
                        ofy().delete().entity(bm);
                    }
                }
            }
            catch (IOException e)
            {
                L.error(e.getMessage());
            }
            return null;
        }
    });
}

Upvotes: 2

Related Questions