2017-08-01 18:00:19 +02:00
package org.gcube.datacatalogue.grsf_manage_widget.server.manage ;
import static org.gcube.resources.discovery.icclient.ICFactory.client ;
import java.io.StringReader ;
2017-11-09 14:49:07 +01:00
import java.util.ArrayList ;
2018-01-31 18:28:47 +01:00
import java.util.Arrays ;
2017-08-01 18:00:19 +02:00
import java.util.HashMap ;
import java.util.HashSet ;
import java.util.List ;
import java.util.Map ;
import java.util.Set ;
2017-11-09 14:49:07 +01:00
import java.util.regex.Matcher ;
import java.util.regex.Pattern ;
2017-08-01 18:00:19 +02:00
2017-11-09 14:49:07 +01:00
import javax.servlet.http.HttpServletRequest ;
2017-08-01 18:00:19 +02:00
import javax.servlet.http.HttpSession ;
import javax.xml.parsers.DocumentBuilder ;
import javax.xml.parsers.DocumentBuilderFactory ;
2018-02-02 15:28:35 +01:00
import org.gcube.common.authorization.library.provider.SecurityTokenProvider ;
2017-11-09 14:49:07 +01:00
import org.gcube.common.portal.PortalContext ;
2017-08-01 18:00:19 +02:00
import org.gcube.common.resources.gcore.utils.XPathHelper ;
import org.gcube.common.scope.api.ScopeProvider ;
2017-11-09 14:49:07 +01:00
import org.gcube.datacatalogue.ckanutillibrary.server.ApplicationProfileScopePerUrlReader ;
import org.gcube.datacatalogue.ckanutillibrary.server.DataCatalogue ;
2018-01-31 18:28:47 +01:00
import org.gcube.datacatalogue.ckanutillibrary.server.DataCatalogueRunningCluster ;
2017-08-01 18:00:19 +02:00
import org.gcube.datacatalogue.ckanutillibrary.shared.ex.ApplicationProfileNotFoundException ;
2017-11-09 14:49:07 +01:00
import org.gcube.datacatalogue.common.Constants ;
2018-02-02 17:32:30 +01:00
import org.gcube.datacatalogue.common.enums.Product_Type ;
2018-01-31 18:28:47 +01:00
import org.gcube.datacatalogue.common.enums.Status ;
2017-12-12 18:54:45 +01:00
import org.gcube.datacatalogue.grsf_manage_widget.shared.ConnectedBean ;
2017-11-09 14:49:07 +01:00
import org.gcube.datacatalogue.grsf_manage_widget.shared.ManageProductBean ;
2017-11-14 18:37:07 +01:00
import org.gcube.datacatalogue.grsf_manage_widget.shared.SimilarGRSFRecord ;
2017-08-01 18:00:19 +02:00
import org.gcube.resources.discovery.client.api.DiscoveryClient ;
import org.gcube.resources.discovery.client.queries.api.Query ;
import org.gcube.resources.discovery.client.queries.impl.QueryBox ;
2017-11-09 14:49:07 +01:00
import org.gcube.vomanagement.usermanagement.model.GCubeUser ;
import org.json.simple.JSONObject ;
import org.json.simple.parser.JSONParser ;
2017-11-14 18:37:07 +01:00
import org.json.simple.parser.ParseException ;
2017-08-01 18:00:19 +02:00
import org.slf4j.Logger ;
import org.slf4j.LoggerFactory ;
import org.w3c.dom.Node ;
import org.w3c.dom.NodeList ;
import org.xml.sax.InputSource ;
2017-11-14 18:37:07 +01:00
import com.liferay.portal.service.UserLocalServiceUtil ;
2017-11-09 14:49:07 +01:00
import eu.trentorise.opendata.jackan.internal.org.apache.http.impl.client.CloseableHttpClient ;
import eu.trentorise.opendata.jackan.internal.org.apache.http.impl.client.HttpClientBuilder ;
import eu.trentorise.opendata.jackan.model.CkanDataset ;
import eu.trentorise.opendata.jackan.model.CkanPair ;
2017-08-01 18:00:19 +02:00
/ * *
2017-11-09 14:49:07 +01:00
* Utility methods for GRSF Management panel widget .
2017-08-01 18:00:19 +02:00
* @author Costantino Perciante at ISTI - CNR ( costantino . perciante @isti.cnr.it )
* /
public class Utils {
private static final String GENERIC_RESOURCE_NAME = " GRSFManageEntries " ;
private static final String GENERIC_RESOURCE_SECONDARY_TYPE = " ApplicationProfile " ;
private static final Logger logger = LoggerFactory . getLogger ( Utils . class ) ;
2017-11-09 14:49:07 +01:00
private static final String REGEX_UUID = " [0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12} " ;
2017-08-01 18:00:19 +02:00
2017-11-09 14:49:07 +01:00
/ * *
* Look up from the IS other information that can be potentially displayed in read only mode in the management panel .
* @return a list of extra keys to show .
* /
2017-08-01 18:00:19 +02:00
public static Set < String > getLookedUpExtrasKeys ( ) {
Set < String > lookedUpExtrasKeys = new HashSet < String > ( ) ;
String scope = ScopeProvider . instance . get ( ) ;
logger . debug ( " Trying to fetch applicationProfile profile from the infrastructure for " + GENERIC_RESOURCE_NAME + " scope: " + scope ) ;
try {
Query q = new QueryBox ( " for $profile in collection('/db/Profiles/GenericResource')//Resource " +
" where $profile/Profile/SecondaryType/string() eq ' " + GENERIC_RESOURCE_SECONDARY_TYPE + " ' and $profile/Profile/Name/string() " +
" eq ' " + GENERIC_RESOURCE_NAME + " ' " +
" return $profile " ) ;
DiscoveryClient < String > client = client ( ) ;
List < String > appProfile = client . submit ( q ) ;
if ( appProfile = = null | | appProfile . size ( ) = = 0 )
throw new ApplicationProfileNotFoundException ( " Your applicationProfile is not registered in the infrastructure " ) ;
else {
String elem = appProfile . get ( 0 ) ;
DocumentBuilder docBuilder = DocumentBuilderFactory . newInstance ( ) . newDocumentBuilder ( ) ;
Node node = docBuilder . parse ( new InputSource ( new StringReader ( elem ) ) ) . getDocumentElement ( ) ;
XPathHelper helper = new XPathHelper ( node ) ;
List < String > currValue = null ;
currValue = helper . evaluate ( " /Resource/Profile/Body/text() " ) ;
if ( currValue ! = null & & currValue . size ( ) > 0 ) {
String body = currValue . get ( 0 ) ;
String [ ] splittedSet = body . split ( " , " ) ;
if ( splittedSet ! = null & & splittedSet . length > 0 )
for ( String entry : splittedSet ) {
String trimmed = entry . trim ( ) ;
if ( trimmed . isEmpty ( ) )
continue ;
lookedUpExtrasKeys . add ( trimmed ) ;
}
}
}
logger . info ( " Extras entries are " + lookedUpExtrasKeys ) ;
return lookedUpExtrasKeys ;
} catch ( Exception e ) {
logger . error ( " Error while trying to fetch applicationProfile profile from the infrastructure " , e ) ;
return null ;
}
}
/ * *
* Return a map for converting a key to a namespace : key format by reading a generic resource .
* @param httpSession
* @return a map
* /
2017-11-09 14:49:07 +01:00
@SuppressWarnings ( " unchecked " )
2017-08-01 18:00:19 +02:00
public static Map < String , String > getFieldToFieldNameSpaceMapping ( HttpSession httpSession , String resourceName ) {
2017-11-09 14:49:07 +01:00
2017-08-01 18:00:19 +02:00
// check if this information is available in session
String sessionKey = ScopeProvider . instance . get ( ) + resourceName ;
if ( httpSession . getAttribute ( sessionKey ) ! = null )
return ( Map < String , String > ) httpSession . getAttribute ( sessionKey ) ;
2017-11-09 14:49:07 +01:00
2017-08-01 18:00:19 +02:00
Map < String , String > namespacesMap = new HashMap < String , String > ( ) ; // e.g. fishery_identity:Short Title -> Short Title
try {
Query q = new QueryBox ( " for $profile in collection('/db/Profiles/GenericResource')//Resource " +
" where $profile/Profile/SecondaryType/string() eq ' " + " ApplicationProfile " + " ' and $profile/Profile/Name/string() " +
" eq ' " + resourceName + " ' " +
" return $profile " ) ;
DiscoveryClient < String > client = client ( ) ;
List < String > appProfile = client . submit ( q ) ;
if ( appProfile = = null | | appProfile . size ( ) = = 0 )
throw new Exception ( " Your applicationProfile is not registered in the infrastructure " ) ;
else {
String elem = appProfile . get ( 0 ) ;
DocumentBuilder docBuilder = DocumentBuilderFactory . newInstance ( ) . newDocumentBuilder ( ) ;
Node node = docBuilder . parse ( new InputSource ( new StringReader ( elem ) ) ) . getDocumentElement ( ) ;
XPathHelper helper = new XPathHelper ( node ) ;
NodeList nodeListKeys = helper . evaluateForNodes ( " //originalKey " ) ;
NodeList nodeListModifiedKeys = helper . evaluateForNodes ( " //modifiedKey " ) ;
int sizeKeys = nodeListKeys ! = null ? nodeListKeys . getLength ( ) : 0 ;
int sizeKeysModifed = nodeListModifiedKeys ! = null ? nodeListModifiedKeys . getLength ( ) : 0 ;
if ( sizeKeys ! = sizeKeysModifed )
throw new Exception ( " Malformed XML " ) ;
logger . debug ( " Size is " + sizeKeys ) ;
for ( int i = 0 ; i < sizeKeys ; i + + ) {
namespacesMap . put ( nodeListModifiedKeys . item ( i ) . getTextContent ( ) , nodeListKeys . item ( i ) . getTextContent ( ) ) ;
}
}
logger . debug ( " Map is " + namespacesMap ) ;
2018-02-02 17:32:30 +01:00
2018-02-02 15:28:35 +01:00
// put them into session for speeding up the operations
httpSession . setAttribute ( sessionKey , namespacesMap ) ;
2017-08-01 18:00:19 +02:00
return namespacesMap ;
} catch ( Exception e ) {
logger . error ( " Error while trying to fetch applicationProfile profile from the infrastructure " , e ) ;
return null ;
}
}
/ * *
2017-11-09 14:49:07 +01:00
* Replace the extras ' keys if needed , e . g . fishery_identity : Short Title - > Short Title
* @param extrasAsPairs
2017-08-01 18:00:19 +02:00
* @param namespaces
2017-11-09 14:49:07 +01:00
* @return a map with replaced key value pairs
2017-08-01 18:00:19 +02:00
* /
2017-11-09 14:49:07 +01:00
public static Map < String , List < String > > replaceFieldsKey ( List < CkanPair > extrasAsPairs ,
2017-08-01 18:00:19 +02:00
Map < String , String > namespaces ) {
2017-11-09 14:49:07 +01:00
Map < String , List < String > > toReturn = new HashMap < String , List < String > > ( ) ;
2017-08-01 18:00:19 +02:00
2017-11-09 14:49:07 +01:00
for ( CkanPair ckanPair : extrasAsPairs ) {
String pairKey = ckanPair . getKey ( ) ;
String pairValue = ckanPair . getValue ( ) ;
String replacedKey = namespaces . containsKey ( pairKey ) ? namespaces . get ( pairKey ) : pairKey ;
2017-08-01 18:00:19 +02:00
2017-11-09 14:49:07 +01:00
List < String > values = null ;
if ( toReturn . containsKey ( replacedKey ) )
values = toReturn . get ( replacedKey ) ;
2017-08-01 18:00:19 +02:00
else
2017-11-09 14:49:07 +01:00
values = new ArrayList < String > ( 1 ) ;
values . add ( pairValue ) ;
toReturn . put ( replacedKey , values ) ;
}
return toReturn ;
}
2018-01-31 18:28:47 +01:00
/ * *
* Get the extras of this dataset as hashmap
* @param extrasAsPairs
* @return
* /
2018-02-02 15:28:35 +01:00
public static Map < String , List < String > > getExtrasAsHashMap ( List < CkanPair > extrasAsPairs ) {
2018-01-31 18:28:47 +01:00
Map < String , List < String > > toReturn = new HashMap < String , List < String > > ( ) ;
for ( CkanPair ckanPair : extrasAsPairs ) {
String pairKey = ckanPair . getKey ( ) ;
String pairValue = ckanPair . getValue ( ) ;
List < String > values = null ;
if ( toReturn . containsKey ( pairKey ) )
values = toReturn . get ( pairKey ) ;
else
values = new ArrayList < String > ( 1 ) ;
values . add ( pairValue ) ;
toReturn . put ( pairKey , values ) ;
}
return toReturn ;
}
2017-11-09 14:49:07 +01:00
/ * *
* Send an update for this bean
* @param baseUrl
* @param bean
* @param username
* @param catalogue
* @return true on success , false otherwise
* /
2018-02-02 17:32:30 +01:00
public static String updateRecord (
String serviceUrl ,
ManageProductBean bean ,
DataCatalogue catalogue ,
String username ,
String fullName ,
HttpServletRequest httpServletRequest ,
long groupId ,
String context ,
String token ,
List < String > hashtags ) throws Exception {
2017-11-09 14:49:07 +01:00
if ( serviceUrl = = null )
throw new IllegalArgumentException ( " GRSF Updater service url cannot be null " ) ;
if ( bean = = null )
throw new IllegalArgumentException ( " Item bean to manage cannot be null " ) ;
try ( CloseableHttpClient httpClient = HttpClientBuilder . create ( ) . build ( ) ; ) {
2018-01-31 18:28:47 +01:00
// if there are merges, update the status of the involved records immediately
if ( bean . isMergesInvolved ( ) )
updateStatusInvolvedRecords ( bean , catalogue ) ;
2017-11-09 14:49:07 +01:00
2018-01-31 18:28:47 +01:00
// send update to the knowledge base
2018-02-02 15:28:35 +01:00
GRSFUpdaterServiceClient . updateKB ( httpClient , serviceUrl , bean , catalogue , username , fullName ) ;
// manage interactions through a separated thread but set there security token and context
new Thread ( ( ) - > {
2018-02-02 17:32:30 +01:00
2018-02-02 15:28:35 +01:00
ScopeProvider . instance . set ( context ) ;
SecurityTokenProvider . instance . set ( token ) ;
2018-02-02 17:32:30 +01:00
try {
// send email to Editors and Reviewers
SocialCommunications . sendEmailAdministrators ( bean , catalogue , username , fullName , groupId , httpServletRequest , bean . isMergesInvolved ( ) ) ;
// create a post about the operation
SocialCommunications . writeProductPost ( bean , username , fullName , hashtags , true ) ;
} catch ( Exception e ) {
logger . error ( " Something failed while alerting editors/reviewers " , e ) ;
}
2018-02-02 15:28:35 +01:00
} ) . start ( ) ;
2017-12-13 18:34:45 +01:00
2018-01-31 18:28:47 +01:00
} catch ( Exception e ) {
logger . error ( " Unable to update this Item " , e ) ;
throw e ;
}
return null ;
}
/ * *
* Update the status of the involved records to " to be merged "
* @param bean
* @param catalogue
* @param username
* @param fullName
* @throws Exception
* /
private static void updateStatusInvolvedRecords ( ManageProductBean bean , DataCatalogue catalogue ) throws Exception {
String context = ScopeProvider . instance . get ( ) ;
String sysApi = fetchSysAPI ( context ) ;
for ( SimilarGRSFRecord s : bean . getSimilarGrsfRecords ( ) ) {
if ( s . isSuggestedMerge ( ) ) {
String productId = s . getKnowledgeBaseId ( ) ;
2018-02-02 15:28:35 +01:00
Map < String , List < String > > extrasMap = getExtrasAsHashMap ( catalogue . getDataset ( productId , sysApi ) . getExtras ( ) ) ;
2018-01-31 18:28:47 +01:00
extrasMap . put ( Constants . STATUS_OF_THE_GRSF_RECORD_CUSTOM_KEY , Arrays . asList ( Status . To_be_Merged . getOrigName ( ) ) ) ;
catalogue . patchProductCustomFields ( productId , sysApi , extrasMap ) ;
}
}
// update the current status record
String productId = bean . getKnowledgeBaseIdentifier ( ) ;
2018-02-02 15:28:35 +01:00
Map < String , List < String > > extrasMap = getExtrasAsHashMap ( catalogue . getDataset ( productId , sysApi ) . getExtras ( ) ) ;
2018-01-31 18:28:47 +01:00
extrasMap . put ( Constants . STATUS_OF_THE_GRSF_RECORD_CUSTOM_KEY , Arrays . asList ( Status . To_be_Merged . getOrigName ( ) ) ) ;
catalogue . patchProductCustomFields ( productId , sysApi , extrasMap ) ;
}
2017-12-13 18:34:45 +01:00
2017-11-09 14:49:07 +01:00
/ * *
* Get the scope in which ckan information needs to be discovered from the url
* @param httpServletRequest
* @return
* /
public static String getScopeFromClientUrl ( HttpServletRequest httpServletRequest ) {
if ( httpServletRequest = = null )
throw new IllegalArgumentException ( " HttpServletRequest is null! " ) ;
String scopeToReturn = null ;
try {
String clientUrl = getCurrentClientUrl ( httpServletRequest ) . split ( " \\ ? " ) [ 0 ] ;
logger . debug ( " Client url is " + clientUrl ) ;
// check if this information is in session, otherwise set it and return
HttpSession session = httpServletRequest . getSession ( ) ;
if ( ( scopeToReturn = ( String ) session . getAttribute ( clientUrl ) ) ! = null ) {
logger . debug ( " Scope to return is " + scopeToReturn ) ;
} else {
// ask to the ckan library and set it
scopeToReturn = ApplicationProfileScopePerUrlReader . getScopePerUrl ( clientUrl ) ;
logger . debug ( " Scope to return is " + scopeToReturn ) ;
session . setAttribute ( clientUrl , scopeToReturn ) ;
}
} catch ( Exception e ) {
2017-11-14 18:37:07 +01:00
scopeToReturn = getCurrentContext ( httpServletRequest , true ) ;
2017-11-09 14:49:07 +01:00
logger . warn ( " Failed to determine the scope from the client url, returning the current one: " + scopeToReturn ) ;
}
return scopeToReturn ;
}
/ * *
* Needed to get the url of the client
* @param httpServletRequest the httpServletRequest object
* @return the instance of the user
* @see the url at client side
* /
public static String getCurrentClientUrl ( HttpServletRequest httpServletRequest ) {
if ( httpServletRequest = = null )
throw new IllegalArgumentException ( " HttpServletRequest is null! " ) ;
return httpServletRequest . getHeader ( Constants . GCUBE_REQUEST_URL ) ;
}
/ * *
* Retrieve the current scope by using the portal manager
* @param b
* @return a GcubeUser object
* /
public static String getCurrentContext ( HttpServletRequest request , boolean setInThread ) {
if ( request = = null )
throw new IllegalArgumentException ( " HttpServletRequest is null! " ) ;
PortalContext pContext = PortalContext . getConfiguration ( ) ;
String context = pContext . getCurrentScope ( request ) ;
logger . debug ( " Returning context " + context ) ;
if ( context ! = null & & setInThread )
ScopeProvider . instance . set ( context ) ;
return context ;
}
/ * *
* Retrieve the current user by using the portal manager
* @return a GcubeUser object
* /
public static GCubeUser getCurrentUser ( HttpServletRequest request ) {
if ( request = = null )
throw new IllegalArgumentException ( " HttpServletRequest is null! " ) ;
PortalContext pContext = PortalContext . getConfiguration ( ) ;
GCubeUser user = pContext . getCurrentUser ( request ) ;
logger . debug ( " Returning user " + user ) ;
return user ;
}
2018-02-02 17:32:30 +01:00
// /**
// * Given a semantic identifier, check if a record exists and return it
// * @param suggestedRecordSemanticIdentifier
// * @param catalogue
// * @return CkanDataset
// * @throws Exception in case no record matches the semantic identifier
// */
// public static CkanDataset getRecordBySemanticIdentifier(
// String suggestedRecordSemanticIdentifier, DataCatalogue catalogue,
// String apiKey) throws Exception {
//
// if(suggestedRecordSemanticIdentifier == null || suggestedRecordSemanticIdentifier.isEmpty())
// throw new Exception(Constants.GRSF_SEMANTIC_IDENTIFIER_CUSTOM_KEY + " cannot be null or emtpy");
//
// String query = Constants.GRSF_SEMANTIC_IDENTIFIER_CUSTOM_KEY + "\"" + suggestedRecordSemanticIdentifier+ "\"";
// List<CkanDataset> datasets = catalogue.searchForPackageInOrganization(apiKey, query, 0, 10, Constants.GRSF_ADMIN_ORGANIZATION_NAME);
//
// if(datasets == null || datasets.isEmpty()){
// String message = "Unable to find dataset with such " + Constants.GRSF_SEMANTIC_IDENTIFIER_CUSTOM_KEY;
// logger.warn(message);
// throw new Exception(message);
// }
//
// logger.info("Result size is " + datasets.size());
//
// if(datasets.size() == 1)
// return datasets.get(0);
// else{
//
// // worst situation.. we need to check for the right one
// for(CkanDataset dataset: datasets)
// for(CkanPair extra : dataset.getExtras())
// if(extra.getKey().contains(Constants.GRSF_SEMANTIC_IDENTIFIER_CUSTOM_KEY) && extra.getValue().equals(suggestedRecordSemanticIdentifier)){
// logger.info("Matching dataset has id " + dataset.getId() + " with value " + Constants.GRSF_SEMANTIC_IDENTIFIER_CUSTOM_KEY);
// return dataset;
// }
//
// }
//
// // in the end ....
// throw new Exception("Unable to find record with " + Constants.GRSF_SEMANTIC_IDENTIFIER_CUSTOM_KEY + " equals to " + suggestedRecordSemanticIdentifier);
//
// }
2017-11-09 14:49:07 +01:00
/ * *
* Exploits the fact that in GRSF the url of a record contains the name ( which is unique ) of the record itself
* @param url
* @param clg
* @return
2018-02-02 15:28:35 +01:00
* @throws Exception
2017-11-09 14:49:07 +01:00
* /
2018-02-02 15:28:35 +01:00
public static CkanDataset getDatasetFromUrl ( String url , DataCatalogue clg , String apiKey ) throws Exception {
2017-11-09 14:49:07 +01:00
if ( url = = null | | url . isEmpty ( ) )
return null ;
// Parse url
// Create a Pattern object
Pattern r = Pattern . compile ( REGEX_UUID ) ;
// Now create matcher object.
Matcher m = r . matcher ( url ) ;
if ( m . find ( ) ) {
String uuidFound = m . group ( ) ;
logger . debug ( " Found match for uuid " + uuidFound ) ;
return clg . getDataset ( uuidFound , apiKey ) ;
}
2018-02-02 15:28:35 +01:00
throw new Exception ( " No record exists with such url " + url ) ;
2017-11-09 14:49:07 +01:00
}
2017-12-13 18:34:45 +01:00
2017-12-12 18:54:45 +01:00
/ * *
* Exploits the fact that in GRSF the url of a record contains the name ( which is unique ) of the record itself
* @param url
* @param clg
* @return
* /
public static String getDatasetKnowledgeBaseIdFromUrl ( String url ) {
if ( url = = null | | url . isEmpty ( ) )
return null ;
// Parse url
// Create a Pattern object
Pattern r = Pattern . compile ( REGEX_UUID ) ;
// Now create matcher object.
Matcher m = r . matcher ( url ) ;
if ( m . find ( ) ) {
String uuidFound = m . group ( ) ;
logger . debug ( " Found match for uuid " + uuidFound ) ;
return uuidFound ;
}
return null ;
}
2017-11-09 14:49:07 +01:00
// /**
// * Get extra information to show in the management panel, if any
// * @param extrasAsPairs
// */
// public static void getExtrasToShow(List<CkanPair> extrasAsPairs, ){
//
// Set<String> extrasToShow = getLookedUpExtrasKeys();
// if(extrasToShow != null && !extrasToShow.isEmpty()){
// Map<String, String> extrasKeyValuePair = new HashMap<String, String>();
// = product.getExtras();
// for (CkanPair ckanPair : extrasAsPairs) {
// String key = ckanPair.getKey();
// String value = ckanPair.getValue();
//
// if(extrasToShow.contains(key)){
// String currentValueInMap = extrasKeyValuePair.get(key);
// if(currentValueInMap == null)
// currentValueInMap = value;
// else
// currentValueInMap += ", " + value;
// extrasKeyValuePair.put(key, currentValueInMap);
// }
// }
// toReturn.setExtrasIfAvailable(extrasKeyValuePair);
// }
//
// }
2017-12-13 18:34:45 +01:00
2017-11-14 18:37:07 +01:00
/ * *
* Get a { @link SimilarGRSFRecord } from a json string
* @param json
* @return { @link SimilarGRSFRecord }
* @throws ParseException
* /
public static SimilarGRSFRecord similarGRSFRecordFromJson ( String json ) throws ParseException {
if ( json = = null )
return null ;
JSONParser parser = new JSONParser ( ) ;
JSONObject object = ( JSONObject ) parser . parse ( json ) ;
return new SimilarGRSFRecord (
( String ) object . get ( Constants . SIMILAR_RECORDS_BEAN_FIELD_DESCRIPTION ) ,
2017-12-12 18:54:45 +01:00
getDatasetKnowledgeBaseIdFromUrl ( ( String ) object . get ( Constants . SIMILAR_RECORDS_BEAN_FIELD_URL ) ) ,
2017-11-14 18:37:07 +01:00
( String ) object . get ( Constants . SIMILAR_RECORDS_BEAN_FIELD_IDENTIFIER ) ,
( String ) object . get ( Constants . SIMILAR_RECORDS_BEAN_FIELD_NAME ) ,
( String ) object . get ( Constants . SIMILAR_RECORDS_BEAN_FIELD_URL )
) ;
}
2017-12-13 18:34:45 +01:00
2017-11-14 18:37:07 +01:00
/ * *
* Checks if is into portal .
*
* @return true , if is into portal
* /
public static boolean isIntoPortal ( ) {
try {
UserLocalServiceUtil . getService ( ) ;
return true ;
} catch ( Exception ex ) {
logger . debug ( " Development Mode ON " ) ;
return false ;
}
}
2017-11-09 14:49:07 +01:00
2017-12-12 18:54:45 +01:00
/ * *
* Get Connected bean from record
2018-02-02 17:32:30 +01:00
* @param httpSession
2017-12-12 18:54:45 +01:00
* @param json
* @param sourceIdentifier
* @param sourceDomain
2018-02-02 15:28:35 +01:00
* @param grsfDomain
2017-12-12 18:54:45 +01:00
* @return
* @throws ParseException
* /
2018-02-02 15:28:35 +01:00
public static ConnectedBean connectedBeanRecordFromUrl (
String destUrl ,
DataCatalogue clg ,
2018-02-02 17:32:30 +01:00
String apiKey ,
HttpSession httpSession
) throws ParseException {
2018-02-02 15:28:35 +01:00
if ( destUrl = = null )
2017-12-12 18:54:45 +01:00
return null ;
2018-02-02 17:32:30 +01:00
String connectedBeanUuid = getDatasetKnowledgeBaseIdFromUrl ( destUrl ) ;
2018-02-02 15:28:35 +01:00
CkanDataset destDataset = clg . getDataset ( connectedBeanUuid , apiKey ) ;
2018-02-02 17:32:30 +01:00
boolean isStock = destDataset . getExtrasAsHashMap ( ) . get ( Constants . DOMAIN_CUSTOM_KEY ) . contains ( Product_Type . STOCK . getOrigName ( ) ) ;
Map < String , String > fieldsNamespacesMap =
Utils . getFieldToFieldNameSpaceMapping ( httpSession , isStock ?
Constants . GENERIC_RESOURCE_NAME_MAP_KEY_NAMESPACES_STOCK : Constants . GENERIC_RESOURCE_NAME_MAP_KEY_NAMESPACES_FISHERY ) ;
Map < String , List < String > > extrasWithoutNamespaces = Utils . replaceFieldsKey ( destDataset . getExtras ( ) , fieldsNamespacesMap ) ;
String semanticId = extrasWithoutNamespaces . get ( Constants . GRSF_SEMANTIC_IDENTIFIER_CUSTOM_KEY ) . get ( 0 ) ;
String destDomain = extrasWithoutNamespaces . get ( Constants . DOMAIN_CUSTOM_KEY ) . get ( 0 ) ;
2017-12-12 18:54:45 +01:00
return new ConnectedBean (
2018-02-02 15:28:35 +01:00
connectedBeanUuid ,
destDataset . getTitle ( ) ,
destUrl ,
2018-02-02 17:32:30 +01:00
destDomain ,
semanticId
2017-12-12 18:54:45 +01:00
) ;
2017-12-13 18:34:45 +01:00
2017-12-12 18:54:45 +01:00
}
2018-01-31 18:28:47 +01:00
/ * *
* Fetch the sysadmin key from the IS
* @return
* @throws Exception
* /
public static String fetchSysAPI ( String context ) throws Exception {
DataCatalogueRunningCluster catalogueRunningInstance = new DataCatalogueRunningCluster ( context ) ;
return catalogueRunningInstance . getSysAdminToken ( ) ;
}
2017-08-01 18:00:19 +02:00
}