Reorganized code to support multiple urls and to manage query via Java API instead of HTTP API

git-svn-id: https://svn.d4science.research-infrastructures.eu/gcube/trunk/information-system/resource-registry@133203 82a268e6-3cf1-43bd-a215-b396298e98cf
This commit is contained in:
Luca Frosini 2016-10-14 13:35:20 +00:00
parent 6662e7b6ef
commit c1e4e869bf
14 changed files with 233 additions and 123 deletions

View File

@ -20,42 +20,46 @@ import com.tinkerpop.blueprints.impls.orient.OrientGraphFactory;
*/ */
public abstract class SecurityContextMapper { public abstract class SecurityContextMapper {
private static Logger logger = LoggerFactory.getLogger(SecurityContextMapper.class); private static Logger logger = LoggerFactory
.getLogger(SecurityContextMapper.class);
public static final String MANAGEMENT_SECURITY_CONTEXT = "ManagementSecurityContext"; public static final String MANAGEMENT_SECURITY_CONTEXT = "ManagementSecurityContext";
private static final Map<PermissionMode, Map<String, OrientGraphFactory>> securityContextFactories; private static final Map<PermissionMode, Map<String, OrientGraphFactory>> securityContextFactories;
static { static {
try { try {
boolean created = DatabaseIntializator.initGraphDB(); boolean created = DatabaseIntializator.initGraphDB();
logger.trace("Creating factory for {} connecting as {}", logger.trace("Creating factory for {} connecting as {}",
DatabaseEnvironment.getDBURI(), DatabaseEnvironment.DB_URI,
DatabaseEnvironment.DEFAULT_ADMIN_USERNAME); DatabaseEnvironment.DEFAULT_ADMIN_USERNAME);
securityContextFactories = new HashMap<>(); securityContextFactories = new HashMap<>();
OrientGraphFactory factory = new OrientGraphFactory( OrientGraphFactory factory = new OrientGraphFactory(
DatabaseEnvironment.getDBURI(), DatabaseEnvironment.DB_URI,
DatabaseEnvironment.DEFAULT_ADMIN_USERNAME, DatabaseEnvironment.DEFAULT_ADMIN_USERNAME,
DatabaseEnvironment.CHANGED_ADMIN_PASSWORD) DatabaseEnvironment.CHANGED_ADMIN_PASSWORD)
.setupPool(1, 10); .setupPool(1, 10);
for(PermissionMode p : PermissionMode.values()){ for (PermissionMode p : PermissionMode.values()) {
Map<String, OrientGraphFactory> map = new HashMap<>(); Map<String, OrientGraphFactory> map = new HashMap<>();
map.put(null, factory); map.put(null, factory);
securityContextFactories.put(p, map); securityContextFactories.put(p, map);
map.put(null, factory); map.put(null, factory);
} }
if(created){ if (created) {
OrientGraph orientGraph = factory.getTx(); OrientGraph orientGraph = factory.getTx();
SecurityContext.createSecurityContext(orientGraph, MANAGEMENT_SECURITY_CONTEXT, true); SecurityContext.createSecurityContext(orientGraph,
MANAGEMENT_SECURITY_CONTEXT, true);
getSecurityContextFactory(MANAGEMENT_SECURITY_CONTEXT, PermissionMode.READER);
getSecurityContextFactory(MANAGEMENT_SECURITY_CONTEXT, PermissionMode.WRITER); getSecurityContextFactory(MANAGEMENT_SECURITY_CONTEXT,
PermissionMode.READER);
getSecurityContextFactory(MANAGEMENT_SECURITY_CONTEXT,
PermissionMode.WRITER);
DatabaseIntializator.createEntitiesAndRelations(); DatabaseIntializator.createEntitiesAndRelations();
} }
@ -99,29 +103,31 @@ public abstract class SecurityContextMapper {
* use null for no context (used for admin operations) * use null for no context (used for admin operations)
* @return * @return
*/ */
public static OrientGraphFactory getSecurityContextFactory(String contextID, PermissionMode permissionMode) { public static OrientGraphFactory getSecurityContextFactory(
String contextID, PermissionMode permissionMode) {
OrientGraphFactory factory = null; OrientGraphFactory factory = null;
Map<String, OrientGraphFactory> permissionSecurityContextFactories = Map<String, OrientGraphFactory> permissionSecurityContextFactories = securityContextFactories
securityContextFactories.get(permissionMode); .get(permissionMode);
factory = permissionSecurityContextFactories.get(contextID); factory = permissionSecurityContextFactories.get(contextID);
if (factory == null) { if (factory == null) {
String username = getSecurityRoleOrUserName(permissionMode, String username = getSecurityRoleOrUserName(permissionMode,
SecurityType.USER, contextID); SecurityType.USER, contextID);
String password = DatabaseEnvironment.DEFAULT_PASSWORDS.get(permissionMode); String password = DatabaseEnvironment.DEFAULT_PASSWORDS
.get(permissionMode);
factory = new OrientGraphFactory(DatabaseEnvironment.getDBURI(),
username, password).setupPool(1, 10); factory = new OrientGraphFactory(DatabaseEnvironment.DB_URI,
username, password).setupPool(1, 10);
permissionSecurityContextFactories.put(contextID, factory); permissionSecurityContextFactories.put(contextID, factory);
} }
return factory; return factory;
} }
public static String getSecurityRoleOrUserName( public static String getSecurityRoleOrUserName(
PermissionMode permissionMode, SecurityType securityType, PermissionMode permissionMode, SecurityType securityType,
String contextID) { String contextID) {

View File

@ -62,28 +62,17 @@ public class DatabaseEnvironment {
public static final Map<PermissionMode, String> DEFAULT_PASSWORDS; public static final Map<PermissionMode, String> DEFAULT_PASSWORDS;
protected static int currentHost; protected static final String HOSTS;
protected static final String[] HOST_ARRAY;
public static final String DB_URI;
public static final String[] HOSTS;
public static final String[] HTTP_URL_STRINGS; public static final String[] HTTP_URL_STRINGS;
public static final String[] URI_DBS;
public static String getDBURI(){
return URI_DBS[currentHost];
}
public static String getHTTPURL(){
return HTTP_URL_STRINGS[currentHost];
}
static { static {
Properties properties = new Properties(); Properties properties = new Properties();
InputStream input = null; InputStream input = null;
currentHost = 0;
try { try {
input = DatabaseEnvironment.class.getClassLoader().getResourceAsStream(PROPERTY_FILENAME); input = DatabaseEnvironment.class.getClassLoader().getResourceAsStream(PROPERTY_FILENAME);
@ -91,8 +80,7 @@ public class DatabaseEnvironment {
// load a properties file // load a properties file
properties.load(input); properties.load(input);
String hostsString = properties.getProperty(HOST_VARNAME); HOSTS = properties.getProperty(HOST_VARNAME);
HOSTS = hostsString.split(",");
REMOTE_PROTOCOL = properties.getProperty(REMOTE_PROTOCOL_VARNAME); REMOTE_PROTOCOL = properties.getProperty(REMOTE_PROTOCOL_VARNAME);
@ -100,7 +88,7 @@ public class DatabaseEnvironment {
HTTP_PORT = properties.getProperty(HTTP_PORT_VARNAME); HTTP_PORT = properties.getProperty(HTTP_PORT_VARNAME);
DB = properties.getProperty(DB_VARNAME); DB = properties.getProperty(DB_VARNAME);
DB_URI = REMOTE_PROTOCOL + HOSTS + "/" + DB;
USERNAME = properties.getProperty(USERNAME_VARNAME); USERNAME = properties.getProperty(USERNAME_VARNAME);
PASSWORD = properties.getProperty(PASSWORD_VARNAME); PASSWORD = properties.getProperty(PASSWORD_VARNAME);
@ -121,13 +109,11 @@ public class DatabaseEnvironment {
DEFAULT_PASSWORDS.put(PermissionMode.READER, DEFAULT_CREATED_READER_USER_PASSWORD); DEFAULT_PASSWORDS.put(PermissionMode.READER, DEFAULT_CREATED_READER_USER_PASSWORD);
HOST_ARRAY = HOSTS.split(";");
HTTP_URL_STRINGS = new String[HOST_ARRAY.length];
HTTP_URL_STRINGS = new String[HOSTS.length]; for(int i=0; i<HOST_ARRAY.length; i++){
URI_DBS = new String[HOSTS.length]; HTTP_URL_STRINGS[i] = HTTP_PROTOCOL + HOST_ARRAY[i] + HTTP_PORT;
for(int i=0; i<HOSTS.length; i++){
HTTP_URL_STRINGS[i] = HTTP_PROTOCOL + HOSTS[i] + HTTP_PORT;
URI_DBS[i] = REMOTE_PROTOCOL + HOSTS[i] + "/" + DB;
} }
} catch(Exception e){ } catch(Exception e){

View File

@ -11,6 +11,7 @@ import org.gcube.informationsystem.resourceregistry.context.SecurityContextMappe
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import com.orientechnologies.common.log.OLogManager;
import com.orientechnologies.orient.client.remote.OServerAdmin; import com.orientechnologies.orient.client.remote.OServerAdmin;
import com.orientechnologies.orient.core.metadata.OMetadata; import com.orientechnologies.orient.core.metadata.OMetadata;
import com.orientechnologies.orient.core.metadata.schema.OClass; import com.orientechnologies.orient.core.metadata.schema.OClass;
@ -24,51 +25,68 @@ import com.tinkerpop.blueprints.impls.orient.OrientVertexType;
/** /**
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
* *
*/ */
public class DatabaseIntializator { public class DatabaseIntializator {
private static Logger logger = LoggerFactory.getLogger(DatabaseIntializator.class); private static Logger logger = LoggerFactory
.getLogger(DatabaseIntializator.class);
private static final String DATABASE_TYPE = "graph"; private static final String DATABASE_TYPE = "graph";
private static final String STORAGE_MODE = "plocal"; private static final String STORAGE_MODE = "plocal";
private static final String O_RESTRICTED_CLASS = "ORestricted"; private static final String O_RESTRICTED_CLASS = "ORestricted";
public static boolean initGraphDB() throws Exception { public static boolean initGraphDB() throws Exception {
logger.trace("Connecting to {} as {} to create new DB", DatabaseEnvironment.getDBURI(), DatabaseEnvironment.USERNAME); OLogManager.instance().setWarnEnabled(false);
OServerAdmin serverAdmin = new OServerAdmin(DatabaseEnvironment.getDBURI()).connect(DatabaseEnvironment.USERNAME, OLogManager.instance().setErrorEnabled(false);
DatabaseEnvironment.PASSWORD); OLogManager.instance().setInfoEnabled(false);
OLogManager.instance().setDebugEnabled(false);
logger.trace("Connecting to {} as {} to create new DB",
DatabaseEnvironment.DB_URI, DatabaseEnvironment.USERNAME);
OServerAdmin serverAdmin = new OServerAdmin(DatabaseEnvironment.DB_URI)
.connect(DatabaseEnvironment.USERNAME,
DatabaseEnvironment.PASSWORD);
if (!serverAdmin.existsDatabase()) { if (!serverAdmin.existsDatabase()) {
logger.trace("Creating Database {}", DatabaseEnvironment.getDBURI()); logger.trace("Creating Database {}", DatabaseEnvironment.DB_URI);
serverAdmin.createDatabase(DatabaseEnvironment.DB, DATABASE_TYPE, STORAGE_MODE); serverAdmin.createDatabase(DatabaseEnvironment.DB, DATABASE_TYPE,
STORAGE_MODE);
logger.trace( logger.trace(
"Connecting to newly created database {} as {} with default password", "Connecting to newly created database {} as {} with default password",
DatabaseEnvironment.getDBURI(), DatabaseEnvironment.DEFAULT_ADMIN_USERNAME); DatabaseEnvironment.DB_URI,
DatabaseEnvironment.DEFAULT_ADMIN_USERNAME);
OrientGraphFactory factory = new OrientGraphFactory(DatabaseEnvironment.getDBURI(),
DatabaseEnvironment.DEFAULT_ADMIN_USERNAME, DatabaseEnvironment.DEFAULT_ADMIN_PASSWORD).setupPool( OrientGraphFactory factory = new OrientGraphFactory(
1, 10); DatabaseEnvironment.DB_URI,
DatabaseEnvironment.DEFAULT_ADMIN_USERNAME,
DatabaseEnvironment.DEFAULT_ADMIN_PASSWORD)
.setupPool(1, 10);
OrientGraphNoTx orientGraphNoTx = factory.getNoTx(); OrientGraphNoTx orientGraphNoTx = factory.getNoTx();
OMetadata oMetadata = orientGraphNoTx.getRawGraph().getMetadata(); OMetadata oMetadata = orientGraphNoTx.getRawGraph().getMetadata();
OSecurity oSecurity = oMetadata.getSecurity(); OSecurity oSecurity = oMetadata.getSecurity();
logger.trace("Changing {} password", DatabaseEnvironment.DEFAULT_ADMIN_USERNAME); logger.trace("Changing {} password",
OUser admin = oSecurity.getUser(DatabaseEnvironment.DEFAULT_ADMIN_USERNAME); DatabaseEnvironment.DEFAULT_ADMIN_USERNAME);
OUser admin = oSecurity
.getUser(DatabaseEnvironment.DEFAULT_ADMIN_USERNAME);
admin.setPassword(DatabaseEnvironment.CHANGED_ADMIN_PASSWORD); admin.setPassword(DatabaseEnvironment.CHANGED_ADMIN_PASSWORD);
admin.save(); admin.save();
for (PermissionMode permissionMode : DatabaseEnvironment.DEFAULT_PASSWORDS.keySet()) { for (PermissionMode permissionMode : DatabaseEnvironment.DEFAULT_PASSWORDS
.keySet()) {
OUser oUser = oSecurity.getUser(permissionMode.toString()); OUser oUser = oSecurity.getUser(permissionMode.toString());
oUser.setPassword(DatabaseEnvironment.DEFAULT_PASSWORDS.get(permissionMode)); oUser.setPassword(DatabaseEnvironment.DEFAULT_PASSWORDS
.get(permissionMode));
oUser.save(); oUser.save();
logger.trace("Updating password for user {}", permissionMode.toString()); logger.trace("Updating password for user {}",
permissionMode.toString());
} }
logger.trace("Setting Record-level Security (see https://orientdb.com/docs/last/Database-Security.html)"); logger.trace("Setting Record-level Security (see https://orientdb.com/docs/last/Database-Security.html)");
@ -85,24 +103,24 @@ public class DatabaseIntializator {
orientGraphNoTx.shutdown(); orientGraphNoTx.shutdown();
factory.close(); factory.close();
return true; return true;
} }
return false; return false;
} }
public static void createEntitiesAndRelations() throws Exception{ public static void createEntitiesAndRelations() throws Exception {
ERDiscovery.addPackage(Embedded.class.getPackage()); ERDiscovery.addPackage(Embedded.class.getPackage());
ERDiscovery.addPackage(Entity.class.getPackage()); ERDiscovery.addPackage(Entity.class.getPackage());
ERDiscovery.addPackage(Relation.class.getPackage()); ERDiscovery.addPackage(Relation.class.getPackage());
ERDiscovery erDiscovery = new ERDiscovery(); ERDiscovery erDiscovery = new ERDiscovery();
erDiscovery.discoverERTypes(); erDiscovery.discoverERTypes();
EntityRegistrationAction entityRegistrationAction = new EntityRegistrationAction(); EntityRegistrationAction entityRegistrationAction = new EntityRegistrationAction();
erDiscovery.manageDiscoveredERTypes(entityRegistrationAction); erDiscovery.manageDiscoveredERTypes(entityRegistrationAction);
} }
} }

View File

@ -45,10 +45,11 @@ public class Access {
*/ */
@GET @GET
public String query(@QueryParam(AccessPath.QUERY_PARAM) String query, public String query(@QueryParam(AccessPath.QUERY_PARAM) String query,
@QueryParam(AccessPath.LIMIT_PARAM) int limit,
@QueryParam(AccessPath.FETCH_PLAN_PARAM) String fetchPlan) @QueryParam(AccessPath.FETCH_PLAN_PARAM) String fetchPlan)
throws InvalidQueryException { throws InvalidQueryException {
logger.info("Requested query (fetch plan {}):\n{}", fetchPlan, query); logger.info("Requested query (fetch plan {}, limit : {}):\n{}", fetchPlan, limit, query);
return queryManager.execute(query, fetchPlan); return queryManager.query(query, limit, fetchPlan);
} }
/** /**

View File

@ -160,7 +160,7 @@ public class ContextManagementImpl implements ContextManagement {
SecurityContext.addToSecurityContext(orientGraph, SecurityContext.addToSecurityContext(orientGraph,
context.asVertex(), uuidString); context.asVertex(), uuidString);
String contextJsonString = Utility.toJsonString(context.asVertex()); String contextJsonString = Utility.toJsonString(context.asVertex(), true);
logger.trace("Creating {}", contextJsonString); logger.trace("Creating {}", contextJsonString);
orientGraph.commit(); orientGraph.commit();
@ -185,7 +185,7 @@ public class ContextManagementImpl implements ContextManagement {
OrientGraph orientGraph = SecurityContextMapper OrientGraph orientGraph = SecurityContextMapper
.getSecurityContextFactory(null, PermissionMode.READER).getTx(); .getSecurityContextFactory(null, PermissionMode.READER).getTx();
Vertex context = getContext(orientGraph, contextUUID); Vertex context = getContext(orientGraph, contextUUID);
return Utility.toJsonString(context); return Utility.toJsonString(context, false);
} }
@Override @Override
@ -223,7 +223,7 @@ public class ContextManagementImpl implements ContextManagement {
orientGraph.commit(); orientGraph.commit();
String contextJsonString = Utility.toJsonString(context); String contextJsonString = Utility.toJsonString(context, true);
logger.info("Context renamed {}", contextJsonString); logger.info("Context renamed {}", contextJsonString);
orientGraph.shutdown(); orientGraph.shutdown();
@ -246,7 +246,7 @@ public class ContextManagementImpl implements ContextManagement {
.getSecurityContextFactory(null, PermissionMode.WRITER).getTx(); .getSecurityContextFactory(null, PermissionMode.WRITER).getTx();
Vertex context = getContext(orientGraph, contextToMoveUUID); Vertex context = getContext(orientGraph, contextToMoveUUID);
logger.trace("Context to move {}", Utility.toJsonString(context)); logger.trace("Context to move {}", Utility.toJsonString(context, true));
checkContext(orientGraph, newParentUUID, checkContext(orientGraph, newParentUUID,
context.getProperty(Context.NAME_PROPERTY).toString()); context.getProperty(Context.NAME_PROPERTY).toString());
@ -263,14 +263,14 @@ public class ContextManagementImpl implements ContextManagement {
if (newParentUUID != null) { if (newParentUUID != null) {
Vertex parent = getContext(orientGraph, newParentUUID); Vertex parent = getContext(orientGraph, newParentUUID);
logger.trace("New Parent Context {}", logger.trace("New Parent Context {}",
Utility.toJsonString(parent)); Utility.toJsonString(parent, true));
orientGraph.addEdge(null, parent, context, IsParentOf.NAME); orientGraph.addEdge(null, parent, context, IsParentOf.NAME);
} }
orientGraph.commit(); orientGraph.commit();
context = getContext(orientGraph, contextToMoveUUID); context = getContext(orientGraph, contextToMoveUUID);
String contextJsonString = Utility.toJsonString(context); String contextJsonString = Utility.toJsonString(context, true);
logger.info("Context moved {}", contextJsonString); logger.info("Context moved {}", contextJsonString);
orientGraph.shutdown(); orientGraph.shutdown();
@ -288,7 +288,7 @@ public class ContextManagementImpl implements ContextManagement {
.getSecurityContextFactory(null, PermissionMode.WRITER).getTx(); .getSecurityContextFactory(null, PermissionMode.WRITER).getTx();
Vertex context = getContext(orientGraph, uuid); Vertex context = getContext(orientGraph, uuid);
logger.trace("Context to be delete {}", logger.trace("Context to be delete {}",
Utility.toJsonString(context)); Utility.toJsonString(context, true));
Iterable<Edge> edges = context.getEdges(Direction.OUT, IsParentOf.NAME); Iterable<Edge> edges = context.getEdges(Direction.OUT, IsParentOf.NAME);
if (edges != null && edges.iterator().hasNext()) { if (edges != null && edges.iterator().hasNext()) {

View File

@ -508,8 +508,8 @@ public class EntityManagementImpl implements EntityManagement {
logger.trace("Creating {} ({}) beetween {} -> {}", logger.trace("Creating {} ({}) beetween {} -> {}",
Relation.class.getSimpleName(), relationType, Relation.class.getSimpleName(), relationType,
Utility.toJsonString(source), Utility.toJsonString(source, true),
Utility.toJsonString(target)); Utility.toJsonString(target, true));
Edge edge = orientGraph.addEdge(null, source, target, relationType); Edge edge = orientGraph.addEdge(null, source, target, relationType);

View File

@ -3,24 +3,22 @@
*/ */
package org.gcube.informationsystem.resourceregistry.resources.impl; package org.gcube.informationsystem.resourceregistry.resources.impl;
import java.io.ByteArrayOutputStream; import java.io.StringWriter;
import java.io.InputStream; import java.io.Writer;
import java.net.HttpURLConnection; import java.util.List;
import java.net.URL;
import java.net.URLEncoder;
import org.gcube.informationsystem.resourceregistry.api.Query; import org.gcube.informationsystem.resourceregistry.api.Query;
import org.gcube.informationsystem.resourceregistry.api.exceptions.InvalidQueryException; import org.gcube.informationsystem.resourceregistry.api.exceptions.InvalidQueryException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.context.ContextException; import org.gcube.informationsystem.resourceregistry.api.rest.AccessPath;
import org.gcube.informationsystem.resourceregistry.context.SecurityContextMapper;
import org.gcube.informationsystem.resourceregistry.context.SecurityContextMapper.PermissionMode; import org.gcube.informationsystem.resourceregistry.context.SecurityContextMapper.PermissionMode;
import org.gcube.informationsystem.resourceregistry.dbinitialization.DatabaseEnvironment;
import org.gcube.informationsystem.resourceregistry.resources.utils.ContextUtility; import org.gcube.informationsystem.resourceregistry.resources.utils.ContextUtility;
import org.glassfish.jersey.internal.util.Base64; import org.gcube.informationsystem.resourceregistry.resources.utils.Utility;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import com.sun.research.ws.wadl.HTTPMethods; import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery;
/** /**
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
@ -30,15 +28,17 @@ public class QueryImpl implements Query {
private static Logger logger = LoggerFactory.getLogger(QueryImpl.class); private static Logger logger = LoggerFactory.getLogger(QueryImpl.class);
/*
private static final String QUERY = "query/"; private static final String QUERY = "query/";
private static final String SQL = "sql/"; private static final String SQL = "sql/";
private static final String DEFAULT_LIMIT = "20/";
private static final String DEFAULT_LIMIT = DEFAULT_LIMIT_INT + "/";
private static final URL BASE_QUERY_URL; private static final URL BASE_QUERY_URL;
static { static {
try { try {
URL url = new URL(DatabaseEnvironment.getHTTPURL()); URL url = new URL(DatabaseEnvironment.HTTP_URL_STRINGS[0]);
URL urlQuery = new URL(url, QUERY); URL urlQuery = new URL(url, QUERY);
URL urlDB = new URL(urlQuery, DatabaseEnvironment.DB + "/"); URL urlDB = new URL(urlQuery, DatabaseEnvironment.DB + "/");
BASE_QUERY_URL = new URL(urlDB, SQL); BASE_QUERY_URL = new URL(urlDB, SQL);
@ -76,13 +76,13 @@ public class QueryImpl implements Query {
URL queryURL = new URL(BASE_QUERY_URL, URLEncoder.encode(query, URL queryURL = new URL(BASE_QUERY_URL, URLEncoder.encode(query,
"UTF-8") + "/"); "UTF-8") + "/");
/* / *
if (limit != null && limit > 0) { if (limit != null && limit > 0) {
queryURL = new URL(queryURL, limit.toString() + "/"); queryURL = new URL(queryURL, limit.toString() + "/");
} else { } else {
queryURL = new URL(queryURL, DEFAULT_LIMIT); queryURL = new URL(queryURL, DEFAULT_LIMIT);
} }
*/ * /
queryURL = new URL(queryURL, DEFAULT_LIMIT); queryURL = new URL(queryURL, DEFAULT_LIMIT);
@ -119,5 +119,54 @@ public class QueryImpl implements Query {
throw new InvalidQueryException(e.getMessage(), e); throw new InvalidQueryException(e.getMessage(), e);
} }
}
*/
@Override
public String query(String query, int limit, String fetchPlan)
throws InvalidQueryException {
int sanitizedLimit = limit > 4 ? limit : AccessPath.DEFAULT_LIMIT;
ODatabaseDocumentTx oDatabaseDocumentTx = null;
try {
oDatabaseDocumentTx = ContextUtility
.getActualSecurityContextDatabaseTx(PermissionMode.READER);
OSQLSynchQuery<ODocument> osqlSynchQuery = new OSQLSynchQuery<>(query, sanitizedLimit);
osqlSynchQuery.setFetchPlan(fetchPlan);
osqlSynchQuery.setCacheableResult(true);
logger.debug("Going to execute query : \"{}\", fetchPlan : \"{}\", limit : {}",
osqlSynchQuery.getText(), osqlSynchQuery.getFetchPlan(),
osqlSynchQuery.getLimit());
List<Object> records = oDatabaseDocumentTx.query(osqlSynchQuery);
Writer writer = new StringWriter();
writer.append("{\"result\":[");
for(int i=0; i<records.size(); i++){
ODocument oDocument = (ODocument) records.get(i);
writer.append(Utility.toJsonString(oDocument, false));
if( i<(records.size()-1) ){
writer.append(",");
}
}
writer.append("]}");
return writer.toString();
} catch (Exception e) {
throw new InvalidQueryException(e.getMessage());
} finally {
if (oDatabaseDocumentTx != null) {
oDatabaseDocumentTx.close();
}
}
} }
} }

View File

@ -18,6 +18,7 @@ import org.gcube.informationsystem.resourceregistry.context.SecurityContextMappe
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;
import com.orientechnologies.orient.core.metadata.security.OSecurity; import com.orientechnologies.orient.core.metadata.security.OSecurity;
import com.orientechnologies.orient.core.record.impl.ODocument; import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery; import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery;
@ -25,6 +26,7 @@ import com.tinkerpop.blueprints.Edge;
import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.blueprints.Vertex;
import com.tinkerpop.blueprints.impls.orient.OrientGraph; import com.tinkerpop.blueprints.impls.orient.OrientGraph;
import com.tinkerpop.blueprints.impls.orient.OrientGraphFactory; import com.tinkerpop.blueprints.impls.orient.OrientGraphFactory;
import com.tinkerpop.blueprints.impls.orient.OrientGraphNoTx;
/** /**
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
@ -77,12 +79,25 @@ public class ContextUtility {
} }
} }
public static OrientGraphFactory getFactory(PermissionMode permissionMode) throws ResourceRegistryException{
try {
String contextID = getActualContextUUID();
return SecurityContextMapper
.getSecurityContextFactory(contextID, permissionMode);
} catch (ContextException ce) {
logger.error("Unable to retrieve context.", ce);
throw ce;
} catch (Exception e) {
logger.error("Unable to retrieve context.", e);
throw new ResourceRegistryException(e);
}
}
public static OrientGraph getActualSecurityContextGraph( public static OrientGraph getActualSecurityContextGraph(
PermissionMode permissionMode) throws ResourceRegistryException { PermissionMode permissionMode) throws ResourceRegistryException {
try { try {
String contextID = getActualContextUUID(); OrientGraphFactory factory = getFactory(permissionMode);
OrientGraphFactory factory = SecurityContextMapper
.getSecurityContextFactory(contextID, permissionMode);
return factory.getTx(); return factory.getTx();
} catch (ContextException ce) { } catch (ContextException ce) {
logger.error("Unable to retrieve context.", ce); logger.error("Unable to retrieve context.", ce);
@ -92,7 +107,36 @@ public class ContextUtility {
throw new ResourceRegistryException(e); throw new ResourceRegistryException(e);
} }
} }
public static OrientGraphNoTx getActualSecurityContextGraphNoTx(
PermissionMode permissionMode) throws ResourceRegistryException {
try {
OrientGraphFactory factory = getFactory(permissionMode);
return factory.getNoTx();
} catch (ContextException ce) {
logger.error("Unable to retrieve context.", ce);
throw ce;
} catch (Exception e) {
logger.error("Unable to retrieve context.", e);
throw new ResourceRegistryException(e);
}
}
public static ODatabaseDocumentTx getActualSecurityContextDatabaseTx(
PermissionMode permissionMode) throws ResourceRegistryException {
try {
OrientGraphFactory factory = getFactory(permissionMode);
return factory.getDatabase();
} catch (ContextException ce) {
logger.error("Unable to retrieve context.", ce);
throw ce;
} catch (Exception e) {
logger.error("Unable to retrieve context.", e);
throw new ResourceRegistryException(e);
}
}
public static Vertex getContextVertexByFullName(OrientGraph orientGraph, public static Vertex getContextVertexByFullName(OrientGraph orientGraph,
String fullName) throws ContextNotFoundException { String fullName) throws ContextNotFoundException {
@ -119,7 +163,7 @@ public class ContextUtility {
Vertex context = iterator.next(); Vertex context = iterator.next();
logger.trace("Context Representing Vertex : {}", logger.trace("Context Representing Vertex : {}",
Utility.toJsonString(context)); Utility.toJsonString(context, true));
if (iterator.hasNext()) { if (iterator.hasNext()) {
throw new ContextNotFoundException( throw new ContextNotFoundException(

View File

@ -42,12 +42,16 @@ public class Utility {
public static String toJsonString(OrientElement element, boolean raw) { public static String toJsonString(OrientElement element, boolean raw) {
ORecord oRecord = element.getRecord(); ORecord oRecord = element.getRecord();
return toJsonString(oRecord, raw);
}
public static String toJsonString(ORecord oRecord, boolean raw) {
if (raw) { if (raw) {
return oRecord.toJSON(); return oRecord.toJSON();
} }
return oRecord.toJSON("class"); return oRecord.toJSON("class");
} }
public static JSONObject toJsonObject(Element element, boolean raw) throws JSONException { public static JSONObject toJsonObject(Element element, boolean raw) throws JSONException {
if(raw){ if(raw){
return GraphSONUtility.jsonFromElement(element, return GraphSONUtility.jsonFromElement(element,
@ -64,7 +68,7 @@ public class Utility {
} }
} }
public static String toJsonString(Element element) { public static String toJsonString(Element element, boolean raw) {
try { try {
return toJsonObject(element, true).toString(); return toJsonObject(element, true).toString();
} catch (Exception e) { } catch (Exception e) {
@ -99,7 +103,7 @@ public class Utility {
Iterator<Vertex> iterator = vertexes.iterator(); Iterator<Vertex> iterator = vertexes.iterator();
Vertex entity = iterator.next(); Vertex entity = iterator.next();
logger.trace("{} with {} is : {}", entityType, uuid, Utility.toJsonString(entity)); logger.trace("{} with {} is : {}", entityType, uuid, Utility.toJsonString(entity, true));
if (iterator.hasNext()) { if (iterator.hasNext()) {
throw new ResourceRegistryException("Found more than one " throw new ResourceRegistryException("Found more than one "
@ -136,7 +140,7 @@ public class Utility {
Edge relation = iterator.next(); Edge relation = iterator.next();
logger.trace("{} with {} is : {}", relationType, uuid, logger.trace("{} with {} is : {}", relationType, uuid,
Utility.toJsonString(relation)); Utility.toJsonString(relation, true));
if (iterator.hasNext()) { if (iterator.hasNext()) {
throw new ResourceRegistryException("Found more than one " throw new ResourceRegistryException("Found more than one "

View File

@ -17,7 +17,7 @@ public class QueryManagerFactory implements Factory<Query>{
return new Query() { return new Query() {
@Override @Override
public String execute(String query, String fetchPlan) throws InvalidQueryException { public String query(String query, int limit, String fetchPlan) throws InvalidQueryException {
if (query.equals("error")) if (query.equals("error"))
throw new InvalidQueryException("error in query"); throw new InvalidQueryException("error in query");
return "result"; return "result";

View File

@ -21,7 +21,10 @@ public class QueryImplTest {
public void testQuery() throws InvalidQueryException{ public void testQuery() throws InvalidQueryException{
ScopeProvider.instance.set("/gcube/devNext"); ScopeProvider.instance.set("/gcube/devNext");
QueryImpl queryImpl = new QueryImpl(); QueryImpl queryImpl = new QueryImpl();
String ret = queryImpl.execute("select * from CPUFacet", null);
String query = "select * from CPUFacet";
String ret = queryImpl.query(query, 2, null);
logger.debug(ret); logger.debug(ret);
} }

View File

@ -1,4 +1,4 @@
HOST=orientdb01-d-d4s.d4science.org,orientdb02-d-d4s.d4science.org,orientdb02-d-d4s.d4science.org HOST=orientdb01-d-d4s.d4science.org;orientdb02-d-d4s.d4science.org;orientdb03-d-d4s.d4science.org
REMOTE_PROTOCOL=remote: REMOTE_PROTOCOL=remote:
HTTP_PROTOCOL=https:// HTTP_PROTOCOL=https://
HTTP_PORT=:443 HTTP_PORT=:443

View File

@ -1,4 +1,3 @@
#HOST=orientdb01-d-d4s.d4science.org
HOST=pc-frosini.isti.cnr.it HOST=pc-frosini.isti.cnr.it
REMOTE_PROTOCOL= remote: REMOTE_PROTOCOL= remote:

View File

@ -7,7 +7,7 @@
</appender> </appender>
<logger name="org.gcube" level="DEBUG" /> <logger name="org.gcube" level="TRACE" />
<root level="WARN"> <root level="WARN">
<appender-ref ref="STDOUT" /> <appender-ref ref="STDOUT" />