package faq.server;
import java.util.ArrayList;
import java.util.concurrent.ConcurrentMap;
import org.mapdb.DB;
import faq.shared.Category;
import faq.shared.CategoryComponent;
import faq.shared.CategoryIterator;
import faq.shared.Question;
/**Classe che gestisce la memorizzazione delle domande
*
* Gestisce la memorizzazione di una nuova domanda all'interno dello stesso database
* che memorizza le categorie.
* Permette di aggiungere o eliminare domande relative a una determinata categoria.
*
*
*/
public class QuestionHandlerImpl
{
// Database
private DB db;
// Lista radici alberi categorie
private ConcurrentMap<String, Category> categoryMap;
// oggetto per la gestione delle categorie
private CategoryHandlerImpl categoryHandler;
public void clear(){
categoryMap.clear();
categoryHandler.clear();
}
public QuestionHandlerImpl( DB db, CategoryHandlerImpl categoryHandler)
{
this.db = db;
this.categoryMap = this.db.getTreeMap("category");
this.categoryHandler = categoryHandler;
}
public void addQuestion(Category category, Question question)
{
Category root = this.categoryMap.get("root");
Category categoria = categoryHandler.getCategory(category.getName(), root);
categoria.add(question);
question.setCategory(categoria);
categoryMap.replace("root", categoryMap.get("root"), root);
this.db.commit();
}
public void removeQuestion(Category category, Question question)
{
Category root = this.categoryMap.get("root");
Category categoria = categoryHandler.getCategory(category.getName(), root);
categoria.remove(question);
categoryMap.replace("root", categoryMap.get("root"), root);
this.db.commit();
}
// Tutte le domande relative a una categoria
public ArrayList<Question> getQuestions(Category category)
{
Category root = this.categoryMap.get("root");
Category categoria = categoryHandler.getCategory(category.getName(), root);
ArrayList<Question> res = new ArrayList<Question>();
CategoryIterator sfogliaCategoria = (CategoryIterator) categoria.createIterator();
while(sfogliaCategoria.hasNext())
{
CategoryComponent componente = (CategoryComponent) sfogliaCategoria.next();
if( componente instanceof Question )
{
res.add( (Question)componente );
}
else
{
res.addAll(getQuestions((Category) componente));
}
}
res.trimToSize();
return res;
}
public ArrayList<Question> getAllQuestions()
{
Category root = this.categoryMap.get("root");
return getQuestions(root);
}
}
/**
*
*/
package faq.server;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.concurrent.ConcurrentMap;
import org.mapdb.DB;
import faq.shared.Answer;
import faq.shared.Category;
import faq.shared.Question;
/**Classe che gestisce la memorizzazione delle risposte
*
* Gestisce la memorizzazione di una nuova risposta all'interno dello stesso database
* che memorizza le domande e le categorie.
* Permette di aggiungere o eliminare risposte relative a una determinata domanda.
*
*
*/
public class AnswerHandlerImpl
{
// Database
private DB db;
// Lista radici alberi categorie
private ConcurrentMap<String, Category> categoryMap;
public void clear() {
categoryMap.clear();
}
public AnswerHandlerImpl( DB db)
{
this.db = db;
this.categoryMap = this.db.getTreeMap("category");
}
public void addAnswer(Question question, Answer answer)
{
Category root = this.categoryMap.get("root");
question.addAnswer(answer);
categoryMap.replace("root", categoryMap.get("root"), root);
this.db.commit();
}
public void removeAnswer(Question question, Answer answer)
{
Category root = this.categoryMap.get("root");
question.removeAnswer(answer);
categoryMap.replace("root", categoryMap.get("root"), root);
this.db.commit();
}
// Tutte le risposte relative a una domanda
public ArrayList<Answer> getAnswers(Question question)
{
Category root = this.categoryMap.get("root");
ArrayList<Answer> res = new ArrayList<Answer>();
Iterator sfogliaDomanda = question.createIterator();
while(sfogliaDomanda.hasNext())
{
res.add((Answer) sfogliaDomanda.next());
}
res.trimToSize();
return res;
}
}
/**
*
*/
package faq.server;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.concurrent.ConcurrentMap;
import org.mapdb.DB;
import faq.shared.Answer;
import faq.shared.Category;
import faq.shared.Judgment;
/**Classe che gestisce la memorizzazione dei giudizi
*
* Gestisce la memorizzazione di un nuovo giudizio all'interno dello stesso database
* che memorizza le risposte, le domande e le categorie.
* Permette di aggiungere giudizi relative a una determinata risposta.
*
*
*/
public class JudgmentHandlerImpl
{
// Database
private DB db;
// Lista radici alberi categorie
private ConcurrentMap<String, Category> categoryMap;
public void clear(){
categoryMap.clear();
}
public JudgmentHandlerImpl( DB db)
{
this.db = db;
this.categoryMap = this.db.getTreeMap("category");
}
public void addJudgment(Answer answer, Judgment judgment)
{
Category root = this.categoryMap.get("root");
answer.addJudgment(judgment);;
categoryMap.replace("root", categoryMap.get("root"), root);
this.db.commit();
}
// Tutte i giudizi relative a una risposta
public ArrayList<Judgment> getJudgments(Answer answer)
{
//Category root = this.categoryMap.get("root");
ArrayList<Judgment> res = new ArrayList<Judgment>();
Iterator sfogliaRisposta = answer.createIterator();
while(sfogliaRisposta.hasNext())
{
res.add((Judgment) sfogliaRisposta.next());
}
res.trimToSize();
return res;
}
}
/*
* Gestisce le operazioni sugli users
*/
public class LoginServiceImpl {
// Database
private DB db;
// Lista utenti
private ConcurrentMap<String, User> userMap;
public LoginServiceImpl( DB db){
this.db = db;
this.userMap = this.db.getTreeMap("user");
if( userMap.get("admin") == null){ // l'admin deve essere sempre presente nel db
addAdmin();
}
}
// Agigunge un utente al db, se gia' presente lancia eccezione
public User addUser( String username, String password, String email, String name, String surname, String sex, String birthDate, String birthPlace, String address ) throws DuplicatedUserNameException {
if( userMap.get( username ) != null ){
throw new DuplicatedUserNameException( username );
}
else{
User user = new NormalUser(username,password,email,name,surname,sex,birthDate,birthPlace,address);
this.userMap.put( username, user );
this.db.commit();
return user;
}
}
// Metodo che azzera la collezione utenti
public void clear(){
userMap.clear();
}
public void remove( String userName){
userMap.remove( userName );
}
// Aggiunge l'utente admin
public void addAdmin(){
User admin = new AdminUser("admin", "admin", "admin@admin.com", null, null, null, null, null, null);
userMap.put("admin", admin);
this.db.commit();
}
// Controlla username e password, se l'utente non e' presente o la password e' sbagliata lancia eccezioni
public User login(String userName, String password) throws WrongPasswordException, UserNotFoundException {
User user = this.userMap.get( userName );
if( user != null ){
if( !user.getPassword().equals(password) ){
throw new WrongPasswordException();
}
}
else{
throw new UserNotFoundException();
}
return user;
}
// Tutti gli utenti ( funzionalità admin )
public ArrayList<User> getAllUsers(){
ArrayList<User> res = new ArrayList<User>(userMap.values());
return res;
}
// Tutti gli utenti non giudici o admin ( funzionalità admin )
public ArrayList<User> getRegistered(){
ArrayList<User> users = new ArrayList<User>( userMap.values() );
ArrayList<User> res = new ArrayList<User>();
for( User u : users ){
if( u instanceof NormalUser ){
res.add( u );
}
}
res.trimToSize();
return res;
}
// Nomina un giudice sostituendo l'istanza di utente normale
// con quella di utente giudice, associandola allo stesso nome
public ArrayList<User> nominateJudge( String userName ){
NormalUser normalToJudge = (NormalUser) userMap.get(userName);
//judge.setRoleJudge();
User judge = new JudgeUser(normalToJudge);
userMap.replace(userName, normalToJudge, judge);
this.db.commit();
return getRegistered();
}
// Tutti gli utenti giudici ( funzionalità admin )
public ArrayList<User> getJudges(){
ArrayList<User> users = new ArrayList<User>( userMap.values() );
ArrayList<User> res = new ArrayList<User>();
for( User u : users){
if( u instanceof JudgeUser ){
res.add( u );
}
}
res.trimToSize();
return res;
}
}
package faq.shared;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import com.google.gwt.i18n.shared.DateTimeFormat;
/**Classe per la gestione delle domande
*
*/
public class Question extends CategoryComponent implements Serializable
{
/**
*
*/
private static final long serialVersionUID = 1L;
private String question;
private RegisteredUser user;
private Date date;
private ArrayList<Answer> answers = new ArrayList<>();
private Category category;
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
public Question(){}
public Question(String question, RegisteredUser user)
{
this.question=question;
this.user=user;
this.date= new Date();
}
public String getQuestion()
{
return question;
}
public User getUser()
{
return user;
}
public Date getDate()
{
return date;
}
public String getDay()
{
return DateTimeFormat.getFormat("yyyy-MM-dd").format(this.date);
//DateTimeFormat fmt = DateTimeFormat.getFormat("EEEE, MMMM dd, yyyy");
//return fmt.format(this.date);
}
public String getTime()
{
return DateTimeFormat.getFormat("hh:mm").format(this.date);
}
public void addAnswer(Answer answer)
{
answers.add(answer);
}
public void removeAnswer(Answer answer)
{
answers.remove(answer);
}
public Answer getAnswer(int i)
{
return answers.get(i);
}
public Iterator<Object> createIterator()
{
return new AnswerIterator<>(answers);
}
@Override
public int compareTo(Object o) {
return getDate().compareTo(((Question) o).getDate());
}
}
package faq.shared;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import com.google.gwt.i18n.shared.DateTimeFormat;
/**Classe che gestisce le risposte
*
*
*/
public class Answer implements Collection, Comparable<Object>, Serializable
{
/**
*
*/
private static final long serialVersionUID = 1L;
private String answer;
private RegisteredUser user;
private Date date;
private ArrayList<Judgment> judgments = new ArrayList<>();
public Answer(){}
public Answer(String answer, RegisteredUser user)
{
this.answer=answer;
this.user=user;
this.date= new Date();
}
public String getAnswer()
{
return answer;
}
public User getUser()
{
return user;
}
public Date getDate()
{
return date;
}
public String getDay()
{
return DateTimeFormat.getFormat("yyyy-MM-dd").format(this.date);
//DateTimeFormat fmt = DateTimeFormat.getFormat("EEEE, MMMM dd, yyyy");
//return fmt.format(this.date);
}
public String getTime()
{
return DateTimeFormat.getFormat("hh:mm").format(this.date);
}
public void addJudgment(Judgment judgment)
{
judgments.add(judgment);
}
public Judgment getJudgment(int i)
{
return judgments.get(i);
}
public double getEverageJudgment()
{
int total = 0;
for(Judgment j : judgments)
{
total = total + j.getJudgment();
}
if(judgments.size() == 0)
{
return 0;
}
else
{
return total/judgments.size();
}
}
@Override
public Iterator<Object> createIterator() {
return new JudgmentIterator<>(judgments);
}
@Override
public int compareTo(Object o) {
if (this.judgments.size() == 0)
{
return getDate().compareTo(((Answer) o).getDate());
}
else
{
if(this.getEverageJudgment() == ((Answer) o).getEverageJudgment())
{
return getDate().compareTo(((Answer) o).getDate());
}
else if(this.getEverageJudgment() > ((Answer) o).getEverageJudgment())
{
return 1;
}
else
{
return -1;
}
}
}
}
this is my code, how can i put category
of type Category
and question
of type Question
in my db? I cant.. help me please. thx u
I have to achieve a google application with gwt as "Yahoo Answer" and i manage the class with pattern composite, iterator, strategy and singleton for user.
Now i want to fill database, but i dont have string but use object.. how do i fill the database (mapdb) with category, question and answer?
I have to change type Category
in String
?
package faq.server;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import org.mapdb.DB;
import org.mapdb.DBMaker;
import faq.client.FAQService;
import faq.shared.Answer;
import faq.shared.Category;
import faq.shared.DuplicatedUserNameException;
import faq.shared.Judgment;
import faq.shared.Question;
import faq.shared.User;
import faq.shared.UserNotFoundException;
import faq.shared.WrongPasswordException;
public class FAQServiceImpl implements FAQService {
LoginServiceImpl loginService;
AnswerHandlerImpl answerHandler;
CategoryHandlerImpl categoryHandler;
JudgmentHandlerImpl judgmentHandler;
QuestionHandlerImpl questionHandler;
public FAQServiceImpl() {
DB db = DBMaker.newFileDB( new File( "FAQ-DB.txt" ) ).closeOnJvmShutdown().make();
loginService = new LoginServiceImpl( db );
answerHandler = new AnswerHandlerImpl( db);
categoryHandler = new CategoryHandlerImpl( db);
judgmentHandler = new JudgmentHandlerImpl( db );
questionHandler = new QuestionHandlerImpl( db, categoryHandler );
}
// DEBUG svuotare il db
public void restartDb() {
loginService.clear();
answerHandler.clear();
categoryHandler.clear();
judgmentHandler.clear();
questionHandler.clear();
loginService.addAdmin();
categoryHandler.addRoot();
}
// DEBUG popolare il db
public void populate() {
try {
addUser( "Sergio" , "m" , "sergio@studio.it" , null , null , null , null , null , null );
addUser( "Valentina" , "f" , "valentina@studio.it" , null , null , null , null , null , null );
addUser( "massimo" , "massimo" , "massimo@mail.it" , null , null , null , null , null , null );
} catch ( DuplicatedUserNameException e ) {
e.printStackTrace();
}
addCategory( "Scienze" );
addSubCategory( null , "Ecologia" );
addSubCategory( null , "Programmazione" );
addSubCategory( null , "JavaScript" );
addSubCategory( null , "Java" );
addSubCategory( null , "PHP" );
}
public User addUser( String username, String password, String email, String name, String surname, String sex,
String birthDate, String birthPlace, String address ) throws DuplicatedUserNameException {
return loginService.addUser( username , password , email , name , surname , sex , birthDate , birthPlace ,
address );
}
public User login( String userName, String password ) throws WrongPasswordException, UserNotFoundException {
return loginService.login( userName , password );
}
public ArrayList<User> getRegistered() {
return loginService.getRegistered();
}
public ArrayList<User> getAllUsers() {
return loginService.getAllUsers();
}
public ArrayList<User> nominateJudge( String userName ){
return loginService.nominateJudge( userName );
}
public ArrayList<User> getJudges() {
return loginService.getJudges();
}
public ArrayList<Question> addQuestion(Category category, Question question) {
questionHandler.addQuestion(category, question);
return getQuestions(category);
}
@Override
public ArrayList<Question> getQuestions(Category category) {
return getQuestions(category);
}
@Override
public ArrayList<Question> removeQuestion(Category category, Question question, User user) {
questionHandler.removeQuestion(category, question);
return getQuestions(category);
}
@Override
public Question addAnswer(Answer answer, Question question) {
answerHandler.addAnswer(question, answer);
return question;
}
public ArrayList<Answer> getAnswers(Question question) {
return answerHandler.getAnswers(question);
}
@Override
public Question removeAnswer(Question question, User user, Answer answer) {
answerHandler.removeAnswer(question, answer);
return question;
}
@Override
public Category renameCategory(Category category, String name) {
categoryHandler.renameCategory(category, name);
return getAllCategory();
}
@Override
public Category addCategory(String categoryName) {
categoryHandler.addCategory(categoryName);
return getAllCategory();
}
@Override
public Category addSubCategory(Category category, String name) {
categoryHandler.addSubCategory(category, name);
return getAllCategory();
}
@Override
public Question getQuestions(Category category, String question) {
return getQuestions(category, question);
}
@Override
public Answer addJudgment(Answer answer, Judgment judgment) {
judgmentHandler.addJudgment(answer, judgment);
return answer ;
}
@Override
public Category getAllCategory() {
return categoryHandler.getAllCategory();
}
@Override
public ArrayList<Question> getAllQuestions() {
return questionHandler.getAllQuestions();
}
@Override
public Category getCategory(String categoryName) {
return categoryHandler.getCategory(categoryName, null);
}
}
I have to fill database.. thx u
You need to debug it, but seems you have an error calling your addSubcategory method
addCategory( "Scienze" );
addSubCategory( null , "Ecologia" );
addSubCategory( null , "Programmazione" );
addSubCategory( null , "JavaScript" );
addSubCategory( null , "Java" );
addSubCategory( null , "PHP" );
Change that code by:
Category scienze = addCategory( "Scienze" );
addSubCategory( scienze , "Ecologia" );
addSubCategory( scienze , "Programmazione" );
addSubCategory( scienze , "JavaScript" );
addSubCategory( scienze , "Java" );
addSubCategory( scienze , "PHP" );