|
| 1 | +package org.couchbase.quickstart.runners; |
| 2 | + |
| 3 | +import com.couchbase.client.core.error.*; |
| 4 | +import com.couchbase.client.java.Bucket; |
| 5 | +import com.couchbase.client.java.Cluster; |
| 6 | +import com.couchbase.client.java.json.JsonObject; |
| 7 | +import com.couchbase.client.java.manager.collection.CollectionManager; |
| 8 | +import com.couchbase.client.java.manager.collection.CollectionSpec; |
| 9 | +import com.couchbase.client.java.query.QueryResult; |
| 10 | +import org.couchbase.quickstart.configs.CollectionNames; |
| 11 | +import org.couchbase.quickstart.configs.DBProperties; |
| 12 | +import org.springframework.beans.factory.annotation.Autowired; |
| 13 | +import org.springframework.boot.CommandLineRunner; |
| 14 | +import org.springframework.stereotype.Component; |
| 15 | + |
| 16 | + |
| 17 | +/** |
| 18 | + * This class run after the application startup. It automatically setup all indexes needed |
| 19 | + */ |
| 20 | +@Component |
| 21 | +public class DBSetupRunner implements CommandLineRunner { |
| 22 | + |
| 23 | + @Autowired |
| 24 | + private Bucket bucket; |
| 25 | + @Autowired |
| 26 | + private Cluster cluster; |
| 27 | + @Autowired |
| 28 | + private DBProperties props; |
| 29 | + |
| 30 | + @Override |
| 31 | + public void run(String... args) { |
| 32 | + |
| 33 | + try { |
| 34 | + cluster.queryIndexes().createPrimaryIndex(props.getBucketName()); |
| 35 | + } catch (Exception e) { |
| 36 | + System.out.println("Primary index already exists on bucket "+props.getBucketName()); |
| 37 | + } |
| 38 | + |
| 39 | + CollectionManager collectionManager = bucket.collections(); |
| 40 | + try { |
| 41 | + CollectionSpec spec = CollectionSpec.create(CollectionNames.PROFILE, bucket.defaultScope().name()); |
| 42 | + collectionManager.createCollection(spec); |
| 43 | + } catch (CollectionExistsException e){ |
| 44 | + System.out.println(String.format("Collection <%s> already exists", CollectionNames.PROFILE)); |
| 45 | + } catch (Exception e) { |
| 46 | + System.out.println(String.format("Generic error <%s>",e.getMessage())); |
| 47 | + } |
| 48 | + |
| 49 | + try { |
| 50 | + final QueryResult result = cluster.query("CREATE PRIMARY INDEX default_profile_index ON "+props.getBucketName()+"._default."+ CollectionNames.PROFILE); |
| 51 | + for (JsonObject row : result.rowsAsObject()){ |
| 52 | + System.out.println(String.format("Index Creation Status %s",row.getObject("meta").getString("status"))); |
| 53 | + } |
| 54 | + } catch (IndexExistsException e){ |
| 55 | + System.out.println(String.format("Collection's primary index already exists")); |
| 56 | + } catch (Exception e){ |
| 57 | + System.out.println(String.format("General error <%s> when trying to create index ",e.getMessage())); |
| 58 | + } |
| 59 | + |
| 60 | + } |
| 61 | +} |
0 commit comments