package pt.estgp.estgweb.services.courses;
import jomm.dao.impl.AbstractDao;
import jomm.utils.StreamsUtils;
import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import pt.estgp.estgweb.domain.*;
import pt.estgp.estgweb.domain.dao.DaoFactory;
import pt.estgp.estgweb.filters.chains.ResourceAccessControlEnum;
import pt.estgp.estgweb.services.courses.coursereport.CourseReportUtils;
import pt.estgp.estgweb.services.courses.coursereport.documentmodel.*;
import pt.estgp.estgweb.services.courses.coursereport.documentmodel.courseunitreport.CourseUnitSection;
import pt.estgp.estgweb.services.courses.coursereport.documentmodel.learningresults.LearningGlobalAnalysisSection;
import pt.estgp.estgweb.services.courses.coursereport.documentmodel.learningresults.components.*;
import pt.estgp.estgweb.services.courses.coursereport.documentmodel.reportucsummary.CourseUnitDtpStat;
import pt.estgp.estgweb.services.courses.coursereport.documentmodel.reportucsummary.UnitDtpSemester;
import pt.estgp.estgweb.services.courses.coursereport.documentmodel.reportucsummary.UnitsDtpTable;
import pt.estgp.estgweb.services.courses.coursereport.documentmodel.surveys.SurveysResultsSection;
import pt.estgp.estgweb.services.data.RepositoryFile4JsonView;
import pt.estgp.estgweb.services.data.RepositoryService;
import pt.estgp.estgweb.services.questionarios.QuestionariosReportsService;
import pt.estgp.estgweb.services.questionarios.pedagogico.reportprocessors.utils.DataTable;
import pt.estgp.estgweb.utils.Globals;
import pt.estgp.estgweb.utils.documentBuilder.DocumentSection;
import pt.estgp.estgweb.utils.documentBuilder.QuestionariosDataTableComponent;
import pt.estgp.estgweb.web.controllers.utils.FileUploaded;
import pt.utl.ist.berserk.logic.serviceManager.IService;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;
/**
* Created by jorgemachado on 14/10/17.
*/
public class CourseReportServices
implements IService
{
private static final 1.5.0/docs/api/java/util/logging/Logger.html">Logger logger =
1.5.0/docs/api/java/util/logging/Logger.html">Logger.
getLogger(CourseReportServices.
class);
/****************************************************************************/
/* SERVICOS CORE DOS REPORTS
/****************************************************************************/
/**
*
* @param courseCode
* @param year
* @return
* @throws java.io.IOException
* @throws org.json.JSONException
*/
public CourseReportDocument createNewCourseReportDocument
(1.5.0/docs/api/java/lang/String.html">String courseCode,
1.5.0/docs/api/java/lang/String.html">String year
) throws 1.5.0/docs/api/java/io/IOException.html">IOException, JSONException
{
Course course = DaoFactory.
getCourseDaoImpl().
findCourseByCode(courseCode
);
CourseReportDocument reportCourseDocument =
new CourseReportDocument
();
reportCourseDocument.
init(course,year
);
//FIRST SERVICE TO CALL TO OBTAIN UNITS AND EVALUATIONS
//THIS IS THE BASE FOR THE REMAIN SERVICE CALLS
List
<DocumentSection
> courseUnitSections = updateCleanCourseUnitSections
(courseCode, year, reportCourseDocument
);
//A tabela de resultados globais não vai ser utilizada
//PARA CORRER ESTE SERVICO A PARTIR DA INTERFACE É PRECISO
//PERCEBER QUE DEPENDE DO SERVICO DE UPDATE DAS SECOES DAS COURSEUNITS
UnitsLearningResultsTable unitsLearningResultsTable = updateCleanLearningResultsFromCourseUnitsSections
(reportCourseDocument
);
//Atualiza no DOC a tabela de analise DTP
UnitsDtpTable unitsDtpTable = updateDtpStatsTable4Course
(reportCourseDocument, courseCode, year
);
//Atualiza as tabelas dos Quesitonários pedagogicos
SurveysResultsSection surveysResultsSection = updateSurveysDataTables
(courseCode, year, reportCourseDocument
);
return reportCourseDocument
;
}
public SurveysResultsSection updateSurveysDataTables
(1.5.0/docs/api/java/lang/String.html">String courseCode,
1.5.0/docs/api/java/lang/String.html">String year, CourseReportDocument reportCourseDocument
) throws 1.5.0/docs/api/java/io/IOException.html">IOException, JSONException
{
SurveysSection surveysSection =
(SurveysSection
) reportCourseDocument.
findDocumentSection(SurveysSection.
class);
SurveysResultsSection surveysResultsSection =
(SurveysResultsSection
) surveysSection.
findSection(SurveysResultsSection.
class);
QuestionariosDataTableComponent dataTableComponentS1 =
(QuestionariosDataTableComponent
) surveysResultsSection.
getComponents().
get(0
);
QuestionariosDataTableComponent dataTableComponentS2 =
(QuestionariosDataTableComponent
) surveysResultsSection.
getComponents().
get(1
);
QuestionariosReportsService questionariosReportsService =
new QuestionariosReportsService
();
1.5.0/docs/api/java/lang/String.html">String jsonDataTableS1 = questionariosReportsService.
loadReportUnidadesSalasJson(courseCode,year,
"S1");
1.5.0/docs/api/java/lang/String.html">String jsonDataTableS2 = questionariosReportsService.
loadReportUnidadesSalasJson(courseCode,year,
"S2");
DataTable dataTableS1 = DataTable.
fromJson(jsonDataTableS1
);
DataTable dataTableS2 = DataTable.
fromJson(jsonDataTableS2
);
dataTableComponentS1.
setDataTable(dataTableS1
);
dataTableComponentS2.
setDataTable(dataTableS2
);
return surveysResultsSection
;
}
/**
* Este serviço atualiza a tabela de resultados de aprendizagem com base nas courseunitssections
* @param reportCourseDocument
* @return UnitsLearningResultsTable
*/
public UnitsLearningResultsTable updateCleanLearningResultsFromCourseUnitsSections
(CourseReportDocument reportCourseDocument
)
{
CourseUnitsReportsSection unitReportsSection =
(CourseUnitsReportsSection
) reportCourseDocument.
findDocumentSection(CourseUnitsReportsSection.
class);
LearningResultsSection learningResultsSection =
(LearningResultsSection
) reportCourseDocument.
findDocumentSection(LearningResultsSection.
class);
UnitsLearningResultsTable learningResultsTable =
(UnitsLearningResultsTable
) learningResultsSection.
findDocComponent(UnitsLearningResultsTable.
class);
Map
<Integer,UnitsLearningResultYear
> anosPlano =
new HashMap
<Integer, UnitsLearningResultYear
>();
Map
<String,UnitsLearningResultSemester
> anoSemestre =
new HashMap
<String, UnitsLearningResultSemester
>();
for(DocumentSection subSection : unitReportsSection.
getSections())
{
CourseUnitSection unitSection =
(CourseUnitSection
) subSection
;
int anoPlano = unitSection.
getAnoPlano();
UnitsLearningResultYear anoFound = anosPlano.
get(anoPlano
);
if(anoFound ==
null)
{
anoFound =
new UnitsLearningResultYear
(anoPlano
);
anosPlano.
put(anoPlano,anoFound
);
learningResultsTable.
getYears().
add(anoFound
);
}
1.5.0/docs/api/java/lang/String.html">String semestreCode =
((CourseUnitSection
) subSection
).
getPeriod();
UnitsLearningResultSemester semestreFound = anoSemestre.
get(anoPlano +
"$" + semestreCode
);
if(semestreFound ==
null)
{
semestreFound =
new UnitsLearningResultSemester
(semestreCode
);
anoSemestre.
put(anoPlano +
"$" + semestreCode,semestreFound
);
anoFound.
getSemesters().
add(semestreFound
);
}
UnitsLearningResultUc uc =
new UnitsLearningResultUc
();
uc.
setPeriod(semestreCode
);
uc.
setName(unitSection.
getName());
uc.
setSigesCode(unitSection.
getSigesCode());
if(unitSection.
getCourseUnitEvaluation() !=
null)
{
uc.
setCumprimentoProgramaPercent(unitSection.
getCourseUnitEvaluation().
getCumprimentoProgramaPercent());
uc.
setAlunosInscritos(unitSection.
getCourseUnitEvaluation().
getNumAlunosInscritos());
uc.
setAprovados1013(unitSection.
getCourseUnitEvaluation().
getNumAlunosAprov1013());
uc.
setAprovados1416(unitSection.
getCourseUnitEvaluation().
getNumAlunosAprov1416());
uc.
setAprovados1720(unitSection.
getCourseUnitEvaluation().
getNumAlunosAprov1720());
uc.
setSemElementos(unitSection.
getCourseUnitEvaluation().
getNumAlunosSemElementosAvaliacao());
uc.
setAprovados(unitSection.
getCourseUnitEvaluation().
getNumAlunosAprovTotal());
uc.
setReprovados(unitSection.
getCourseUnitEvaluation().
getNumAlunosInscritos() - unitSection.
getCourseUnitEvaluation().
getNumAlunosAprovTotal() - unitSection.
getCourseUnitEvaluation().
getNumAlunosSemElementosAvaliacao());
if(uc.
getAlunosInscritos() > 0
)
{
uc.
setAprovadosPercent((float) (uc.
getAprovados() * 100.0 / uc.
getAlunosInscritos()));
uc.
setReprovadosPercent((float) (uc.
getReprovados() * 100.0 / uc.
getAlunosInscritos()));
uc.
setSemElementosPercent((float) (uc.
getSemElementos() * 100.0 / uc.
getAlunosInscritos()));
}
if(uc.
getAprovados() > 0
)
{
uc.
setAprovados1013Percent((float) (uc.
getAprovados1013() * 100.0 / uc.
getAprovados()));
uc.
setAprovados1416Percent((float) (uc.
getAprovados1416() * 100.0 / uc.
getAprovados()));
uc.
setAprovados1720Percent((float) (uc.
getAprovados1720() * 100.0 / uc.
getAprovados()));
}
}
semestreFound.
getUcs().
add(uc
);
}
1.5.0/docs/api/java/util/Collections.html">Collections.
sort(learningResultsTable.
getYears(),
new Comparator
<UnitsLearningResultYear
>() {
@
1.5.0/docs/api/java/lang/Override.html">Override
public int compare
(UnitsLearningResultYear o1, UnitsLearningResultYear o2
) {
return o1.
getAno() - o2.
getAno();
}
});
for(UnitsLearningResultYear learningYearLine: learningResultsTable.
getYears())
{
1.5.0/docs/api/java/util/Collections.html">Collections.
sort(learningYearLine.
getSemesters(),
new Comparator
<UnitsLearningResultSemester
>() {
@
1.5.0/docs/api/java/lang/Override.html">Override
public int compare
(UnitsLearningResultSemester o1, UnitsLearningResultSemester o2
) {
return o1.
getSemestre().
compareTo(o2.
getSemestre());
}
});
}
//UPDATE TOTAIS DE SEMESTRES E DE ANOS
float totalCumProgPercentGlobal =
0;
float totalInscritosGlobal =
0;
float totalReprovadosPercentGlobal =
0;
float totalAprovadosPercentGlobal =
0;
float totalSemElementosPercentGlobal =
0;
float totalAprovados1013PercentGlobal =
0;
float totalAprovados1416PercentGlobal =
0;
float totalAprovados1720PercentGlobal =
0;
for(UnitsLearningResultYear learningYearLine: learningResultsTable.
getYears())
{
float totalCumProgPercentAno =
0;
float totalInscritosAno =
0;
float totalReprovadosPercentAno =
0;
float totalAprovadosPercentAno =
0;
float totalSemElementosPercentAno =
0;
float totalAprovados1013PercentAno =
0;
float totalAprovados1416PercentAno =
0;
float totalAprovados1720PercentAno =
0;
for(UnitsLearningResultSemester semester: learningYearLine.
getSemesters())
{
float totalCumProgPercent =
0;
float totalInscritos =
0;
float totalReprovadosPercent =
0;
float totalAprovadosPercent =
0;
float totalSemElementosPercent =
0;
float totalAprovados1013Percent =
0;
float totalAprovados1416Percent =
0;
float totalAprovados1720Percent =
0;
for(UnitsLearningResultUc uc: semester.
getUcs())
{
totalCumProgPercent += uc.
getCumprimentoProgramaPercent();
totalInscritos += uc.
getAlunosInscritos();
totalAprovadosPercent += uc.
getAprovadosPercent();
totalReprovadosPercent += uc.
getReprovadosPercent();
totalSemElementosPercent += uc.
getSemElementosPercent();
totalAprovados1013Percent += uc.
getAprovados1013();
totalAprovados1416Percent += uc.
getAprovados1416();
totalAprovados1720Percent += uc.
getAprovados1720();
}
//media de inscritos
if(semester.
getUcs().
size() > 0
)
{
semester.
setCumprimentoProgramaPercent( totalCumProgPercent /
((float)semester.
getUcs().
size()));
semester.
setAlunosInscritos( totalInscritos /
((float)semester.
getUcs().
size()));
semester.
setAprovadosPercent( totalAprovadosPercent /
((float)semester.
getUcs().
size()));
semester.
setReprovadosPercent( totalReprovadosPercent /
((float)semester.
getUcs().
size()));
semester.
setSemElementosPercent( totalSemElementosPercent /
((float)semester.
getUcs().
size()));
semester.
setAprovados1013Percent( totalAprovados1013Percent /
((float)semester.
getUcs().
size()));
semester.
setAprovados1416Percent( totalAprovados1416Percent /
((float)semester.
getUcs().
size()));
semester.
setAprovados1720Percent( totalAprovados1720Percent /
((float)semester.
getUcs().
size()));
}
totalCumProgPercentAno += semester.
getCumprimentoProgramaPercent();
totalInscritosAno += semester.
getAlunosInscritos();
totalAprovadosPercentAno += semester.
getAprovadosPercent();
totalReprovadosPercentAno += semester.
getReprovadosPercent();
totalSemElementosPercentAno += semester.
getSemElementosPercent();
totalAprovados1013PercentAno += semester.
getAprovados1013();
totalAprovados1416PercentAno += semester.
getAprovados1416();
totalAprovados1720PercentAno += semester.
getAprovados1720();
}
//media de inscritos
if(learningYearLine.
getSemesters().
size() > 0
)
{
learningYearLine.
setCumprimentoProgramaPercent( totalCumProgPercentAno /
((float)learningYearLine.
getSemesters().
size()));
learningYearLine.
setAlunosInscritos( totalInscritosAno /
((float)learningYearLine.
getSemesters().
size()));
learningYearLine.
setAprovadosPercent( totalAprovadosPercentAno /
((float)learningYearLine.
getSemesters().
size()));
learningYearLine.
setReprovadosPercent( totalReprovadosPercentAno /
((float)learningYearLine.
getSemesters().
size()));
learningYearLine.
setSemElementosPercent( totalSemElementosPercentAno /
((float)learningYearLine.
getSemesters().
size()));
learningYearLine.
setAprovados1013Percent( totalAprovados1013PercentAno /
((float)learningYearLine.
getSemesters().
size()));
learningYearLine.
setAprovados1416Percent( totalAprovados1416PercentAno /
((float)learningYearLine.
getSemesters().
size()));
learningYearLine.
setAprovados1720Percent( totalAprovados1720PercentAno /
((float)learningYearLine.
getSemesters().
size()));
}
totalCumProgPercentGlobal += learningYearLine.
getCumprimentoProgramaPercent();
totalInscritosGlobal += learningYearLine.
getAlunosInscritos();
totalAprovadosPercentGlobal += learningYearLine.
getAprovadosPercent();
totalReprovadosPercentGlobal += learningYearLine.
getReprovadosPercent();
totalSemElementosPercentGlobal += learningYearLine.
getSemElementosPercent();
totalAprovados1013PercentGlobal += learningYearLine.
getAprovados1013();
totalAprovados1416PercentGlobal += learningYearLine.
getAprovados1416();
totalAprovados1720PercentGlobal += learningYearLine.
getAprovados1720();
}
if(learningResultsTable.
getYears().
size() > 0
)
{
learningResultsTable.
setCumprimentoProgramaPercent( totalCumProgPercentGlobal /
((float)learningResultsTable.
getYears().
size()));
learningResultsTable.
setAlunosInscritos( totalInscritosGlobal /
(learningResultsTable.
getYears().
size()));
learningResultsTable.
setAprovadosPercent( totalAprovadosPercentGlobal /
((float)learningResultsTable.
getYears().
size()));
learningResultsTable.
setReprovadosPercent( totalReprovadosPercentGlobal /
((float)learningResultsTable.
getYears().
size()));
learningResultsTable.
setSemElementosPercent( totalSemElementosPercentGlobal /
((float)learningResultsTable.
getYears().
size()));
learningResultsTable.
setAprovados1013Percent( totalAprovados1013PercentGlobal /
((float)learningResultsTable.
getYears().
size()));
learningResultsTable.
setAprovados1416Percent( totalAprovados1416PercentGlobal /
((float)learningResultsTable.
getYears().
size()));
learningResultsTable.
setAprovados1720Percent( totalAprovados1720PercentGlobal /
((float)learningResultsTable.
getYears().
size()));
}
return learningResultsTable
;
}
/**
* Gera uma tabela de estatisticas dos DTP recorrendo ao servico WS de
* load de tabelas DTP, caso o serviço nao devolva unidades são criadas novas
* com os valores a falso.
*
* @param courseCode
* @param year
* @return UnitsDtpTable
* @throws java.io.IOException
* @throws org.json.JSONException
*/
public UnitsDtpTable updateDtpStatsTable4Course
(CourseReportDocument reportCourseDocument,
1.5.0/docs/api/java/lang/String.html">String courseCode,
1.5.0/docs/api/java/lang/String.html">String year
) throws 1.5.0/docs/api/java/io/IOException.html">IOException, JSONException
{
ReportsUcSummarySection reportsUcSummarySection =
(ReportsUcSummarySection
) reportCourseDocument.
findDocumentSection(ReportsUcSummarySection.
class);
UnitsDtpTable unitsDtpTable =
(UnitsDtpTable
) reportsUcSummarySection.
findDocComponent(UnitsDtpTable.
class);
UnitDtpSemester semester1 =
new UnitDtpSemester
();
UnitDtpSemester semester2 =
new UnitDtpSemester
();
unitsDtpTable.
setSemester1(semester1
);
unitsDtpTable.
setSemester2(semester2
);
List
<CourseUnit
> units = DaoFactory.
getCourseUnitDaoImpl().
loadByCourseSiges(courseCode, year
);
CourseUnitDtpStat
[] statsLoaded
;
try
{
1.5.0/docs/api/java/lang/String.html">String json = loadCourseUnitDtpStats
(courseCode,year
);
JSONObject response =
new JSONObject
(json
);
JSONArray stats =
(JSONArray
) response.
get("dtpstats");
statsLoaded = CourseUnitDtpStat.
fromJson(stats
);
}
catch(1.5.0/docs/api/java/lang/Exception.html">Exception e
)
{
logger.
error(e,e
);
statsLoaded =
new CourseUnitDtpStat
[0
];
}
for(CourseUnit cu :units
)
{
CourseUnitDtpStat statFound = CourseReportUtils.
findCourseUnitDtpStat(statsLoaded,
(CourseUnitImpl
) cu
);
if(statFound ==
null)
{
statFound = CourseReportUtils.
createCourseUnitDtpStat(cu
);
}
if(((CourseUnitImpl
) cu
).
getSemestreAbsolutoS1S2().
equals("S1"))
semester1.
getCourseUnitDtpStats().
add(statFound
);
else
semester2.
getCourseUnitDtpStats().
add(statFound
);
}
return unitsDtpTable
;
}
/**
* Update course unit sections with reports, this method dows not change learning results table
* values from learning results stays in unit but does not change learning results Table
* @param courseCode
* @param year
* @param reportCourseDocument
* @throws org.json.JSONException
* @throws java.io.IOException
* @return a list of CourseUnitSection
*/
public List
<DocumentSection
> updateCleanCourseUnitSections
(1.5.0/docs/api/java/lang/String.html">String courseCode,
1.5.0/docs/api/java/lang/String.html">String year, CourseReportDocument reportCourseDocument
) throws JSONException,
1.5.0/docs/api/java/io/IOException.html">IOException {
List
<CourseUnit
> units = DaoFactory.
getCourseUnitDaoImpl().
loadByCourseSiges(courseCode, year
);
CourseUnitsReportsSection unitReportsSection =
(CourseUnitsReportsSection
) reportCourseDocument.
findDocumentSection(CourseUnitsReportsSection.
class);
CourseUnitSection
[] courseUnitSections =
null;
try{
1.5.0/docs/api/java/lang/String.html">String courseUnitSectionsJson = loadCourseEvaluationSections
(courseCode,year
);
JSONObject object =
new JSONObject
(courseUnitSectionsJson
);
JSONArray evaluations = object.
getJSONArray("evaluations");
courseUnitSections = CourseUnitSection.
fromJsonArray(evaluations.
toString());
}
catch(1.5.0/docs/api/java/lang/Exception.html">Exception e
)
{
logger.
error(e,e
);
courseUnitSections =
new CourseUnitSection
[0
];
}
ArrayList
<DocumentSection
> subSections =
new ArrayList
<DocumentSection
>();
unitReportsSection.
setSections(subSections
);
for(CourseUnit cu :units
)
{
CourseUnitSection sectionFound = CourseReportUtils.
findCourseUnitSection(courseUnitSections,
(CourseUnitImpl
) cu
);
if(sectionFound ==
null)
{
sectionFound = CourseReportUtils.
createCourseUnitEvaluationSection((CourseUnitImpl
) cu
);
}
if(sectionFound.
getCourseUnitEvaluation() ==
null)
{
CourseUnitEvaluationImpl courseUnitEvaluation = DomainObjectFactory.
createCourseUnitEvaluationImpl();
courseUnitEvaluation.
setAutoGeneratedCourseReport(true);
DaoFactory.
getCourseUnitEvaluationDaoImpl().
save(courseUnitEvaluation
);
cu.
setCourseUnitEvaluation(courseUnitEvaluation
);
sectionFound.
setCourseUnitEvaluation(courseUnitEvaluation
);
}
unitReportsSection.
getSections().
add(sectionFound
);
}
return subSections
;
}
/**
* Este servico gera um grafico com a taxa global de aproveitamento e grava-o no repositorio digital
* devolvendo o respectivo RepositoryFile4JsonView em json para poder ser anexado ao objecto imagem do
* widget do grafico
* @param reportDocumentJson
* @param session
* @return
* @throws java.io.IOException
*/
public 1.5.0/docs/api/java/lang/String.html">String generateGlobalLearningResultsChartImg
(1.5.0/docs/api/java/lang/String.html">String reportDocumentJson,UserSession session
) throws 1.5.0/docs/api/java/io/IOException.html">IOException {
CourseReportDocument reportDocument = CourseReportDocument.
fromJson(reportDocumentJson
);
LearningResultsSection learningResultsSection =
(LearningResultsSection
) reportDocument.
findDocumentSection(LearningResultsSection.
class);
LearningGlobalAnalysisSection learningGlobalAnalysisSection =
(LearningGlobalAnalysisSection
) learningResultsSection.
findSection(LearningGlobalAnalysisSection.
class);
GlobalLearningResultsChartImg chartImg =
(GlobalLearningResultsChartImg
) learningGlobalAnalysisSection.
findDocComponent(GlobalLearningResultsChartImg.
class);
UnitsLearningResultsTable table =
(UnitsLearningResultsTable
) learningResultsSection.
findDocComponent(UnitsLearningResultsTable.
class);
FileUploaded fileUploaded = chartImg.
generateChart2tmp(table,reportDocument
);
RepositoryService repositoryService =
new RepositoryService
();
boolean imageInitialized = chartImg.
getImage() !=
null
&&
chartImg.
getImage().
getIdentifier() !=
null;
RepositoryFile4JsonView view
;
if(imageInitialized
)
{
1.5.0/docs/api/java/lang/String.html">String identifier = chartImg.
getImage().
getIdentifier();
view = repositoryService.
replaceRepositoryFileFromFileUpload(identifier, fileUploaded, ResourceAccessControlEnum.
privateDomain, session
);
}
else
{
view = repositoryService.
storeRepositoryFileFromFileUpload(fileUploaded,ResourceAccessControlEnum.
privateDomain,session
);
}
chartImg.
setImage(view
);
//TODO FALTA GUARDAR O JSON NO CURSO
return view.
toJson();
}
/**
* Este servico gera um grafico com a taxa global de aproveitamento e grava-o no repositorio digital
* devolvendo o respectivo RepositoryFile4JsonView em json para poder ser anexado ao objecto imagem do
* widget do grafico
* @param reportDocumentJson
* @param session
* @return
* @throws java.io.IOException
*/
public 1.5.0/docs/api/java/lang/String.html">String generateGlobalLearningResultsChartYearImg
(1.5.0/docs/api/java/lang/String.html">String reportDocumentJson,UserSession session
) throws 1.5.0/docs/api/java/io/IOException.html">IOException {
CourseReportDocument reportDocument = CourseReportDocument.
fromJson(reportDocumentJson
);
LearningResultsSection learningResultsSection =
(LearningResultsSection
) reportDocument.
findDocumentSection(LearningResultsSection.
class);
LearningGlobalAnalysisSection learningGlobalAnalysisSection =
(LearningGlobalAnalysisSection
) learningResultsSection.
findSection(LearningGlobalAnalysisSection.
class);
GlobalLearningResultsChartYearImg chartImg =
(GlobalLearningResultsChartYearImg
) learningGlobalAnalysisSection.
findDocComponent(GlobalLearningResultsChartYearImg.
class);
UnitsLearningResultsTable table =
(UnitsLearningResultsTable
) learningResultsSection.
findDocComponent(UnitsLearningResultsTable.
class);
FileUploaded fileUploaded = chartImg.
generateChart2tmp(table,reportDocument
);
RepositoryService repositoryService =
new RepositoryService
();
boolean imageInitialized = chartImg.
getImage() !=
null
&&
chartImg.
getImage().
getIdentifier() !=
null;
RepositoryFile4JsonView view
;
if(imageInitialized
)
{
1.5.0/docs/api/java/lang/String.html">String identifier = chartImg.
getImage().
getIdentifier();
view = repositoryService.
replaceRepositoryFileFromFileUpload(identifier, fileUploaded, ResourceAccessControlEnum.
privateDomain, session
);
}
else
{
view = repositoryService.
storeRepositoryFileFromFileUpload(fileUploaded,ResourceAccessControlEnum.
privateDomain,session
);
}
chartImg.
setImage(view
);
//TODO FALTA GUARDAR O JSON NO CURSO
return view.
toJson();
}
/****************************************************************************/
/*
SERVICOS WS-API
*/
/****************************************************************************/
/**
* This service loads a list of course units given course code and year
* with dtp stats codes pre-filled
* @param courseCode
* @param year
* @return
* @throws org.json.JSONException
* @throws java.io.IOException
*/
public 1.5.0/docs/api/java/lang/String.html">String loadCourseUnitDtpStats
(1.5.0/docs/api/java/lang/String.html">String courseCode,
1.5.0/docs/api/java/lang/String.html">String year
) throws JSONException,
1.5.0/docs/api/java/io/IOException.html">IOException {
if(Globals.
SYSTEM_WSJSON_SERVICE_COURSE_UNITS_DTP_STATS.
indexOf("localhost")>=0
)
{
JSONArray array =
new JSONArray
();
List
<CourseUnit
> units = DaoFactory.
getCourseUnitDaoImpl().
loadByCourseSiges(courseCode, year
);
for(CourseUnit cu: units
)
{
CourseUnitDtpStat stat = CourseReportUtils.
createCourseUnitDtpStat(cu
);
//sections.add(courseUnitSection);
array.
put(stat.
toJsonObject());
}
JSONObject obj =
new JSONObject
();
obj.
put("dtpstats",array
);
return obj.
toString();
}
else
{
1.5.0/docs/api/java/lang/String.html">String serviceUrl = Globals.
SYSTEM_WSJSON_SERVICE_COURSE_UNITS_DTP_STATS +
"?code=" + courseCode +
"&year=" + year
;
1.5.0/docs/api/java/lang/String.html">String json =
"{ dtpstats : [] }";
try{
1.5.0/docs/api/java/net/URL.html">URL url =
new 1.5.0/docs/api/java/net/URL.html">URL(serviceUrl
);
1.5.0/docs/api/java/net/URLConnection.html">URLConnection conn = url.
openConnection();
5+0%2Fdocs%2Fapi+InputStream">InputStream is = conn.
getInputStream();
json = StreamsUtils.
readString(is
);
is.
close();
}catch(1.5.0/docs/api/java/lang/Throwable.html">Throwable e
)
{
logger.
error("Connecting " + serviceUrl,e
);
return json
;
}
JSONObject jsonObject =
new JSONObject
(json
);
if(jsonObject.
get("service").
equals("ok"))
return jsonObject.
get("response").
toString();
else
return json
;
}
}
/**
*
* Para um determinado curso e ano o serviço faz uma listagem de todas as suas unidades curriculares
* e lista a sua informação básica juntamente com o relatório de avaliação disponivel
* O serviço adiciona ainda o Ano de cada unidade por inspeção do Plano de Estudos
* caso a unidade não seja encontrada no Plano de estudos o ano irá ser preenchido com -1
*
* @param courseCode codigo Siges na base de dados
* @param year 201617, 201718
* @return String JSONObject with a JSON ARRAY of List<CourseUnitSection>
*/
public 1.5.0/docs/api/java/lang/String.html">String loadCourseEvaluationSections
(1.5.0/docs/api/java/lang/String.html">String courseCode,
1.5.0/docs/api/java/lang/String.html">String year
) throws JSONException,
1.5.0/docs/api/java/io/IOException.html">IOException {
if(Globals.
SYSTEM_WSJSON_SERVICE_COURSE_UNITS_EVALUATION_REPORT.
indexOf("localhost")>=0
)
{
JSONArray array =
new JSONArray
();
List
<CourseUnit
> units = DaoFactory.
getCourseUnitDaoImpl().
loadByCourseSiges(courseCode, year
);
for(CourseUnit cu: units
)
{
CourseUnitSection courseUnitSection = CourseReportUtils.
createCourseUnitEvaluationSection((CourseUnitImpl
) cu
);
if(courseUnitSection.
getAnoPlano() < 0)
{
logger.
info("Ano do Plano not available from courseUnitsEvaluation Service, will read from API loadPlanYearForCourseUnitCode");
try{
1.5.0/docs/api/java/lang/String.html">String json = loadPlanYearForCourseUnitCode
(courseCode,cu.
getCode(),cu.
getSemestre());
int ano =
new JSONObject
(json
).
getInt("year");
courseUnitSection.
setAnoPlano(ano
);
}catch(1.5.0/docs/api/java/lang/Throwable.html">Throwable e
)
{
logger.
error("Nao conseguiu obter o ano do plano da API: " + e.
toString(),e
);
}
}
array.
put(courseUnitSection.
toJsonObject());
}
JSONObject obj =
new JSONObject
();
obj.
put("evaluations",array
);
return obj.
toString();
}
else
{
1.5.0/docs/api/java/lang/String.html">String json =
"{ evaluations : [] }";
1.5.0/docs/api/java/lang/String.html">String serviceUrl = Globals.
SYSTEM_WSJSON_SERVICE_COURSE_UNITS_EVALUATION_REPORT +
"?code=" + courseCode +
"&year=" + year
;
try{
1.5.0/docs/api/java/net/URL.html">URL url =
new 1.5.0/docs/api/java/net/URL.html">URL(serviceUrl
);
1.5.0/docs/api/java/net/URLConnection.html">URLConnection conn = url.
openConnection();
5+0%2Fdocs%2Fapi+InputStream">InputStream is = conn.
getInputStream();
json = StreamsUtils.
readString(is
);
is.
close();
}catch(1.5.0/docs/api/java/lang/Throwable.html">Throwable e
)
{
logger.
error("Connecting " + serviceUrl,e
);
return json
;
}
JSONObject jsonObject =
new JSONObject
(json
);
if(jsonObject.
get("service").
equals("ok"))
return jsonObject.
get("response").
toString();
else
return json
;
}
}
/**
*
*
* @param courseCode codigo Siges na base de dados
* @param unitCode
* @return Json com o ano do plano exemplo: { year : 1 }
* ou -1 se não for encontrado
*/
public 1.5.0/docs/api/java/lang/String.html">String loadPlanYearForCourseUnitCode
(1.5.0/docs/api/java/lang/String.html">String courseCode,
1.5.0/docs/api/java/lang/String.html">String unitCode,
1.5.0/docs/api/java/lang/String.html">String period
) throws JSONException,
1.5.0/docs/api/java/io/IOException.html">IOException {
if(Globals.
SYSTEM_WSJSON_SERVICE_COURSE_UNIT_PLAN_YEAR.
indexOf("localhost")>=0
)
{
CourseImpl c = DaoFactory.
getCourseDaoImpl().
findCourseByCode(courseCode
);
int year = c.
getUnidadeAnoPlano(period,unitCode
);
return "{ year : " + year +
" }";
}
else
{
1.5.0/docs/api/java/lang/String.html">String json =
"{ year : -1 }";
1.5.0/docs/api/java/lang/String.html">String serviceUrl = Globals.
SYSTEM_WSJSON_SERVICE_COURSE_UNIT_PLAN_YEAR +
"?courseCode=" + courseCode +
"&unitCode=" + unitCode +
"&period=" + period
;
try{
1.5.0/docs/api/java/net/URL.html">URL url =
new 1.5.0/docs/api/java/net/URL.html">URL(serviceUrl
);
1.5.0/docs/api/java/net/URLConnection.html">URLConnection conn = url.
openConnection();
5+0%2Fdocs%2Fapi+InputStream">InputStream is = conn.
getInputStream();
json = StreamsUtils.
readString(is
);
is.
close();
}catch(1.5.0/docs/api/java/lang/Throwable.html">Throwable e
)
{
logger.
error("Connecting " + serviceUrl,e
);
return json
;
}
JSONObject jsonObject =
new JSONObject
(json
);
if(jsonObject.
get("service").
equals("ok"))
return jsonObject.
get("response").
toString();
else
return json
;
}
}
/** Req2
* Método para guardar um courseReportDocument na base de dados e volta a retornar o mesmo em Json
* @param reportDocumentJson ReportDocument em Json para save
* */
public 1.5.0/docs/api/java/lang/String.html">String saveCourseReportDocument
(1.5.0/docs/api/java/lang/String.html">String reportDocumentJson, UserSession session
) throws 1.5.0/docs/api/java/io/IOException.html">IOException {
//Recebe o Conteudo do reportDocument em Json e deserializa para um objecto do tipo CourseReportDocument
CourseReportDocument courseReportDocument = CourseReportDocument.
fromJson(reportDocumentJson
);
1.5.0/docs/api/java/lang/String.html">String courseCode = courseReportDocument.
getCourseCode();
1.5.0/docs/api/java/lang/String.html">String courseYear = courseReportDocument.
getYear();
//Vai à base de dados buscar o curso e as informações relativas a esse curso através do courseCode
//E transforma num object do tipo Course (Class que mapeia a tabela Course)
Course course = DaoFactory.
getCourseDaoImpl().
findCourseByCode(courseCode
);
List
<CourseYear
> courseYearList = DaoFactory.
getCourseYearDaoImpl().
findCourseYear(courseCode, courseYear
);
CourseYear cy
;
if (courseYearList.
isEmpty()){
cy = DomainObjectFactory.
createCourseYearImpl();
cy.
setCourse(course
);
course.
getCourseYears().
add(cy
);
cy.
setImportYear(courseYear
);
DaoFactory.
getCourseYearDaoImpl().
save(cy
);
}else{
//Vai buscar o primeiro index da lista
cy = courseYearList.
get(0
);
}
cy.
setCourseReportDocument(reportDocumentJson
);
return reportDocumentJson
;
}
/**
* Metodo que dá load ao json da tabela
*/
public 1.5.0/docs/api/java/lang/String.html">String loadCourseReportDocument
(1.5.0/docs/api/java/lang/String.html">String courseCode,
1.5.0/docs/api/java/lang/String.html">String year, UserSession session
) throws 1.5.0/docs/api/java/io/IOException.html">IOException {
List
<CourseYear
> courseYearList = DaoFactory.
getCourseYearDaoImpl().
findCourseYear(courseCode, year
);
CourseYear cy
;
//Cria a string para onde se vai fazer load e atribuir
1.5.0/docs/api/java/lang/String.html">String courseReportJson =
null;
if (courseYearList.
isEmpty()){
cy =
null;
}else{
cy = courseYearList.
get(0
);
}
if (cy
!=
null) {
courseReportJson = cy.
getCourseReportDocument();
}
if (courseReportJson ==
null) {
try {
CourseReportDocument courseReport = createNewCourseReportDocument
(courseCode, year
);
courseReportJson = courseReport.
toJson();
saveCourseReportDocument
(courseReportJson, session
);
} catch (1.5.0/docs/api/java/lang/Throwable.html">Throwable e
) {
1.5.0/docs/api/java/lang/System.html">System.
out.
println(e
);
e.
printStackTrace();
}
}
return courseReportJson
;
}
public static void main
(1.5.0/docs/api/java/lang/String.html">String[] args
) throws 1.5.0/docs/api/java/io/IOException.html">IOException, JSONException
{
AbstractDao.
getCurrentSession().
beginTransaction();
CourseReportDocument reportCourseDocument =
new CourseReportServices
().
createNewCourseReportDocument("44",
"201617");
1.5.0/docs/api/java/lang/System.html">System.
out.
println(reportCourseDocument.
toJson());
AbstractDao.
getCurrentSession().
getTransaction().
commit();
//System.setProperty("javax.net.ssl.trustStore", "/JORGE/COPIAS/.keystore");
//System.setProperty("javax.net.ssl.trustStorePassword", "changeit");
/*URL url = new URL("http://pae.ipportalegre.pt/wsjson/api/app/ws-course-pedagogic-results-list?code=44&year=201617&period=S1");
System.out.println(StreamsUtils.readString(url.openStream()));*/
}
/*
public String loadUnitsAndCreateLearningResultsTables4Course(String courseCode, String year) throws IOException, JSONException
{
}
*/
//TODO loadUnitsAndCreateLearningResultsTables4Course
//HIPOTESE DEVOLVER DOIS OBJECTOS
//SERVICO DE ARRANQUE
//DEVOLVE UM REPORT DOCUMENT E O CHAMADOR USA O QUE QUISER
//A GERACAO DE GRAFICOS FAZ-SE APENAS A PEDIDO
// SE ELE PEDIR PARA ATUALIZAR TUDO CARREGA-SE UNIDADES E TABELAS NU DOC NOVO
// E NO BROWSER SUBSTITUI-SE ESSES ELEMENTOS NOS ANTIGOS a seccao das unidades
// e as as tabelas
}