Skip to content

Commit

Permalink
Merge branch 'main' into test-#1606-ContextLoaderListener-not-initial…
Browse files Browse the repository at this point in the history
…ized-during-controller-tests
  • Loading branch information
nya-elimu authored Aug 24, 2022
2 parents db8dd40 + b00de2d commit 906e71c
Show file tree
Hide file tree
Showing 9 changed files with 127 additions and 28 deletions.
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
<groupId>ai.elimu</groupId>
<artifactId>webapp</artifactId>
<packaging>war</packaging>
<version>2.2.131-SNAPSHOT</version>
<version>2.2.133-SNAPSHOT</version>

<properties>
<java.version>11</java.version>
Expand Down
3 changes: 3 additions & 0 deletions src/main/java/ai/elimu/dao/WordDao.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,15 @@

import ai.elimu.model.content.Word;

import ai.elimu.model.v2.enums.content.WordType;
import org.springframework.dao.DataAccessException;

public interface WordDao extends GenericDao<Word> {

Word readByText(String text) throws DataAccessException;

Word readByTextAndType(String text, WordType wordType) throws DataAccessException;

List<Word> readAllOrdered() throws DataAccessException;

List<Word> readAllOrderedByUsage() throws DataAccessException;
Expand Down
26 changes: 26 additions & 0 deletions src/main/java/ai/elimu/dao/jpa/WordDaoJpa.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@

import java.util.List;
import javax.persistence.NoResultException;
import javax.persistence.Query;

import ai.elimu.model.v2.enums.content.WordType;
import org.springframework.dao.DataAccessException;

import ai.elimu.dao.WordDao;
Expand All @@ -24,6 +26,30 @@ public Word readByText(String text) throws DataAccessException {
}
}

@Override
public Word readByTextAndType(String text, WordType wordType) throws DataAccessException {
Query queryBuilder;
String query = "SELECT w " +
"FROM Word w " +
"WHERE w.text = :text ";
if (wordType == null) {
query += "AND w.wordType IS NULL";
queryBuilder = em.createQuery(query)
.setParameter("text", text);
} else {
query += "AND w.wordType = :wordType";
queryBuilder = em.createQuery(query)
.setParameter("text", text)
.setParameter("wordType", wordType);
}

try {
return (Word) queryBuilder.getSingleResult();
} catch (NoResultException e) {
return null;
}
}

@Override
public List<Word> readAllOrdered() throws DataAccessException {
return em.createQuery(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ public String postWordContribution(
logger.info("wordGson: " + wordGson);

// Check if the word is already existing.
Word existingWord = wordDao.readByText(wordGson.getText().toLowerCase());
Word existingWord = wordDao.readByTextAndType(wordGson.getText().toLowerCase(), wordGson.getWordType());
if (existingWord != null) {
jsonObject.put("result", "error");
jsonObject.put("errorMessage", "NonUnique");
Expand Down
8 changes: 4 additions & 4 deletions src/main/java/ai/elimu/util/db/DbContentImportHelper.java
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ public synchronized void performDatabaseContentImport(Environment environment, L
throw new IllegalArgumentException("Database content can only be imported from the TEST environment or from the PROD environment");
}

String contentDirectoryPath = "db" + File.separator + "content_" + environment + File.separator + language.toString().toLowerCase();
String contentDirectoryPath = "db/content_" + environment + "/" + language.toString().toLowerCase();
logger.info("contentDirectoryPath: \"" + contentDirectoryPath + "\"");
URL contentDirectoryURL = getClass().getClassLoader().getResource(contentDirectoryPath);
logger.info("contentDirectoryURL: " + contentDirectoryURL);
Expand Down Expand Up @@ -298,9 +298,9 @@ public synchronized void performDatabaseContentImport(Environment environment, L

// Extract and import Videos from CSV file in src/main/resources/
// TODO


String analyticsDirectoryPath = "db" + File.separator + "analytics_" + environment + File.separator + language.toString().toLowerCase();
String analyticsDirectoryPath = "db/analytics_" + environment + "/" + language.toString().toLowerCase();
logger.info("analyticsDirectoryPath: \"" + analyticsDirectoryPath + "\"");
URL analyticsDirectoryURL = getClass().getClassLoader().getResource(analyticsDirectoryPath);
logger.info("analyticsDirectoryURL: " + analyticsDirectoryURL);
Expand Down
56 changes: 36 additions & 20 deletions src/main/java/ai/elimu/web/SignOnControllerGitHub.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import java.util.Calendar;
import javax.servlet.http.HttpServletRequest;
import org.apache.logging.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONObject;
import ai.elimu.dao.ContributorDao;
import ai.elimu.model.contributor.Contributor;
Expand Down Expand Up @@ -41,6 +42,8 @@ public class SignOnControllerGitHub {

private static final String PROTECTED_RESOURCE_URL = "https://api.github.com/user";

private static final String PROTECTED_RESOURCE_URL_EMAILS = PROTECTED_RESOURCE_URL + "/emails";

private OAuth20Service oAuth20Service;

private final String secretState = "secret_" + new Random().nextInt(999_999);
Expand Down Expand Up @@ -95,46 +98,48 @@ public String handleCallback(HttpServletRequest request, Model model) {
String code = request.getParameter("code");
logger.debug("verifierParam: " + code);

String responseBody = null;

String responseBodyUser;
String responseBodyUserEmails;
logger.info("Trading the Authorization Code for an Access Token...");
try {
OAuth2AccessToken accessToken = oAuth20Service.getAccessToken(code);
logger.debug("accessToken: " + accessToken);
logger.info("Got the Access Token!");

// Access the protected resource
OAuthRequest oAuthRequest = new OAuthRequest(Verb.GET, PROTECTED_RESOURCE_URL);
oAuth20Service.signRequest(accessToken, oAuthRequest);
Response response = oAuth20Service.execute(oAuthRequest);
responseBody = response.getBody();
logger.info("response.getCode(): " + response.getCode());
logger.info("response.getBody(): " + responseBody);
responseBodyUser = executeGithubRequest(accessToken, PROTECTED_RESOURCE_URL);
responseBodyUserEmails = executeGithubRequest(accessToken, PROTECTED_RESOURCE_URL_EMAILS);
} catch (IOException | InterruptedException | ExecutionException ex) {
logger.error(ex);
return "redirect:/sign-on?error=" + ex.getMessage();
}

JSONObject jsonObject = new JSONObject(responseBody);
logger.info("jsonObject: " + jsonObject);
JSONObject jsonObjectUser = new JSONObject(responseBodyUser);
logger.info("jsonObjectUser: " + jsonObjectUser);
JSONArray jsonArrayUserEmails = new JSONArray(responseBodyUserEmails);
logger.info("jsonArrayUserEmails: " + jsonArrayUserEmails);
JSONObject jsonObjectUserEmail = jsonArrayUserEmails.getJSONObject(0);
logger.info("jsonObjectUserEmail: " + jsonObjectUserEmail);

Contributor contributor = new Contributor();
if (jsonObject.has("email") && !jsonObject.isNull("email")) {
contributor.setEmail(jsonObject.getString("email"));
if (jsonObjectUser.has("email") && !jsonObjectUser.isNull("email")) {
contributor.setEmail(jsonObjectUser.getString("email"));
} else if (jsonObjectUserEmail.has("email") && !jsonObjectUserEmail.isNull("email")) {
contributor.setEmail(jsonObjectUserEmail.getString("email"));
}
if (jsonObject.has("login")) {
contributor.setUsernameGitHub(jsonObject.getString("login"));
if (jsonObjectUser.has("login")) {
contributor.setUsernameGitHub(jsonObjectUser.getString("login"));
}
if (jsonObject.has("id")) {
Long idAsLong = jsonObject.getLong("id");
if (jsonObjectUser.has("id")) {
Long idAsLong = jsonObjectUser.getLong("id");
String id = String.valueOf(idAsLong);
contributor.setProviderIdGitHub(id);
}
if (jsonObject.has("avatar_url")) {
contributor.setImageUrl(jsonObject.getString("avatar_url"));
if (jsonObjectUser.has("avatar_url")) {
contributor.setImageUrl(jsonObjectUser.getString("avatar_url"));
}
if (jsonObject.has("name") && !jsonObject.isNull("name")) {
String name = jsonObject.getString("name");
if (jsonObjectUser.has("name") && !jsonObjectUser.isNull("name")) {
String name = jsonObjectUser.getString("name");
String[] nameParts = name.split(" ");
String firstName = nameParts[0];
logger.info("firstName: " + firstName);
Expand Down Expand Up @@ -197,4 +202,15 @@ public String handleCallback(HttpServletRequest request, Model model) {
return "redirect:/content";
}
}

private String executeGithubRequest(OAuth2AccessToken accessToken, String url) throws IOException, ExecutionException, InterruptedException {
logger.info("executeGithubRequest");
logger.info("url: " + url);
OAuthRequest oAuthRequest = new OAuthRequest(Verb.GET, url);
oAuth20Service.signRequest(accessToken, oAuthRequest);
Response response = oAuth20Service.execute(oAuthRequest);
logger.info("response.getCode(): " + response.getCode());
logger.info("response.getBody(): " + response.getBody());
return response.getBody();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ public String handleSubmit(
Model model) {
logger.info("handleSubmit");

Word existingWord = wordDao.readByText(word.getText());
Word existingWord = wordDao.readByTextAndType(word.getText(), word.getWordType());
if (existingWord != null) {
result.rejectValue("text", "NonUnique");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,7 @@ public String handleSubmit(
) {
logger.info("handleSubmit");

Word existingWord = wordDao.readByText(word.getText());
Word existingWord = wordDao.readByTextAndType(word.getText(), word.getWordType());
if ((existingWord != null) && !existingWord.getId().equals(word.getId())) {
result.rejectValue("text", "NonUnique");
}
Expand Down
54 changes: 54 additions & 0 deletions src/test/java/ai/elimu/dao/WordDaoTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package ai.elimu.dao;

import ai.elimu.model.content.Word;
import ai.elimu.model.v2.enums.content.WordType;
import junit.framework.TestCase;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={
"file:src/main/webapp/WEB-INF/spring/applicationContext.xml",
"file:src/main/webapp/WEB-INF/spring/applicationContext-jpa.xml"
})
public class WordDaoTest extends TestCase {

@Autowired
private WordDao wordDao;

private final String WORD_TEXT = "ExampleWord";

@Test
public void testStoreTheSameWordWithOtherType() {
wordDao.create(getWordWitTheSameText(WordType.ADJECTIVE));
wordDao.create(getWordWitTheSameText(WordType.ADVERB));
wordDao.create(getWordWitTheSameText(WordType.NOUN));
wordDao.create(getWordWitTheSameText(WordType.NUMBER));
wordDao.create(getWordWitTheSameText(WordType.PREPOSITION));
wordDao.create(getWordWitTheSameText(WordType.PRONOUN));
wordDao.create(getWordWitTheSameText(WordType.VERB));
wordDao.create(getWordWitTheSameText(null));

assertThat(wordDao.readByTextAndType(WORD_TEXT, WordType.ADJECTIVE).getWordType(), is(WordType.ADJECTIVE));
assertThat(wordDao.readByTextAndType(WORD_TEXT, WordType.ADVERB).getWordType(), is(WordType.ADVERB));
assertThat(wordDao.readByTextAndType(WORD_TEXT, WordType.NOUN).getWordType(), is(WordType.NOUN));
assertThat(wordDao.readByTextAndType(WORD_TEXT, WordType.NUMBER).getWordType(), is(WordType.NUMBER));
assertThat(wordDao.readByTextAndType(WORD_TEXT, WordType.PREPOSITION).getWordType(), is(WordType.PREPOSITION));
assertThat(wordDao.readByTextAndType(WORD_TEXT, WordType.PRONOUN).getWordType(), is(WordType.PRONOUN));
assertThat(wordDao.readByTextAndType(WORD_TEXT, WordType.VERB).getWordType(), is(WordType.VERB));
assertNull(wordDao.readByTextAndType(WORD_TEXT, null).getWordType());
}

private Word getWordWitTheSameText(WordType wordType) {
Word word = new Word();
word.setText(WORD_TEXT);
word.setWordType(wordType);
return word;
}
}

0 comments on commit 906e71c

Please sign in to comment.