Skip to content

Commit

Permalink
Fixed severity posed by sonarqube
Browse files Browse the repository at this point in the history
  • Loading branch information
PALASH2201 committed Oct 13, 2024
1 parent b82cdf7 commit 4837ce6
Show file tree
Hide file tree
Showing 5 changed files with 128 additions and 28 deletions.
4 changes: 4 additions & 0 deletions caching/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
MONGO_USER=
MONGO_PASSWORD=
MONGO_DB_NAME=
MONGO_DB_PORT=
3 changes: 3 additions & 0 deletions caching/.gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,4 @@
/target/

### ENV Files ###
.env
27 changes: 23 additions & 4 deletions caching/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -47,11 +47,30 @@
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>bson</artifactId>
<version>4.9.0</version>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-legacy</artifactId>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-sync</artifactId>
<version>4.9.0</version>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-core</artifactId>
<version>4.9.0</version>
</dependency>
<dependency>
<groupId>io.github.cdimascio</groupId>
<artifactId>java-dotenv</artifactId>
<version>5.2.2</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.30</version>
<scope>provided</scope>
</dependency>

</dependencies>
<!--
Due to the use of MongoDB in the test of this pattern, TRAVIS and/or MAVEN might fail if the DB connection is
Expand Down
78 changes: 62 additions & 16 deletions caching/src/main/java/com/iluwatar/caching/database/MongoDb.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
* This project is licensed under the MIT license.
* Module model-view-viewmodel is using ZK framework licensed under LGPL
* (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
Expand Down Expand Up @@ -31,12 +33,16 @@

import com.iluwatar.caching.UserAccount;
import com.iluwatar.caching.constants.CachingConstants;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoClientSettings;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.UpdateOptions;
import io.github.cdimascio.dotenv.Dotenv;
import java.util.Collections;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.bson.Document;

Expand All @@ -46,29 +52,69 @@
*/
@Slf4j
public class MongoDb implements DbManager {
private static final String DATABASE_NAME = "admin";
private static final String MONGO_USER = "root";
private static final String MONGO_PASSWORD = "rootpassword";

/**Initialize Dotenv object.*/
public static final Dotenv DOTENV = Dotenv.load();

/**Get database name from .env file.*/
private static final String DATABASE_NAME = DOTENV.get("MONGO_DB_NAME");

/**Get mongo username from .env file.*/
private static final String MONGO_USER = DOTENV.get("MONGO_USER");

/**Get mongo password from .env file.*/
private static final String MONGO_PASSWORD = DOTENV.get("MONGO_PASSWORD");

/**Get mongo db port number from .env file.*/
private static final String MONGO_DB_PORT = DOTENV.get("MONGO_DB_PORT");

/**Declaring MongoClient Object.*/
private MongoClient client;
private MongoDatabase db;

void setDb(MongoDatabase db) {
this.db = db;
}
/**Setting MongoDatabase object using Lombok annotation.*/
@Setter
private MongoDatabase db;

/**
* Connect to Db. Check th connection
* Connect to Db. Check th connection.
*/
@Override
public void connect() {
MongoCredential mongoCredential = MongoCredential.createCredential(MONGO_USER,
DATABASE_NAME,
MONGO_PASSWORD.toCharArray());
MongoClientOptions options = MongoClientOptions.builder().build();
client = new MongoClient(new ServerAddress(), mongoCredential, options);
// Create credentials
assert MONGO_USER != null;
assert DATABASE_NAME != null;
assert MONGO_PASSWORD != null;
assert MONGO_DB_PORT != null;
MongoCredential credential = MongoCredential.createCredential(
MONGO_USER,
DATABASE_NAME,
MONGO_PASSWORD.toCharArray()
);

// Set the cluster settings for server address
MongoClientSettings settings = MongoClientSettings.builder()
.applyToClusterSettings(builder ->
builder.hosts(
Collections.singletonList(
new ServerAddress(
"localhost",
Integer.parseInt(MONGO_DB_PORT)
)
)
))
.credential(credential) // Add credentials
.build();

// Create the mongoDBClient with settings
client = MongoClients.create(settings);

// Get the database
db = client.getDatabase(DATABASE_NAME);
}

/**
* Close the connection.
*/
@Override
public void disconnect() {
client.close();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.result.InsertOneResult;
import com.mongodb.client.result.UpdateResult;
import org.bson.Document;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
Expand All @@ -48,7 +50,7 @@ class MongoDbTest {

@Mock
MongoDatabase db;
private MongoDb mongoDb = new MongoDb();
private final MongoDb mongoDb = new MongoDb();

private UserAccount userAccount;

Expand All @@ -67,8 +69,8 @@ void connect() {
@Test
void readFromDb() {
Document document = new Document(USER_ID, ID)
.append(USER_NAME, NAME)
.append(ADD_INFO, ADDITIONAL_INFO);
.append(USER_NAME, NAME)
.append(ADD_INFO, ADDITIONAL_INFO);
MongoCollection<Document> mongoCollection = mock(MongoCollection.class);
when(db.getCollection(CachingConstants.USER_ACCOUNT)).thenReturn(mongoCollection);

Expand All @@ -77,27 +79,53 @@ void readFromDb() {

when(findIterable.first()).thenReturn(document);

assertEquals(mongoDb.readFromDb(ID),userAccount);
assertEquals(mongoDb.readFromDb(ID), userAccount);
}

@Test
void writeToDb() {
// Create a mock for the MongoCollection
MongoCollection<Document> mongoCollection = mock(MongoCollection.class);

// Stub the getCollection method to return the mocked mongoCollection
when(db.getCollection(CachingConstants.USER_ACCOUNT)).thenReturn(mongoCollection);
assertDoesNotThrow(()-> {mongoDb.writeToDb(userAccount);});

// Create a mock for the InsertOneResult (assuming you want to capture the return type)
InsertOneResult mockResult = mock(InsertOneResult.class);

// Mock the insertOne method to return the mocked result
when(mongoCollection.insertOne(any(Document.class))).thenReturn(mockResult);

// Assert that calling writeToDb does not throw an exception
assertDoesNotThrow(() -> {
mongoDb.writeToDb(userAccount);
});
}


@Test
void updateDb() {
MongoCollection<Document> mongoCollection = mock(MongoCollection.class);
when(db.getCollection(CachingConstants.USER_ACCOUNT)).thenReturn(mongoCollection);
assertDoesNotThrow(()-> {mongoDb.updateDb(userAccount);});

// If updateOne is not void, you should return a mock or a new instance of UpdateResult
UpdateResult mockResult = mock(UpdateResult.class);
when(mongoCollection.updateOne(any(Document.class), any(Document.class))).thenReturn(mockResult);

assertDoesNotThrow(() -> { mongoDb.updateDb(userAccount); });
}

@Test
void upsertDb() {
MongoCollection<Document> mongoCollection = mock(MongoCollection.class);
when(db.getCollection(CachingConstants.USER_ACCOUNT)).thenReturn(mongoCollection);
assertDoesNotThrow(()-> {mongoDb.upsertDb(userAccount);});

// Similar to updateDb
UpdateResult mockResult = mock(UpdateResult.class);
when(mongoCollection.updateOne(any(Document.class), any(Document.class))).thenReturn(mockResult);

assertDoesNotThrow(() -> { mongoDb.upsertDb(userAccount); });
}
}


}

0 comments on commit 4837ce6

Please sign in to comment.