forked from D-Net/dnet-hadoop
370 lines
15 KiB
Java
370 lines
15 KiB
Java
|
|
package eu.dnetlib.oa.graph.usagestats.export;
|
|
|
|
import java.io.*;
|
|
import java.net.URL;
|
|
import java.net.URLConnection;
|
|
import java.sql.PreparedStatement;
|
|
import java.sql.ResultSet;
|
|
import java.sql.Statement;
|
|
import java.text.SimpleDateFormat;
|
|
import java.util.Calendar;
|
|
import java.util.Date;
|
|
|
|
import org.apache.hadoop.conf.Configuration;
|
|
import org.apache.hadoop.fs.FSDataOutputStream;
|
|
import org.apache.hadoop.fs.FileSystem;
|
|
import org.apache.hadoop.fs.Path;
|
|
import org.json.simple.JSONArray;
|
|
import org.json.simple.JSONObject;
|
|
import org.json.simple.parser.JSONParser;
|
|
import org.slf4j.Logger;
|
|
import org.slf4j.LoggerFactory;
|
|
|
|
/**
|
|
* @author D. Pierrakos, S. Zoupanos
|
|
*/
|
|
public class IrusStats {
|
|
|
|
private String irusUKURL;
|
|
|
|
private static final Logger logger = LoggerFactory.getLogger(IrusStats.class);
|
|
|
|
public IrusStats(String irusUKURL) throws Exception {
|
|
this.irusUKURL = irusUKURL;
|
|
logger.info("Creating Irus Stats tables");
|
|
createTables();
|
|
logger.info("Created Irus Stats tables");
|
|
// The following may not be needed - It will be created when JSON tables are created
|
|
// createTmpTables();
|
|
}
|
|
|
|
private void createTables() throws Exception {
|
|
try {
|
|
|
|
logger.info("Creating sushilog");
|
|
Statement stmt = ConnectDB.getHiveConnection().createStatement();
|
|
String sqlCreateTableSushiLog = "CREATE TABLE IF NOT EXISTS " + ConnectDB.getUsageStatsDBSchema()
|
|
+ ".sushilog(source STRING, " +
|
|
"repository STRING, rid STRING, date STRING, metric_type STRING, count INT) clustered by (source, " +
|
|
"repository, rid, date, metric_type) into 100 buckets stored as orc tblproperties('transactional'='true')";
|
|
stmt.executeUpdate(sqlCreateTableSushiLog);
|
|
logger.info("Created sushilog");
|
|
|
|
// To see how to apply to the ignore duplicate rules and indexes
|
|
// stmt.executeUpdate(sqlCreateTableSushiLog);
|
|
// String sqlcreateRuleSushiLog = "CREATE OR REPLACE RULE ignore_duplicate_inserts AS "
|
|
// + " ON INSERT TO sushilog "
|
|
// + " WHERE (EXISTS ( SELECT sushilog.source, sushilog.repository,"
|
|
// + "sushilog.rid, sushilog.date "
|
|
// + "FROM sushilog "
|
|
// + "WHERE sushilog.source = new.source AND sushilog.repository = new.repository AND sushilog.rid = new.rid AND sushilog.date = new.date AND sushilog.metric_type = new.metric_type)) DO INSTEAD NOTHING;";
|
|
// stmt.executeUpdate(sqlcreateRuleSushiLog);
|
|
// String createSushiIndex = "create index if not exists sushilog_duplicates on sushilog(source, repository, rid, date, metric_type);";
|
|
// stmt.executeUpdate(createSushiIndex);
|
|
|
|
stmt.close();
|
|
ConnectDB.getHiveConnection().close();
|
|
logger.info("Sushi Tables Created");
|
|
} catch (Exception e) {
|
|
logger.error("Failed to create tables: " + e);
|
|
throw new Exception("Failed to create tables: " + e.toString(), e);
|
|
}
|
|
}
|
|
|
|
// // The following may not be needed - It will be created when JSON tables are created
|
|
// private void createTmpTables() throws Exception {
|
|
// try {
|
|
//
|
|
// Statement stmt = ConnectDB.getConnection().createStatement();
|
|
// String sqlCreateTableSushiLog = "CREATE TABLE IF NOT EXISTS sushilogtmp(source TEXT, repository TEXT, rid TEXT, date TEXT, metric_type TEXT, count INT, PRIMARY KEY(source, repository, rid, date, metric_type));";
|
|
// stmt.executeUpdate(sqlCreateTableSushiLog);
|
|
//
|
|
// // stmt.executeUpdate("CREATE TABLE IF NOT EXISTS public.sushilog AS TABLE sushilog;");
|
|
// // String sqlCopyPublicSushiLog = "INSERT INTO sushilog SELECT * FROM public.sushilog;";
|
|
// // stmt.executeUpdate(sqlCopyPublicSushiLog);
|
|
// String sqlcreateRuleSushiLog = "CREATE OR REPLACE RULE ignore_duplicate_inserts AS "
|
|
// + " ON INSERT TO sushilogtmp "
|
|
// + " WHERE (EXISTS ( SELECT sushilogtmp.source, sushilogtmp.repository,"
|
|
// + "sushilogtmp.rid, sushilogtmp.date "
|
|
// + "FROM sushilogtmp "
|
|
// + "WHERE sushilogtmp.source = new.source AND sushilogtmp.repository = new.repository AND sushilogtmp.rid = new.rid AND sushilogtmp.date = new.date AND sushilogtmp.metric_type = new.metric_type)) DO INSTEAD NOTHING;";
|
|
// stmt.executeUpdate(sqlcreateRuleSushiLog);
|
|
//
|
|
// stmt.close();
|
|
// ConnectDB.getConnection().close();
|
|
// log.info("Sushi Tmp Tables Created");
|
|
// } catch (Exception e) {
|
|
// log.error("Failed to create tables: " + e);
|
|
// throw new Exception("Failed to create tables: " + e.toString(), e);
|
|
// }
|
|
// }
|
|
|
|
public void processIrusStats() throws Exception {
|
|
Statement stmt = ConnectDB.getHiveConnection().createStatement();
|
|
ConnectDB.getHiveConnection().setAutoCommit(false);
|
|
|
|
logger.info("Adding JSON Serde jar");
|
|
stmt.executeUpdate("add jar /usr/share/cmf/common_jars/hive-hcatalog-core-1.1.0-cdh5.14.0.jar");
|
|
logger.info("Added JSON Serde jar");
|
|
|
|
logger.info("Dropping sushilogtmp_json table");
|
|
String drop_sushilogtmp_json = "DROP TABLE IF EXISTS " +
|
|
ConnectDB.getUsageStatsDBSchema() +
|
|
".sushilogtmp_json";
|
|
stmt.executeUpdate(drop_sushilogtmp_json);
|
|
logger.info("Dropped sushilogtmp_json table");
|
|
|
|
logger.info("Creating sushilogtmp_json table");
|
|
String create_sushilogtmp_json = "CREATE EXTERNAL TABLE IF NOT EXISTS " +
|
|
ConnectDB.getUsageStatsDBSchema() + ".sushilogtmp_json(\n" +
|
|
" `ItemIdentifier` ARRAY<\n" +
|
|
" struct<\n" +
|
|
" Type: STRING,\n" +
|
|
" Value: STRING\n" +
|
|
" >\n" +
|
|
" >,\n" +
|
|
" `ItemPerformance` ARRAY<\n" +
|
|
" struct<\n" +
|
|
" `Period`: struct<\n" +
|
|
" `Begin`: STRING,\n" +
|
|
" `End`: STRING\n" +
|
|
" >,\n" +
|
|
" `Instance`: struct<\n" +
|
|
" `Count`: STRING,\n" +
|
|
" `MetricType`: STRING\n" +
|
|
" >\n" +
|
|
" >\n" +
|
|
" >\n" +
|
|
")\n" +
|
|
"ROW FORMAT SERDE 'org.apache.hive.hcatalog.data.JsonSerDe'\n" +
|
|
"LOCATION '" + ExecuteWorkflow.irusUKReportPath + "'\n" +
|
|
"TBLPROPERTIES (\"transactional\"=\"false\")";
|
|
stmt.executeUpdate(create_sushilogtmp_json);
|
|
logger.info("Created sushilogtmp_json table");
|
|
|
|
logger.info("Dropping sushilogtmp table");
|
|
String drop_sushilogtmp = "DROP TABLE IF EXISTS " +
|
|
ConnectDB.getUsageStatsDBSchema() +
|
|
".sushilogtmp";
|
|
stmt.executeUpdate(drop_sushilogtmp);
|
|
logger.info("Dropped sushilogtmp table");
|
|
|
|
logger.info("Creating sushilogtmp table");
|
|
String create_sushilogtmp = "CREATE TABLE " + ConnectDB.getUsageStatsDBSchema()
|
|
+ ".sushilogtmp(source STRING, repository STRING, " +
|
|
"rid STRING, date STRING, metric_type STRING, count INT) clustered by (source) into 100 buckets stored as orc "
|
|
+
|
|
"tblproperties('transactional'='true')";
|
|
stmt.executeUpdate(create_sushilogtmp);
|
|
logger.info("Created sushilogtmp table");
|
|
|
|
logger.info("Inserting to sushilogtmp table");
|
|
String insert_sushilogtmp = "INSERT INTO " + ConnectDB.getUsageStatsDBSchema() + ".sushilogtmp " +
|
|
"SELECT 'IRUS-UK', 'opendoar____::', `ItemIdent`.`Value`, `ItemPerf`.`Period`.`Begin`, " +
|
|
"`ItemPerf`.`Instance`.`MetricType`, `ItemPerf`.`Instance`.`Count` " +
|
|
"FROM " + ConnectDB.getUsageStatsDBSchema() + ".sushilogtmp_json " +
|
|
"LATERAL VIEW posexplode(ItemIdentifier) ItemIdentifierTable AS seqi, ItemIdent " +
|
|
"LATERAL VIEW posexplode(ItemPerformance) ItemPerformanceTable AS seqp, ItemPerf " +
|
|
"WHERE `ItemIdent`.`Type`= 'OAI'";
|
|
stmt.executeUpdate(insert_sushilogtmp);
|
|
logger.info("Inserted to sushilogtmp table");
|
|
|
|
ConnectDB.getHiveConnection().close();
|
|
|
|
// // !!!!!!!!!!!!!!!!!!!!!
|
|
// // To do the following
|
|
// // !!!!!!!!!!!!!!!!!!!!!
|
|
//
|
|
// // String sql = "INSERT INTO sushi_result_downloads SELECT s.source, d.id AS repository, ro.id, s.date, s.count
|
|
// // FROM sushilog s, datasource_oids d, result_oids ro WHERE s.repository=d.orid AND s.oai=ro.orid AND
|
|
// // metric_type='ft_total'";
|
|
// // String sql = "SELECT s.source, d.id AS repository_id, ro.id as result_id, extract('year' from s.date::date)
|
|
// // ||'/'|| LPAD(CAST(extract('month' from s.date::date) AS VARCHAR), 2, '0') as date, s.count INTO
|
|
// // downloads_stats FROM sushilog s, datasource_oids d, result_oids ro WHERE s.repository=d.orid AND
|
|
// // s.oai=ro.orid AND metric_type='ft_total'";
|
|
// // String sql = "INSERT INTO downloads_stats SELECT s.source, d.id AS repository_id, ro.id as result_id,
|
|
// // extract('year' from s.date::date) ||'/'|| LPAD(CAST(extract('month' from s.date::date) AS VARCHAR), 2, '0')
|
|
// // as date, s.count FROM sushilog s, datasource_oids d, result_oids ro WHERE s.repository=d.orid AND
|
|
// // s.oai=ro.orid AND metric_type='ft_total';";
|
|
// String sql = "INSERT INTO downloads_stats SELECT s.source, d.id AS repository_id, ro.id as result_id, extract('year' from s.date::date) ||'/'|| LPAD(CAST(extract('month' from s.date::date) AS VARCHAR), 2, '0') as date, s.count, '0' FROM sushilogtmp s, public.datasource_oids d, public.result_oids ro WHERE s.repository=d.orid AND s.rid=ro.orid AND metric_type='ft_total' AND s.source='IRUS-UK';";
|
|
//
|
|
// stmt.executeUpdate(sql);
|
|
//
|
|
// sql = "Insert into sushilog select * from sushilogtmp;";
|
|
// stmt.executeUpdate(sql);
|
|
//
|
|
// ConnectDB.getConnection().close();
|
|
}
|
|
|
|
public void getIrusRRReport(String irusUKReportPath) throws Exception {
|
|
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("YYYY-MM");
|
|
String reportUrl = irusUKURL + "GetReport/?Report=RR1&Release=4&RequestorID=OpenAIRE&BeginDate=2016-01&EndDate="
|
|
+ simpleDateFormat.format(new Date())
|
|
+ "&RepositoryIdentifier=&ItemDataType=&NewJiscBand=&Granularity=Monthly&Callback=";
|
|
|
|
logger.info("(processIrusRRReport) Getting report: " + reportUrl);
|
|
|
|
String text = getJson(reportUrl, "", "");
|
|
|
|
// log.info("Report: " + text);
|
|
|
|
JSONParser parser = new JSONParser();
|
|
JSONObject jsonObject = (JSONObject) parser.parse(text);
|
|
jsonObject = (JSONObject) jsonObject.get("ReportResponse");
|
|
jsonObject = (JSONObject) jsonObject.get("Report");
|
|
jsonObject = (JSONObject) jsonObject.get("Report");
|
|
jsonObject = (JSONObject) jsonObject.get("Customer");
|
|
JSONArray jsonArray = (JSONArray) jsonObject.get("ReportItems");
|
|
int i = 0;
|
|
for (Object aJsonArray : jsonArray) {
|
|
JSONObject jsonObjectRow = (JSONObject) aJsonArray;
|
|
JSONArray itemIdentifier = (JSONArray) jsonObjectRow.get("ItemIdentifier");
|
|
for (Object identifier : itemIdentifier) {
|
|
JSONObject opendoar = (JSONObject) identifier;
|
|
if (opendoar.get("Type").toString().equals("OpenDOAR")) {
|
|
i++;
|
|
getIrusIRReport(opendoar.get("Value").toString(), irusUKReportPath);
|
|
break;
|
|
}
|
|
}
|
|
// break;
|
|
}
|
|
|
|
logger.info("(processIrusRRReport) Finished with report: " + reportUrl);
|
|
}
|
|
|
|
private void getIrusIRReport(String opendoar, String irusUKReportPath) throws Exception {
|
|
|
|
logger.info("(processIrusIRReport) Getting report(s) with opendoar: " + opendoar);
|
|
|
|
ConnectDB.getHiveConnection().setAutoCommit(false);
|
|
|
|
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("YYYY-MM");
|
|
|
|
Calendar start = Calendar.getInstance();
|
|
start.set(Calendar.YEAR, 2016);
|
|
start.set(Calendar.MONTH, Calendar.JANUARY);
|
|
// start.setTime(simpleDateFormat.parse("2016-01"));
|
|
|
|
Calendar end = Calendar.getInstance();
|
|
end.add(Calendar.DAY_OF_MONTH, -1);
|
|
|
|
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
|
|
PreparedStatement st = ConnectDB
|
|
.getHiveConnection()
|
|
.prepareStatement(
|
|
"SELECT max(date) FROM " + ConnectDB.getUsageStatsDBSchema() + ".sushilog WHERE repository=?");
|
|
st.setString(1, "opendoar____::" + opendoar);
|
|
ResultSet rs_date = st.executeQuery();
|
|
while (rs_date.next()) {
|
|
if (rs_date.getString(1) != null && !rs_date.getString(1).equals("null")
|
|
&& !rs_date.getString(1).equals("")) {
|
|
start.setTime(sdf.parse(rs_date.getString(1)));
|
|
}
|
|
}
|
|
rs_date.close();
|
|
PreparedStatement preparedStatement = ConnectDB
|
|
.getHiveConnection()
|
|
.prepareStatement(
|
|
"INSERT INTO sushilogtmp (source, repository, rid, date, metric_type, count) VALUES (?,?,?,?,?,?)");
|
|
int batch_size = 0;
|
|
|
|
while (start.before(end)) {
|
|
// log.info("date: " + simpleDateFormat.format(start.getTime()));
|
|
String reportUrl = this.irusUKURL + "GetReport/?Report=IR1&Release=4&RequestorID=OpenAIRE&BeginDate="
|
|
+ simpleDateFormat.format(start.getTime()) + "&EndDate=" + simpleDateFormat.format(start.getTime())
|
|
+ "&RepositoryIdentifier=opendoar%3A" + opendoar
|
|
+ "&ItemIdentifier=&ItemDataType=&hasDOI=&Granularity=Monthly&Callback=";
|
|
start.add(Calendar.MONTH, 1);
|
|
|
|
System.out.println("Downloading file: " + reportUrl);
|
|
String text = getJson(reportUrl, "", "");
|
|
if (text == null) {
|
|
continue;
|
|
}
|
|
|
|
FileSystem fs = FileSystem.get(new Configuration());
|
|
String filePath = irusUKReportPath + "/" + "IrusIRReport_" +
|
|
opendoar + "_" + simpleDateFormat.format(start.getTime()) + ".json";
|
|
System.out.println("Storing to file: " + filePath);
|
|
FSDataOutputStream fin = fs.create(new Path(filePath), true);
|
|
|
|
JSONParser parser = new JSONParser();
|
|
JSONObject jsonObject = (JSONObject) parser.parse(text);
|
|
jsonObject = (JSONObject) jsonObject.get("ReportResponse");
|
|
jsonObject = (JSONObject) jsonObject.get("Report");
|
|
jsonObject = (JSONObject) jsonObject.get("Report");
|
|
jsonObject = (JSONObject) jsonObject.get("Customer");
|
|
JSONArray jsonArray = (JSONArray) jsonObject.get("ReportItems");
|
|
if (jsonArray == null) {
|
|
continue;
|
|
}
|
|
String oai = "";
|
|
for (Object aJsonArray : jsonArray) {
|
|
JSONObject jsonObjectRow = (JSONObject) aJsonArray;
|
|
fin.write(jsonObjectRow.toJSONString().getBytes());
|
|
fin.writeChar('\n');
|
|
}
|
|
|
|
fin.close();
|
|
}
|
|
|
|
preparedStatement.executeBatch();
|
|
ConnectDB.getHiveConnection().close();
|
|
|
|
logger.info("(processIrusIRReport) Finished downloading report(s) with opendoar: " + opendoar);
|
|
}
|
|
|
|
private String getJson(String url) throws Exception {
|
|
try {
|
|
System.out.println("===> Connecting to: " + url);
|
|
URL website = new URL(url);
|
|
System.out.println("Connection url -----> " + url);
|
|
URLConnection connection = website.openConnection();
|
|
|
|
// connection.setRequestProperty ("Authorization", "Basic "+encoded);
|
|
StringBuilder response;
|
|
try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
|
|
response = new StringBuilder();
|
|
String inputLine;
|
|
while ((inputLine = in.readLine()) != null) {
|
|
response.append(inputLine);
|
|
// response.append("\n");
|
|
}
|
|
}
|
|
|
|
System.out.println("response ====> " + response.toString());
|
|
|
|
return response.toString();
|
|
} catch (Exception e) {
|
|
logger.error("Failed to get URL: " + e);
|
|
System.out.println("Failed to get URL: " + e);
|
|
throw new Exception("Failed to get URL: " + e.toString(), e);
|
|
}
|
|
}
|
|
|
|
private String getJson(String url, String username, String password) throws Exception {
|
|
// String cred=username+":"+password;
|
|
// String encoded = new sun.misc.BASE64Encoder().encode (cred.getBytes());
|
|
try {
|
|
URL website = new URL(url);
|
|
URLConnection connection = website.openConnection();
|
|
// connection.setRequestProperty ("Authorization", "Basic "+encoded);
|
|
StringBuilder response;
|
|
try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
|
|
response = new StringBuilder();
|
|
String inputLine;
|
|
while ((inputLine = in.readLine()) != null) {
|
|
response.append(inputLine);
|
|
response.append("\n");
|
|
}
|
|
}
|
|
return response.toString();
|
|
} catch (Exception e) {
|
|
logger.error("Failed to get URL", e);
|
|
return null;
|
|
}
|
|
}
|
|
}
|