diff --git a/.legacy/Backend/3party-fixes/alfresco-solr-4.0.e-fixes/src/org/alfresco/solr/ESSlaveAlfrescoSolrEventListener.java b/.legacy/Backend/3party-fixes/alfresco-solr-4.0.e-fixes/src/org/alfresco/solr/ESSlaveAlfrescoSolrEventListener.java index 5f116d8973..2827b7d0da 100644 --- a/.legacy/Backend/3party-fixes/alfresco-solr-4.0.e-fixes/src/org/alfresco/solr/ESSlaveAlfrescoSolrEventListener.java +++ b/.legacy/Backend/3party-fixes/alfresco-solr-4.0.e-fixes/src/org/alfresco/solr/ESSlaveAlfrescoSolrEventListener.java @@ -5,7 +5,7 @@ import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; -import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicBoolean; import org.apache.lucene.index.IndexReader; @@ -63,7 +63,7 @@ public void newSearcher(SolrIndexSearcher newSearcher, SolrIndexSearcher current OpenBitSet deleted = new OpenBitSet(); OwnerIdManager ownerIdManager = new OwnerIdManager(); - HashMap unmatchedByDBID = new HashMap(); + Map unmatchedByDBID = new HashMap<>(); if (currentSearcher != null) { @@ -75,21 +75,21 @@ public void newSearcher(SolrIndexSearcher newSearcher, SolrIndexSearcher current OwnerIdManager oldOwnerIdManager = (OwnerIdManager) currentSearcher.cacheLookup(ALFRESCO_CACHE, KEY_OWNER_ID_MANAGER); ownerIdManager.addAll(oldOwnerIdManager); - ConcurrentHashMap addedLeaves = (ConcurrentHashMap) currentSearcher.cacheLookup(ALFRESCO_CACHE, KEY_ADDED_LEAVES); - ConcurrentHashMap addedAux = (ConcurrentHashMap) currentSearcher.cacheLookup(ALFRESCO_CACHE, KEY_ADDED_AUX); - ConcurrentHashMap addedAcl = (ConcurrentHashMap) currentSearcher.cacheLookup(ALFRESCO_CACHE, KEY_ADDED_ACL); - ConcurrentHashMap addedTx = (ConcurrentHashMap) currentSearcher.cacheLookup(ALFRESCO_CACHE, KEY_ADDED_TX); - ConcurrentHashMap addedAclTx = (ConcurrentHashMap) currentSearcher.cacheLookup(ALFRESCO_CACHE, KEY_ADDED_ACL_TX); - ConcurrentHashMap updatedLeaves = (ConcurrentHashMap) currentSearcher.cacheLookup(ALFRESCO_CACHE, KEY_UPDATED_LEAVES); - ConcurrentHashMap updatedAux = (ConcurrentHashMap) currentSearcher.cacheLookup(ALFRESCO_CACHE, KEY_UPDATED_AUX); - ConcurrentHashMap updatedAcl = (ConcurrentHashMap) currentSearcher.cacheLookup(ALFRESCO_CACHE, KEY_UPDATED_ACL); - ConcurrentHashMap updatedTx = (ConcurrentHashMap) currentSearcher.cacheLookup(ALFRESCO_CACHE, KEY_UPDATED_TX); - ConcurrentHashMap updatedAclTx = (ConcurrentHashMap) currentSearcher.cacheLookup(ALFRESCO_CACHE, KEY_UPDATED_ACL_TX); - ConcurrentHashMap deletedLeaves = (ConcurrentHashMap) currentSearcher.cacheLookup(ALFRESCO_CACHE, KEY_DELETED_LEAVES); - ConcurrentHashMap deletedAux = (ConcurrentHashMap) currentSearcher.cacheLookup(ALFRESCO_CACHE, KEY_DELETED_AUX); - ConcurrentHashMap deletedAcl = (ConcurrentHashMap) currentSearcher.cacheLookup(ALFRESCO_CACHE, KEY_DELETED_ACL); - ConcurrentHashMap deletedTx = (ConcurrentHashMap) currentSearcher.cacheLookup(ALFRESCO_CACHE, KEY_DELETED_TX); - ConcurrentHashMap deletedAclTx = (ConcurrentHashMap) currentSearcher.cacheLookup(ALFRESCO_CACHE, KEY_DELETED_ACL_TX); + ConcurrentMap addedLeaves = (ConcurrentMap) currentSearcher.cacheLookup(ALFRESCO_CACHE, KEY_ADDED_LEAVES); + ConcurrentMap addedAux = (ConcurrentMap) currentSearcher.cacheLookup(ALFRESCO_CACHE, KEY_ADDED_AUX); + ConcurrentMap addedAcl = (ConcurrentMap) currentSearcher.cacheLookup(ALFRESCO_CACHE, KEY_ADDED_ACL); + ConcurrentMap addedTx = (ConcurrentMap) currentSearcher.cacheLookup(ALFRESCO_CACHE, KEY_ADDED_TX); + ConcurrentMap addedAclTx = (ConcurrentMap) currentSearcher.cacheLookup(ALFRESCO_CACHE, KEY_ADDED_ACL_TX); + ConcurrentMap updatedLeaves = (ConcurrentMap) currentSearcher.cacheLookup(ALFRESCO_CACHE, KEY_UPDATED_LEAVES); + ConcurrentMap updatedAux = (ConcurrentMap) currentSearcher.cacheLookup(ALFRESCO_CACHE, KEY_UPDATED_AUX); + ConcurrentMap updatedAcl = (ConcurrentMap) currentSearcher.cacheLookup(ALFRESCO_CACHE, KEY_UPDATED_ACL); + ConcurrentMap updatedTx = (ConcurrentMap) currentSearcher.cacheLookup(ALFRESCO_CACHE, KEY_UPDATED_TX); + ConcurrentMap updatedAclTx = (ConcurrentMap) currentSearcher.cacheLookup(ALFRESCO_CACHE, KEY_UPDATED_ACL_TX); + ConcurrentMap deletedLeaves = (ConcurrentMap) currentSearcher.cacheLookup(ALFRESCO_CACHE, KEY_DELETED_LEAVES); + ConcurrentMap deletedAux = (ConcurrentMap) currentSearcher.cacheLookup(ALFRESCO_CACHE, KEY_DELETED_AUX); + ConcurrentMap deletedAcl = (ConcurrentMap) currentSearcher.cacheLookup(ALFRESCO_CACHE, KEY_DELETED_ACL); + ConcurrentMap deletedTx = (ConcurrentMap) currentSearcher.cacheLookup(ALFRESCO_CACHE, KEY_DELETED_TX); + ConcurrentMap deletedAclTx = (ConcurrentMap) currentSearcher.cacheLookup(ALFRESCO_CACHE, KEY_DELETED_ACL_TX); AtomicBoolean deleteAll = (AtomicBoolean) currentSearcher.cacheLookup(ALFRESCO_CACHE, KEY_DELETE_ALL); AtomicBoolean checkCache = (AtomicBoolean) currentSearcher.cacheLookup(ALFRESCO_CACHE, KEY_CHECK_CACHE); @@ -188,7 +188,7 @@ public int compare(CacheEntry o1, CacheEntry o2) // build lookups - HashMap alcLookUp = new HashMap(); + Map alcLookUp = new HashMap<>(); AclLookUp currentAclLookUp = null; for (int i = 0; i < indexedOderedByAclIdThenDoc.length; i++) @@ -276,7 +276,7 @@ public int compare(CacheEntry o1, CacheEntry o2) // build lookups - HashMap ownerLookUp = new HashMap(); + Map ownerLookUp = new HashMap<>(); OwnerLookUp currentOwnerLookUp = null; for (int i = 0; i < indexedOderedByOwnerIdThenDoc.length; i++) diff --git a/.legacy/Backend/3party-fixes/alfresco-solr-4.0.e-fixes/src/org/alfresco/solr/client/SOLRAPIClient.java b/.legacy/Backend/3party-fixes/alfresco-solr-4.0.e-fixes/src/org/alfresco/solr/client/SOLRAPIClient.java index 6161cf3822..56e941fc4b 100644 --- a/.legacy/Backend/3party-fixes/alfresco-solr-4.0.e-fixes/src/org/alfresco/solr/client/SOLRAPIClient.java +++ b/.legacy/Backend/3party-fixes/alfresco-solr-4.0.e-fixes/src/org/alfresco/solr/client/SOLRAPIClient.java @@ -172,7 +172,7 @@ public List getAclChangeSets(Long fromCommitTime, Long minAclChang } JSONArray aclChangeSetsJSON = json.getJSONArray("aclChangeSets"); - List aclChangeSets = new ArrayList(aclChangeSetsJSON.length()); + List aclChangeSets = new ArrayList<>(aclChangeSetsJSON.length()); for (int i = 0; i < aclChangeSetsJSON.length(); i++) { JSONObject aclChangeSetJSON = aclChangeSetsJSON.getJSONObject(i); @@ -217,7 +217,7 @@ public List getAcls(List aclChangeSets, Long minAclId, int ma JSONObject jsonReq = new JSONObject(); JSONArray aclChangeSetIdsJSON = new JSONArray(); - List aclChangeSetIds = new ArrayList(); + List aclChangeSetIds = new ArrayList<>(); for (AclChangeSet aclChangeSet : aclChangeSets) { Long aclChangeSetId = aclChangeSet.getId(); @@ -255,7 +255,7 @@ public List getAcls(List aclChangeSets, Long minAclId, int ma } JSONArray aclsJSON = json.getJSONArray("acls"); - List acls = new ArrayList(aclsJSON.length()); + List acls = new ArrayList<>(aclsJSON.length()); for (int i = 0; i < aclsJSON.length(); i++) { JSONObject aclJSON = aclsJSON.getJSONObject(i); @@ -285,7 +285,7 @@ public List getAclReaders(List acls) throws AuthenticationExcep JSONObject jsonReq = new JSONObject(); JSONArray aclIdsJSON = new JSONArray(); - List aclIds = new ArrayList(); + List aclIds = new ArrayList<>(); for (Acl acl : acls) { Long aclId = acl.getId(); @@ -323,13 +323,13 @@ public List getAclReaders(List acls) throws AuthenticationExcep } JSONArray aclsReadersJSON = json.getJSONArray("aclsReaders"); - List aclsReaders = new ArrayList(aclsReadersJSON.length()); + List aclsReaders = new ArrayList<>(aclsReadersJSON.length()); for (int i = 0; i < aclsReadersJSON.length(); i++) { JSONObject aclReadersJSON = aclsReadersJSON.getJSONObject(i); long aclId = aclReadersJSON.getLong("aclId"); JSONArray readersJSON = aclReadersJSON.getJSONArray("readers"); - List readers = new ArrayList(aclReadersJSON.length()); + List readers = new ArrayList<>(aclReadersJSON.length()); for (int j = 0; j < readersJSON.length(); j++) { String readerJSON = readersJSON.getString(j); @@ -406,7 +406,7 @@ public Transactions getTransactions(Long fromCommitTime, Long minTxnId, Long toC JSONArray jsonTransactions = json.getJSONArray("transactions"); int numTxns = jsonTransactions.length(); - List transactions = new ArrayList(numTxns); + List transactions = new ArrayList<>(numTxns); for(int i = 0; i < numTxns; i++) { JSONObject solrTxn = jsonTransactions.getJSONObject(i); @@ -512,7 +512,7 @@ public List getNodes(GetNodesParameters parameters, int maxResults) throws } JSONArray jsonNodes = json.getJSONArray("nodes"); - List nodes = new ArrayList(jsonNodes.length()); + List nodes = new ArrayList<>(jsonNodes.length()); for(int i = 0; i < jsonNodes.length(); i++) { JSONObject jsonNodeInfo = jsonNodes.getJSONObject(i); @@ -566,7 +566,7 @@ private PropertyValue getSinglePropertyValue(DataTypeDefinition dataType, Object else if(dataTypeName.equals(DataTypeDefinition.MLTEXT) && (value instanceof JSONArray)) { JSONArray a = (JSONArray)value; - Map mlValues = new HashMap(a.length()); + Map mlValues = new HashMap<>(a.length()); for(int k = 0; k < a.length(); k++) { @@ -751,7 +751,7 @@ public List getNodesMetaData(NodeMetaDataParameters params, int ma JSONArray jsonNodes = json.getJSONArray("nodes"); - List nodes = new ArrayList(jsonNodes.length()); + List nodes = new ArrayList<>(jsonNodes.length()); for(int i = 0; i < jsonNodes.length(); i++) { JSONObject jsonNodeInfo = jsonNodes.getJSONObject(i); @@ -829,7 +829,7 @@ public List getNodesMetaData(NodeMetaDataParameters params, int ma if(jsonNodeInfo.has("properties")) { JSONObject jsonProperties = jsonNodeInfo.getJSONObject("properties"); - Map properties = new HashMap(jsonProperties.length()); + Map properties = new HashMap<>(jsonProperties.length()); @SuppressWarnings("rawtypes") Iterator propKeysIterator = jsonProperties.keys(); while(propKeysIterator.hasNext()) @@ -859,7 +859,7 @@ public List getNodesMetaData(NodeMetaDataParameters params, int ma if(jsonNodeInfo.has("parentAssocs")) { JSONArray jsonParentAssocs = jsonNodeInfo.getJSONArray("parentAssocs"); - List assocs = new ArrayList(jsonParentAssocs.length()); + List assocs = new ArrayList<>(jsonParentAssocs.length()); for(int j = 0; j < jsonParentAssocs.length(); j++) { String childAssocRefStr = jsonParentAssocs.getString(j); @@ -872,7 +872,7 @@ public List getNodesMetaData(NodeMetaDataParameters params, int ma if(jsonNodeInfo.has("childAssocs")) { JSONArray jsonParentAssocs = jsonNodeInfo.getJSONArray("childAssocs"); - List assocs = new ArrayList(jsonParentAssocs.length()); + List assocs = new ArrayList<>(jsonParentAssocs.length()); for(int j = 0; j < jsonParentAssocs.length(); j++) { String childAssocRefStr = jsonParentAssocs.getString(j); @@ -885,7 +885,7 @@ public List getNodesMetaData(NodeMetaDataParameters params, int ma if(jsonNodeInfo.has("childIds")) { JSONArray jsonChildIds = jsonNodeInfo.getJSONArray("childIds"); - List childIds = new ArrayList(jsonChildIds.length()); + List childIds = new ArrayList<>(jsonChildIds.length()); for(int j = 0; j < jsonChildIds.length(); j++) { Long childId = jsonChildIds.getLong(j); @@ -943,7 +943,7 @@ public GetTextContentResponse getTextContent(Long nodeId, QName propertyName, Lo url.append(args); GetRequest req = new GetRequest(url.toString()); - Map headers = new HashMap(2); + Map headers = new HashMap<>(2); if(modifiedSince != null) { @@ -1043,7 +1043,7 @@ public List getModelsDiff(List currentModels) throw new AlfrescoRuntimeException("GetModelsDiff badly formatted response"); } - List diffs = new ArrayList(jsonDiffs.length()); + List diffs = new ArrayList<>(jsonDiffs.length()); for(int i = 0; i < jsonDiffs.length(); i++) { JSONObject jsonDiff = jsonDiffs.getJSONObject(i); diff --git a/.legacy/Backend/3party-fixes/alfresco-solr-4.0.e-fixes/src/org/alfresco/solr/client/SOLRAPIClient2.java b/.legacy/Backend/3party-fixes/alfresco-solr-4.0.e-fixes/src/org/alfresco/solr/client/SOLRAPIClient2.java index c350a1de3d..09dbd342a6 100644 --- a/.legacy/Backend/3party-fixes/alfresco-solr-4.0.e-fixes/src/org/alfresco/solr/client/SOLRAPIClient2.java +++ b/.legacy/Backend/3party-fixes/alfresco-solr-4.0.e-fixes/src/org/alfresco/solr/client/SOLRAPIClient2.java @@ -170,7 +170,7 @@ public List getAclChangeSets(Long fromCommitTime, Long minAclChang } JSONArray aclChangeSetsJSON = json.getJSONArray("aclChangeSets"); - List aclChangeSets = new ArrayList(aclChangeSetsJSON.length()); + List aclChangeSets = new ArrayList<>(aclChangeSetsJSON.length()); for (int i = 0; i < aclChangeSetsJSON.length(); i++) { JSONObject aclChangeSetJSON = aclChangeSetsJSON.getJSONObject(i); @@ -215,7 +215,7 @@ public List getAcls(List aclChangeSets, Long minAclId, int ma JSONObject jsonReq = new JSONObject(); JSONArray aclChangeSetIdsJSON = new JSONArray(); - List aclChangeSetIds = new ArrayList(); + List aclChangeSetIds = new ArrayList<>(); for (AclChangeSet aclChangeSet : aclChangeSets) { Long aclChangeSetId = aclChangeSet.getId(); @@ -253,7 +253,7 @@ public List getAcls(List aclChangeSets, Long minAclId, int ma } JSONArray aclsJSON = json.getJSONArray("acls"); - List acls = new ArrayList(aclsJSON.length()); + List acls = new ArrayList<>(aclsJSON.length()); for (int i = 0; i < aclsJSON.length(); i++) { JSONObject aclJSON = aclsJSON.getJSONObject(i); @@ -283,7 +283,7 @@ public List getAclReaders(List acls) throws AuthenticationExcep JSONObject jsonReq = new JSONObject(); JSONArray aclIdsJSON = new JSONArray(); - List aclIds = new ArrayList(); + List aclIds = new ArrayList<>(); for (Acl acl : acls) { Long aclId = acl.getId(); @@ -321,13 +321,13 @@ public List getAclReaders(List acls) throws AuthenticationExcep } JSONArray aclsReadersJSON = json.getJSONArray("aclsReaders"); - List aclsReaders = new ArrayList(aclsReadersJSON.length()); + List aclsReaders = new ArrayList<>(aclsReadersJSON.length()); for (int i = 0; i < aclsReadersJSON.length(); i++) { JSONObject aclReadersJSON = aclsReadersJSON.getJSONObject(i); long aclId = aclReadersJSON.getLong("aclId"); JSONArray readersJSON = aclReadersJSON.getJSONArray("readers"); - List readers = new ArrayList(aclReadersJSON.length()); + List readers = new ArrayList<>(aclReadersJSON.length()); for (int j = 0; j < readersJSON.length(); j++) { String readerJSON = readersJSON.getString(j); @@ -404,7 +404,7 @@ public Transactions getTransactions(Long fromCommitTime, Long minTxnId, Long toC JSONArray jsonTransactions = json.getJSONArray("transactions"); int numTxns = jsonTransactions.length(); - List transactions = new ArrayList(numTxns); + List transactions = new ArrayList<>(numTxns); for(int i = 0; i < numTxns; i++) { JSONObject solrTxn = jsonTransactions.getJSONObject(i); @@ -510,7 +510,7 @@ public List getNodes(GetNodesParameters parameters, int maxResults) throws } JSONArray jsonNodes = json.getJSONArray("nodes"); - List nodes = new ArrayList(jsonNodes.length()); + List nodes = new ArrayList<>(jsonNodes.length()); for(int i = 0; i < jsonNodes.length(); i++) { JSONObject jsonNodeInfo = jsonNodes.getJSONObject(i); @@ -568,7 +568,7 @@ else if(dataTypeName.equals(DataTypeDefinition.MLTEXT)) // fix: end JSONArray a = (JSONArray)value; - Map mlValues = new HashMap(a.length()); + Map mlValues = new HashMap<>(a.length()); for(int k = 0; k < a.length(); k++) { @@ -745,7 +745,7 @@ public List getNodesMetaData(NodeMetaDataParameters params, int ma JSONArray jsonNodes = json.getJSONArray("nodes"); - List nodes = new ArrayList(jsonNodes.length()); + List nodes = new ArrayList<>(jsonNodes.length()); for(int i = 0; i < jsonNodes.length(); i++) { JSONObject jsonNodeInfo = jsonNodes.getJSONObject(i); @@ -823,7 +823,7 @@ public List getNodesMetaData(NodeMetaDataParameters params, int ma if(jsonNodeInfo.has("properties")) { JSONObject jsonProperties = jsonNodeInfo.getJSONObject("properties"); - Map properties = new HashMap(jsonProperties.length()); + Map properties = new HashMap<>(jsonProperties.length()); @SuppressWarnings("rawtypes") Iterator propKeysIterator = jsonProperties.keys(); while(propKeysIterator.hasNext()) @@ -853,7 +853,7 @@ public List getNodesMetaData(NodeMetaDataParameters params, int ma if(jsonNodeInfo.has("parentAssocs")) { JSONArray jsonParentAssocs = jsonNodeInfo.getJSONArray("parentAssocs"); - List assocs = new ArrayList(jsonParentAssocs.length()); + List assocs = new ArrayList<>(jsonParentAssocs.length()); for(int j = 0; j < jsonParentAssocs.length(); j++) { String childAssocRefStr = jsonParentAssocs.getString(j); @@ -866,7 +866,7 @@ public List getNodesMetaData(NodeMetaDataParameters params, int ma if(jsonNodeInfo.has("childAssocs")) { JSONArray jsonParentAssocs = jsonNodeInfo.getJSONArray("childAssocs"); - List assocs = new ArrayList(jsonParentAssocs.length()); + List assocs = new ArrayList<>(jsonParentAssocs.length()); for(int j = 0; j < jsonParentAssocs.length(); j++) { String childAssocRefStr = jsonParentAssocs.getString(j); @@ -879,7 +879,7 @@ public List getNodesMetaData(NodeMetaDataParameters params, int ma if(jsonNodeInfo.has("childIds")) { JSONArray jsonChildIds = jsonNodeInfo.getJSONArray("childIds"); - List childIds = new ArrayList(jsonChildIds.length()); + List childIds = new ArrayList<>(jsonChildIds.length()); for(int j = 0; j < jsonChildIds.length(); j++) { Long childId = jsonChildIds.getLong(j); @@ -937,7 +937,7 @@ public GetTextContentResponse getTextContent(Long nodeId, QName propertyName, Lo url.append(args); GetRequest req = new GetRequest(url.toString()); - Map headers = new HashMap(2); + Map headers = new HashMap<>(2); if(modifiedSince != null) { @@ -1037,7 +1037,7 @@ public List getModelsDiff(List currentModels) throw new AlfrescoRuntimeException("GetModelsDiff badly formatted response"); } - List diffs = new ArrayList(jsonDiffs.length()); + List diffs = new ArrayList<>(jsonDiffs.length()); for(int i = 0; i < jsonDiffs.length(); i++) { JSONObject jsonDiff = jsonDiffs.getJSONObject(i); diff --git a/.legacy/Backend/3party-fixes/alfresco-solr4-5.0.d-fix/src/org/alfresco/solr/SolrInformationServer.java b/.legacy/Backend/3party-fixes/alfresco-solr4-5.0.d-fix/src/org/alfresco/solr/SolrInformationServer.java index 01c17e947a..d831eaa699 100644 --- a/.legacy/Backend/3party-fixes/alfresco-solr4-5.0.d-fix/src/org/alfresco/solr/SolrInformationServer.java +++ b/.legacy/Backend/3party-fixes/alfresco-solr4-5.0.d-fix/src/org/alfresco/solr/SolrInformationServer.java @@ -960,7 +960,7 @@ private NamedList fixStats(NamedList namedList) private List getRegisteredSearchers() { - List searchers = new ArrayList(); + List searchers = new ArrayList<>(); for (Entry entry : core.getInfoRegistry().entrySet()) { if (entry.getValue() != null) diff --git a/.legacy/Backend/3party-fixes/solr-1.4.1-fixes/src/org/edu_sharing/solr/ReplicationHandler.java b/.legacy/Backend/3party-fixes/solr-1.4.1-fixes/src/org/edu_sharing/solr/ReplicationHandler.java index 979eb43b77..547709cc97 100644 --- a/.legacy/Backend/3party-fixes/solr-1.4.1-fixes/src/org/edu_sharing/solr/ReplicationHandler.java +++ b/.legacy/Backend/3party-fixes/solr-1.4.1-fixes/src/org/edu_sharing/solr/ReplicationHandler.java @@ -107,7 +107,7 @@ public class ReplicationHandler extends RequestHandlerBase implements SolrCoreAw private int numTimesReplicated = 0; - private final Map confFileInfoCache = new HashMap(); + private final Map confFileInfoCache = new HashMap<>(); private Integer reserveCommitDuration = SnapPuller.readInterval("00:00:10"); @@ -210,7 +210,7 @@ public void run() { private List getCommits() { Map commits = core.getDeletionPolicy().getCommits(); - List l = new ArrayList(); + List l = new ArrayList<>(); for (IndexCommit c : commits.values()) { try { @@ -238,7 +238,7 @@ private void getFileChecksum(SolrParams solrParams, SolrQueryResponse rsp) { } private Map getCheckSums(String[] files, File dir, Checksum checksum) { - Map checksumMap = new HashMap(); + Map checksumMap = new HashMap<>(); if (files == null || files.length == 0) return checksumMap; for (String file : files) { @@ -409,7 +409,7 @@ public FileInfo(long lasmodified, String name, long size, long checksum) { } Map getAsMap() { - Map map = new HashMap(); + Map map = new HashMap<>(); map.put(NAME, name); map.put(SIZE, size); map.put(LAST_MODIFIED, lastmodified); @@ -459,7 +459,7 @@ private long computeIndexSize(File f) { * Collects the details such as name, size ,lastModified of a file */ private Map getFileInfo(File file) { - Map fileMeta = new HashMap(); + Map fileMeta = new HashMap<>(); fileMeta.put(NAME, file.getName()); fileMeta.put(SIZE, file.length()); fileMeta.put(LAST_MODIFIED, file.lastModified()); @@ -631,7 +631,7 @@ private NamedList getReplicationDetails(boolean showSlaveDetails) { if (isReplicating) { try { long bytesToDownload = 0; - List filesToDownload = new ArrayList(); + List filesToDownload = new ArrayList<>(); for (Map file : snapPuller.getFilesToDownload()) { filesToDownload.add((String) file.get(NAME)); bytesToDownload += (Long) file.get(SIZE); @@ -648,7 +648,7 @@ private NamedList getReplicationDetails(boolean showSlaveDetails) { slave.add("bytesToDownload", readableSize(bytesToDownload)); long bytesDownloaded = 0; - List filesDownloaded = new ArrayList(); + List filesDownloaded = new ArrayList<>(); for (Map file : snapPuller.getFilesDownloaded()) { filesDownloaded.add((String) file.get(NAME)); bytesDownloaded += (Long) file.get(SIZE); @@ -730,7 +730,7 @@ private void addVal(NamedList nl, String key, Properties props, Class clzz) { } catch (NumberFormatException e) {/*no op*/ } } else if (clzz == List.class) { String ss[] = s.split(","); - List l = new ArrayList(); + List l = new ArrayList<>(); for (int i = 0; i < ss.length; i++) { l.add(new Date(Long.valueOf(ss[i])).toString()); } @@ -742,7 +742,7 @@ private void addVal(NamedList nl, String key, Properties props, Class clzz) { } private List getReplicateAfterStrings() { - List replicateAfter = new ArrayList(); + List replicateAfter = new ArrayList<>(); if (replicateOnCommit) replicateAfter.add("commit"); if (replicateOnOptimize) diff --git a/.legacy/Backend/3party-fixes/solr-1.4.1-fixes/src/org/edu_sharing/solr/SnapPuller.java b/.legacy/Backend/3party-fixes/solr-1.4.1-fixes/src/org/edu_sharing/solr/SnapPuller.java index 9f906b9edd..0ba69a59ff 100644 --- a/.legacy/Backend/3party-fixes/solr-1.4.1-fixes/src/org/edu_sharing/solr/SnapPuller.java +++ b/.legacy/Backend/3party-fixes/solr-1.4.1-fixes/src/org/edu_sharing/solr/SnapPuller.java @@ -372,7 +372,7 @@ private void terminateAndWaitFsyncService() throws Exception { */ private void logReplicationTimeAndConfFiles(Collection> modifiedConfFiles, boolean successfulInstall) { FileOutputStream outFile = null; - List confFiles = new ArrayList(); + List confFiles = new ArrayList<>(); if (modifiedConfFiles != null && !modifiedConfFiles.isEmpty()) for (Map map1 : modifiedConfFiles) confFiles.add((String) map1.get(NAME)); @@ -446,7 +446,7 @@ static long getTotalBytesDownloaded(SnapPuller snappuller) { private StringBuffer readToStringBuffer(long replicationTime, String str) { StringBuffer sb = new StringBuffer(); - List l = new ArrayList(); + List l = new ArrayList<>(); if (str != null && str.length() != 0) { String[] ss = str.split(","); for (int i = 0; i < ss.length; i++) { @@ -523,7 +523,7 @@ private void downloadConfFiles(List> confFilesToDownload, lo fileFetcher = new FileFetcher(tmpconfDir, file, saveAs, true, latestVersion); currentFile = file; fileFetcher.fetchFile(); - confFilesDownloaded.add(new HashMap(file)); + confFilesDownloaded.add(new HashMap<>(file)); } // this is called before copying the files to the original conf dir // so that if there is an exception avoid corrupting the original files. @@ -548,7 +548,7 @@ private void downloadIndexFiles(boolean downloadCompleteIndex, File tmpIdxDir, l fileFetcher = new FileFetcher(tmpIdxDir, file, (String) file.get(NAME), false, latestVersion); currentFile = file; fileFetcher.fetchFile(); - filesDownloaded.add(new HashMap(file)); + filesDownloaded.add(new HashMap<>(file)); } else { LOG.info("Skipping download for " + localIndexFile); } @@ -603,7 +603,7 @@ private boolean copyAFile(File tmpIdxDir, File indexDir, String fname, List copiedfiles = new ArrayList(); + List copiedfiles = new ArrayList<>(); for (Map f : filesDownloaded) { String fname = (String) f.get(NAME); // the segments file must be copied last @@ -685,7 +685,7 @@ private boolean modifyIndexProps(String tmpIdxDirName) { return true; } - private final Map confFileInfoCache = new HashMap(); + private final Map confFileInfoCache = new HashMap<>(); /** * The local conf files are compared with the conf files in the master. If they are same (by checksum) do not copy. @@ -698,7 +698,7 @@ private Collection> getModifiedConfFiles(List> nameVsFile = new HashMap>(); + Map> nameVsFile = new HashMap<>(); NamedList names = new NamedList(); for (Map map : confFilesToDownload) { //if alias is present that is the name the file may have in the slave @@ -806,7 +806,7 @@ Map getCurrentFile() { FileFetcher tmpFileFetcher = fileFetcher; if (tmp == null) return null; - tmp = new HashMap(tmp); + tmp = new HashMap<>(tmp); if (tmpFileFetcher != null) tmp.put("bytesDownloaded", tmpFileFetcher.bytesDownloaded); return tmp; diff --git a/.legacy/Backend/soap-generation/JavaOrigin/src/org/edu_sharing/webservices/alfresco/extension/NativeAlfrescoWrapper.java b/.legacy/Backend/soap-generation/JavaOrigin/src/org/edu_sharing/webservices/alfresco/extension/NativeAlfrescoWrapper.java index 1c2b986670..a1d1a7a1ed 100644 --- a/.legacy/Backend/soap-generation/JavaOrigin/src/org/edu_sharing/webservices/alfresco/extension/NativeAlfrescoWrapper.java +++ b/.legacy/Backend/soap-generation/JavaOrigin/src/org/edu_sharing/webservices/alfresco/extension/NativeAlfrescoWrapper.java @@ -32,7 +32,7 @@ public java.util.HashMap getChildren(java.lang.String parentID, java.lang.String return null; } - public HashMap> getChildrenCheckPermissions(String parentID, String[] permissionsOnChild){ + public Map> getChildrenCheckPermissions(String parentID, String[] permissionsOnChild){ return null; } @@ -192,11 +192,11 @@ public void createVersion(String nodeId, HashMap properties){ } - public HashMap hasAllPermissions(String nodeId, String[] permissions) { + public Map hasAllPermissions(String nodeId, String[] permissions) { return null; } - public HashMap hasAllPermissionsExt(String storeProtocol, String storeId, String nodeId, + public Map hasAllPermissionsExt(String storeProtocol, String storeId, String nodeId, String[] permissions){ return null; } @@ -268,36 +268,36 @@ public String getRepositoryRoot() { return null; } - public HashMap getChild(String parentId, String type, String property, String value){ + public Map getChild(String parentId, String type, String property, String value){ return null; } - public HashMap> getChildenByProps(String parentId, String type, HashMap props){ + public Map> getChildenByProps(String parentId, String type, HashMap props){ return null; } - public HashMap> getChildrenByType(String nodeId, String type) { + public Map> getChildrenByType(String nodeId, String type) { return null; } - public HashMap> getChildrenByAssociation(String storeString, String nodeId, String association){ + public Map> getChildrenByAssociation(String storeString, String nodeId, String association){ return null; } - public HashMap getParents(String nodeID, boolean primary){ + public Map> getParents(String nodeID, boolean primary){ return null; } - public HashMap getAssocNode(String nodeID, String association) { + public Map> getAssocNode(String nodeID, String association) { return null; } - public HashMap getChildRecursive(String parentId, String type, HashMap props){ + public Map getChildRecursive(String parentId, String type, HashMap props){ return null; } - public HashMap> getChildrenRecursive(String parentId, String type){ + public Map> getChildrenRecursive(String parentId, String type){ return null; } @@ -305,7 +305,7 @@ public String[] getAssociationNodeIds(String nodeID, String association) { return null; } - public HashMap getUserInfo(String userName){ + public Map getUserInfo(String userName){ return null; } diff --git a/Backend/alfresco/common/src/main/java/org/edu_sharing/repository/client/tools/CCConstants.java b/Backend/alfresco/common/src/main/java/org/edu_sharing/repository/client/tools/CCConstants.java index 6246463420..af0a7f7b05 100644 --- a/Backend/alfresco/common/src/main/java/org/edu_sharing/repository/client/tools/CCConstants.java +++ b/Backend/alfresco/common/src/main/java/org/edu_sharing/repository/client/tools/CCConstants.java @@ -1029,9 +1029,9 @@ public enum PROPOSAL_STATUS { public static final String TEMPLATE_NODE_NAME = ".METADATA_TEMPLATE"; - private static HashMap lifecycleContributerPropsMap = new HashMap(); + private static Map lifecycleContributerPropsMap = new HashMap<>(); - public static HashMap getLifecycleContributerPropsMap() { + public static Map getLifecycleContributerPropsMap() { if(lifecycleContributerPropsMap.size() == 0){ lifecycleContributerPropsMap.put("publisher", CCM_PROP_IO_REPL_LIFECYCLECONTRIBUTER_PUBLISHER); lifecycleContributerPropsMap.put("unknown", CCM_PROP_IO_REPL_LIFECYCLECONTRIBUTER_UNKNOWN); @@ -1121,9 +1121,9 @@ public static String getLifecycleContributerProp(String role){ return getLifecycleContributerPropsMap().get(role); } - private static HashMap metadataContributerPropsMap = new HashMap(); + private static Map metadataContributerPropsMap = new HashMap<>(); - public static HashMap getMetadataContributerPropsMap() { + public static Map getMetadataContributerPropsMap() { if(metadataContributerPropsMap.size() == 0){ metadataContributerPropsMap.put("creator", CCM_PROP_IO_REPL_METADATACONTRIBUTER_CREATOR); metadataContributerPropsMap.put("provider", CCM_PROP_IO_REPL_METADATACONTRIBUTER_PROVIDER); @@ -1622,7 +1622,7 @@ public static String getMetadataContributerProp(String role){ public static ArrayList getDetailPropList(){ if(detailsProps == null){ - detailsProps = new ArrayList(); + detailsProps = new ArrayList<>(); detailsProps.add(CM_PROP_C_TITLE); detailsProps.add(CM_PROP_C_CREATOR); detailsProps.add(CM_PROP_C_CREATED); @@ -1936,7 +1936,7 @@ public static List getAllCCLicenseKeys(){ public static Map getLicenseMap(){ if(licenseMap == null) { - licenseMap = new HashMap(); + licenseMap = new HashMap<>(); licenseMap.put(CCConstants.COMMON_LICENSE_CC_BY_SA_LINK.split("\\$")[0],CCConstants.COMMON_LICENSE_CC_BY_SA); licenseMap.put(CCConstants.COMMON_LICENSE_CC_BY_LINK.split("\\$")[0],CCConstants.COMMON_LICENSE_CC_BY); licenseMap.put(CCConstants.COMMON_LICENSE_CC_BY_ND_LINK.split("\\$")[0],CCConstants.COMMON_LICENSE_CC_BY_ND); @@ -2119,14 +2119,14 @@ public static String getSendActivationRequestMailText(String username, String us public static final String CC_CACHE_MILLISECONDS_KEY = "CC_CACHE_MILLISECONDS_KEY"; - private static HashMap nameSpaceMap = null; + private static Map nameSpaceMap = null; /** * @return */ - public static HashMap getNameSpaceMap() { + public static Map getNameSpaceMap() { if(nameSpaceMap == null){ - nameSpaceMap = new HashMap(); + nameSpaceMap = new HashMap<>(); nameSpaceMap.put(NAMESPACE_CCM, NAMESPACE_SHORT_CCM); nameSpaceMap.put(NAMESPACE_CM, NAMESPACE_SHORT_CM); nameSpaceMap.put(NAMESPACE_LOM, NAMESPACE_SHORT_LOM); diff --git a/Backend/alfresco/module/src/main/java/org/alfresco/repo/model/filefolder/EduFileFolderServiceImpl.java b/Backend/alfresco/module/src/main/java/org/alfresco/repo/model/filefolder/EduFileFolderServiceImpl.java index 6e014f0174..6d9e446ecd 100644 --- a/Backend/alfresco/module/src/main/java/org/alfresco/repo/model/filefolder/EduFileFolderServiceImpl.java +++ b/Backend/alfresco/module/src/main/java/org/alfresco/repo/model/filefolder/EduFileFolderServiceImpl.java @@ -263,7 +263,7 @@ public void init() */ private List toFileInfo(List nodeRefs) throws InvalidTypeException { - List results = new ArrayList(nodeRefs.size()); + List results = new ArrayList<>(nodeRefs.size()); for (NodeRef nodeRef : nodeRefs) { try @@ -395,7 +395,7 @@ public List list(NodeRef contextNodeRef) qnameSet.add(QName.createQName(CCConstants.CCM_TYPE_IO)); qnameSet.add(QName.createQName(CCConstants.CCM_TYPE_MAP)); List childRefs = nodeService.getChildAssocs(contextNodeRef,qnameSet); - ArrayList toTransform = new ArrayList(); + ArrayList toTransform = new ArrayList<>(); for(ChildAssociationRef childRef:childRefs){ toTransform.add(childRef.getChildRef()); } @@ -407,7 +407,7 @@ public List list(NodeRef contextNodeRef) // use the helper which is also used by the local node service and filter out special nodes which are also invisible in workspace List toTransform = childRefs.stream(). map((ChildAssociationRef::getChildRef)). - filter((NodeRef ref)->!EduSharingNodeHelper.shouldFilter(ref,new ArrayList(Arrays.asList(new String[] {"edugroup"})))). + filter((NodeRef ref)->!EduSharingNodeHelper.shouldFilter(ref,new ArrayList<>(Arrays.asList(new String[] {"edugroup"})))). collect(Collectors.toList()); results = toFileInfo(toTransform); } @@ -453,7 +453,7 @@ private PagingResults getPagingResults(PagingRequest pagingRequest, fi totalCount = null; } - final List nodeInfos = new ArrayList(nodeRefs.size()); + final List nodeInfos = new ArrayList<>(nodeRefs.size()); for (NodeRef nodeRef : nodeRefs) { nodeInfos.add(toFileInfo(nodeRef, true)); @@ -968,7 +968,7 @@ private List listSimpleDeep(NodeRef contextNodeRef, boolean files, bool } // To hold the results. - List result = new ArrayList(); + List result = new ArrayList<>(); // Build a list of folder types Set folderTypeQNames = buildFolderTypes(); @@ -1330,7 +1330,7 @@ public FileInfo create(NodeRef parentNodeRef, String name, QName typeQName, QNam private FileInfo createImpl(NodeRef parentNodeRef, String name, QName typeQName, QName assocQName) throws FileExistsException { // set up initial properties - Map properties = new HashMap(11); + Map properties = new HashMap<>(11); properties.put(ContentModel.PROP_NAME, (Serializable) name); // Check the type is valid for file/folder service @@ -1454,7 +1454,7 @@ public List getNamePath(NodeRef rootNodeRef, NodeRef nodeRef) throws F } try { - ArrayList results = new ArrayList(10); + ArrayList results = new ArrayList<>(10); // get the primary path Path path = nodeService.getPath(nodeRef); // iterate and turn the results into file info objects @@ -1542,7 +1542,7 @@ public List getNameOnlyPath(NodeRef rootNodeRef, final NodeRef nodeRef) try { final NodeRef rNodeRef = rootNodeRef; - final ArrayList results = new ArrayList(10); + final ArrayList results = new ArrayList<>(10); // Run as system as the user could not have access to all folders in the path, see ALF-13816 AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork() { @@ -1877,4 +1877,4 @@ public PagingResults list(NodeRef contextNodeRef, pagingRequest); } }; -} \ No newline at end of file +} diff --git a/Backend/alfresco/module/src/main/java/org/alfresco/repo/search/impl/solr/SolrJSONResultSet.java b/Backend/alfresco/module/src/main/java/org/alfresco/repo/search/impl/solr/SolrJSONResultSet.java index 422a39b489..fa725b402d 100644 --- a/Backend/alfresco/module/src/main/java/org/alfresco/repo/search/impl/solr/SolrJSONResultSet.java +++ b/Backend/alfresco/module/src/main/java/org/alfresco/repo/search/impl/solr/SolrJSONResultSet.java @@ -92,15 +92,15 @@ public class SolrJSONResultSet implements SearchEngineResultSet { private SimpleResultSetMetaData resultSetMetaData; - private HashMap>> fieldFacets = new HashMap>>(1); + private Map>> fieldFacets = new HashMap<>(1); - private Map facetQueries = new HashMap(); + private Map facetQueries = new HashMap<>(); private Map>>> highlighting = new HashMap<>(); - private Map>> facetIntervals = new HashMap>>(1); + private Map>> facetIntervals = new HashMap<>(1); - private Map>> facetRanges = new HashMap>>(); + private Map>> facetRanges = new HashMap<>(); private List pivotFacets = new ArrayList<>(); @@ -116,41 +116,40 @@ public class SolrJSONResultSet implements SearchEngineResultSet { /** * Detached result set based on that provided - * @param json JSONObject + * + * @param json JSONObject * @param searchParameters SearchParameters - * @param nodeService NodeService - * @param nodeDao NodeDAO - * @param limitBy LimitBy - * @param maxResults int + * @param nodeService NodeService + * @param nodeDao NodeDAO + * @param limitBy LimitBy + * @param maxResults int */ - public SolrJSONResultSet(JSONObject json, SearchParameters searchParameters, NodeService nodeService, NodeDAO nodeDao, LimitBy limitBy, int maxResults) - { + public SolrJSONResultSet(JSONObject json, SearchParameters searchParameters, NodeService nodeService, NodeDAO nodeDao, LimitBy limitBy, int maxResults) { logger.info("edu-sharing version of SolrJSONResultSet"); // Note all properties are returned as multi-valued from the WildcardField "*" definition in the SOLR schema.xml this.nodeService = nodeService; this.nodeDao = nodeDao; - try - { + try { JSONObject responseHeader = json.getJSONObject("responseHeader"); status = responseHeader.getLong("status"); queryTime = responseHeader.getLong("QTime"); - if(json.has("response")) { + if (json.has("response")) { JSONObject response = json.getJSONObject("response"); numberFound = response.getLong("numFound"); start = response.getLong("start"); Double d = response.getDouble("maxScore"); maxScore = d.floatValue(); - }else if(json.has("grouped")){ + } else if (json.has("grouped")) { JSONObject grouped = json.getJSONObject("grouped"); /** * @ToDo only the first group by att is used at the moment */ String groupedByName = (String) grouped.names().get(0); - logger.info("groupedByName:"+groupedByName); + logger.info("groupedByName:" + groupedByName); JSONObject groupedByObj = grouped.getJSONObject(groupedByName); /** @@ -160,29 +159,27 @@ public SolrJSONResultSet(JSONObject json, SearchParameters searchParameters, Nod /** * take from serachParams not response.getLong("start"); */ - start = (long)searchParameters.getSkipCount(); - }else{ + start = (long) searchParameters.getSkipCount(); + } else { logger.error("no response or grouped part found"); } - if (json.has("lastIndexedTx")) - { + if (json.has("lastIndexedTx")) { lastIndexedTxId = json.getLong("lastIndexedTx"); } - if (json.has("processedDenies")) - { + if (json.has("processedDenies")) { processedDenies = json.getBoolean("processedDenies"); } - Map dbIdNodeRefs = null; - if(json.has("response")) { + Map dbIdNodeRefs = null; + if (json.has("response")) { JSONObject response = json.getJSONObject("response"); JSONArray docs = response.getJSONArray("docs"); int numDocs = docs.length(); - ArrayList rawDbids = new ArrayList(numDocs); - ArrayList rawScores = new ArrayList(numDocs); + ArrayList rawDbids = new ArrayList<>(numDocs); + ArrayList rawScores = new ArrayList<>(numDocs); for (int i = 0; i < numDocs; i++) { JSONObject doc = docs.getJSONObject(i); JSONArray dbids = doc.optJSONArray("DBID"); @@ -206,30 +203,27 @@ public SolrJSONResultSet(JSONObject json, SearchParameters searchParameters, Nod } // bulk load - if (searchParameters.isBulkFetchEnabled()) - { + if (searchParameters.isBulkFetchEnabled()) { nodeDao.cacheNodesById(rawDbids); } // filter out rubbish page = new ArrayList>(numDocs); - refs = new ArrayList(numDocs); + refs = new ArrayList<>(numDocs); dbIdNodeRefs = new HashMap<>(numDocs); - for(int i = 0; i < numDocs; i++) - { + for (int i = 0; i < numDocs; i++) { Long dbid = rawDbids.get(i); NodeRef nodeRef = nodeService.getNodeRef(dbid); - if(nodeRef != null) - { + if (nodeRef != null) { page.add(new Pair(dbid, rawScores.get(i))); refs.add(nodeRef); dbIdNodeRefs.put(dbid, nodeRef); } } - }else if(json.has("grouped")){ + } else if (json.has("grouped")) { JSONObject grouped = json.getJSONObject("grouped"); /** @@ -242,11 +236,11 @@ public SolrJSONResultSet(JSONObject json, SearchParameters searchParameters, Nod /** * we expect only one document per group: group.limit=1 */ - ArrayList rawDbids = new ArrayList(groups.length()); - ArrayList rawScores = new ArrayList(groups.length()); + ArrayList rawDbids = new ArrayList<>(groups.length()); + ArrayList rawScores = new ArrayList<>(groups.length()); //this should only be one loop - for(int g = 0; g < groups.length(); g++){ + for (int g = 0; g < groups.length(); g++) { JSONObject group = groups.getJSONObject(g); JSONObject doclist = group.getJSONObject("doclist"); @@ -254,28 +248,21 @@ public SolrJSONResultSet(JSONObject json, SearchParameters searchParameters, Nod int numDocs = docs.length(); - for(int i = 0; i < numDocs; i++) - { + for (int i = 0; i < numDocs; i++) { JSONObject doc = docs.getJSONObject(i); JSONArray dbids = doc.optJSONArray("DBID"); - if(dbids != null) - { + if (dbids != null) { Long dbid = dbids.getLong(0); Float score = Float.valueOf(doc.getString("score")); rawDbids.add(dbid); rawScores.add(score); - } - else - { + } else { Long dbid = doc.optLong("DBID"); - if(dbid != null) - { + if (dbid != null) { Float score = doc.getFloat("score"); rawDbids.add(dbid); rawScores.add(score); - } - else - { + } else { // No DBID found throw new QueryParserException("No DBID found for doc ..."); } @@ -288,24 +275,20 @@ public SolrJSONResultSet(JSONObject json, SearchParameters searchParameters, Nod } - // bulk load - if (searchParameters.isBulkFetchEnabled()) - { + if (searchParameters.isBulkFetchEnabled()) { nodeDao.cacheNodesById(rawDbids); } // filter out rubbish page = new ArrayList>(numGropus); - refs = new ArrayList(numGropus); - for(int i = 0; i < numGropus; i++) - { + refs = new ArrayList<>(numGropus); + for (int i = 0; i < numGropus; i++) { Long dbid = rawDbids.get(i); NodeRef nodeRef = nodeService.getNodeRef(dbid); - if(nodeRef != null) - { + if (nodeRef != null) { page.add(new Pair(dbid, rawScores.get(i))); refs.add(nodeRef); } @@ -313,30 +296,22 @@ public SolrJSONResultSet(JSONObject json, SearchParameters searchParameters, Nod } - //Process hightlight response - if(json.has("highlighting") && json.has("response")) - { + if (json.has("highlighting") && json.has("response")) { JSONObject highObj = (JSONObject) json.getJSONObject("highlighting"); - for(Iterator it = highObj.keys(); it.hasNext(); /**/) - { + for (Iterator it = highObj.keys(); it.hasNext(); /**/) { Long nodeKey = null; String aKey = (String) it.next(); JSONObject high = highObj.getJSONObject(aKey); - List< Pair> > highFields = new ArrayList<>(high.length()); - for(Iterator hit = high.keys(); hit.hasNext(); /**/) - { + List>> highFields = new ArrayList<>(high.length()); + for (Iterator hit = high.keys(); hit.hasNext(); /**/) { String highKey = (String) hit.next(); - if ("DBID".equals(highKey)) - { + if ("DBID".equals(highKey)) { nodeKey = high.getLong("DBID"); - } - else - { + } else { JSONArray highVal = high.getJSONArray(highKey); List highValues = new ArrayList<>(highVal.length()); - for (int i = 0, length = highVal.length(); i < length; i++) - { + for (int i = 0, length = highVal.length(); i < length; i++) { highValues.add(highVal.getString(i)); } Pair> highPair = new Pair>(highKey, highValues); @@ -344,101 +319,82 @@ public SolrJSONResultSet(JSONObject json, SearchParameters searchParameters, Nod } } NodeRef nodefRef = dbIdNodeRefs.get(nodeKey); - if (nodefRef != null && !highFields.isEmpty()) - { + if (nodefRef != null && !highFields.isEmpty()) { highlighting.put(nodefRef, highFields); } } } - if(json.has("facet_counts")) - { + if (json.has("facet_counts")) { JSONObject facet_counts = json.getJSONObject("facet_counts"); - if(facet_counts.has("facet_queries")) - { + if (facet_counts.has("facet_queries")) { JSONObject facet_queries = facet_counts.getJSONObject("facet_queries"); - for(Iterator it = facet_queries.keys(); it.hasNext(); /**/) - { + for (Iterator it = facet_queries.keys(); it.hasNext(); /**/) { String fq = (String) it.next(); - Integer count =Integer.valueOf(facet_queries.getInt(fq)); + Integer count = Integer.valueOf(facet_queries.getInt(fq)); facetQueries.put(fq, count); } } - if(facet_counts.has("facet_fields")) - { + if (facet_counts.has("facet_fields")) { JSONObject facet_fields = facet_counts.getJSONObject("facet_fields"); - for(Iterator it = facet_fields.keys(); it.hasNext(); /**/) - { - String fieldName = (String)it.next(); + for (Iterator it = facet_fields.keys(); it.hasNext(); /**/) { + String fieldName = (String) it.next(); JSONArray facets = facet_fields.getJSONArray(fieldName); int facetArraySize = facets.length(); - ArrayList> facetValues = new ArrayList>(facetArraySize/2); - for(int i = 0; i < facetArraySize; i+=2) - { + ArrayList> facetValues = new ArrayList>(facetArraySize / 2); + for (int i = 0; i < facetArraySize; i += 2) { String facetEntryName = facets.getString(i); - Integer facetEntryCount = Integer.valueOf(facets.getInt(i+1)); + Integer facetEntryCount = Integer.valueOf(facets.getInt(i + 1)); Pair pair = new Pair(facetEntryName, facetEntryCount); facetValues.add(pair); } fieldFacets.put(fieldName, facetValues); } } - if(facet_counts.has("facet_intervals")) - { + if (facet_counts.has("facet_intervals")) { JSONObject facet_intervals = facet_counts.getJSONObject("facet_intervals"); - for(Iterator it = facet_intervals.keys(); it.hasNext(); /**/) - { - String fieldName = (String)it.next(); + for (Iterator it = facet_intervals.keys(); it.hasNext(); /**/) { + String fieldName = (String) it.next(); JSONObject intervals = facet_intervals.getJSONObject(fieldName); ArrayList> intervalValues = new ArrayList>(intervals.length()); - for(Iterator itk = intervals.keys(); itk.hasNext(); /**/) - { + for (Iterator itk = intervals.keys(); itk.hasNext(); /**/) { String key = (String) itk.next(); Integer count = Integer.valueOf(intervals.getInt(key)); intervalValues.add(new Pair(key, count)); } - facetIntervals.put(fieldName,intervalValues); + facetIntervals.put(fieldName, intervalValues); } } - if(facet_counts.has("facet_pivot")) - { + if (facet_counts.has("facet_pivot")) { JSONObject facet_pivot = facet_counts.getJSONObject("facet_pivot"); - for(Iterator it = facet_pivot.keys(); it.hasNext(); /**/) - { - String pivotName = (String)it.next(); + for (Iterator it = facet_pivot.keys(); it.hasNext(); /**/) { + String pivotName = (String) it.next(); pivotFacets.addAll(buildPivot(facet_pivot, pivotName, searchParameters.getRanges())); } } - if(facet_counts.has("facet_ranges")) - { + if (facet_counts.has("facet_ranges")) { JSONObject facet_ranges = facet_counts.getJSONObject("facet_ranges"); - for(Iterator it = facet_ranges.keys(); it.hasNext();) - { + for (Iterator it = facet_ranges.keys(); it.hasNext(); ) { String fieldName = (String) it.next(); String end = ""; - try - { + try { end = facet_ranges.getJSONObject(fieldName).getString("end"); - } - catch(JSONException e) - { + } catch (JSONException e) { end = String.valueOf(facet_ranges.getJSONObject(fieldName).getInt("end")); } JSONArray rangeCollection = facet_ranges.getJSONObject(fieldName).getJSONArray("counts"); List> buckets = new ArrayList>(); - for(int i = 0; i < rangeCollection.length(); i += 2) - { - String position = i == 0 ? "head":"body"; - if( i+2 == rangeCollection.length()) - { + for (int i = 0; i < rangeCollection.length(); i += 2) { + String position = i == 0 ? "head" : "body"; + if (i + 2 == rangeCollection.length()) { position = "tail"; } - Map rangeMap = new HashMap(3); + Map rangeMap = new HashMap<>(3); String rangeFrom = rangeCollection.getString(i); - String facetRangeCount = String.valueOf(rangeCollection.getInt(i+1)); - String rangeTo = (i+2 < rangeCollection.length() ? rangeCollection.getString(i+2):end); + String facetRangeCount = String.valueOf(rangeCollection.getInt(i + 1)); + String rangeTo = (i + 2 < rangeCollection.length() ? rangeCollection.getString(i + 2) : end); String label = rangeFrom + " - " + rangeTo; rangeMap.put(GenericFacetResponse.LABEL, label); rangeMap.put(GenericFacetResponse.COUNT, facetRangeCount); @@ -456,8 +412,7 @@ public SolrJSONResultSet(JSONObject json, SearchParameters searchParameters, Nod } } - if(json.has("stats")) - { + if (json.has("stats")) { JSONObject statsObj = json.getJSONObject("stats"); Map> builtStats = buildStats(statsObj); builtStats.forEach((pKey, pVal) -> { @@ -467,38 +422,29 @@ public SolrJSONResultSet(JSONObject json, SearchParameters searchParameters, Nod // process Spell check JSONObject spellCheckJson = (JSONObject) json.opt("spellcheck"); - if (spellCheckJson != null) - { + if (spellCheckJson != null) { List list = new ArrayList<>(3); String flag = ""; boolean searchedFor = false; - if (spellCheckJson.has("searchInsteadFor")) - { + if (spellCheckJson.has("searchInsteadFor")) { flag = "searchInsteadFor"; searchedFor = true; list.add(spellCheckJson.getString(flag)); - } - else if (spellCheckJson.has("didYouMean")) - { + } else if (spellCheckJson.has("didYouMean")) { flag = "didYouMean"; JSONArray suggestions = spellCheckJson.getJSONArray(flag); - for (int i = 0, lenght = suggestions.length(); i < lenght; i++) - { + for (int i = 0, lenght = suggestions.length(); i < lenght; i++) { list.add(suggestions.getString(i)); } } spellCheckResult = new SpellCheckResult(flag, list, searchedFor); - } - else - { + } else { spellCheckResult = new SpellCheckResult(null, null, false); } - } - catch (JSONException e) - { + } catch (JSONException e) { logger.info(e.getMessage()); } // We'll say we were unlimited if we got a number less than the limit @@ -507,35 +453,28 @@ else if (spellCheckJson.has("didYouMean")) PermissionEvaluationMode.EAGER, searchParameters); } - protected Map>> buildRanges(JSONObject facet_ranges) throws JSONException - { - Map>> ranges = new HashMap<>(); + protected Map>> buildRanges(JSONObject facet_ranges) throws JSONException { + Map>> ranges = new HashMap<>(); - for(Iterator it = facet_ranges.keys(); it.hasNext();) - { + for (Iterator it = facet_ranges.keys(); it.hasNext(); ) { String fieldName = (String) it.next(); String end = ""; - try - { + try { end = facet_ranges.getJSONObject(fieldName).getString("end"); - } - catch(JSONException e) - { + } catch (JSONException e) { end = String.valueOf(facet_ranges.getJSONObject(fieldName).getInt("end")); } JSONArray rangeCollection = facet_ranges.getJSONObject(fieldName).getJSONArray("counts"); List> buckets = new ArrayList>(); - for(int i = 0; i < rangeCollection.length(); i+=2) - { - String position = i == 0 ? "head":"body"; - if( i+2 == rangeCollection.length()) - { + for (int i = 0; i < rangeCollection.length(); i += 2) { + String position = i == 0 ? "head" : "body"; + if (i + 2 == rangeCollection.length()) { position = "tail"; } - Map rangeMap = new HashMap(3); + Map rangeMap = new HashMap<>(3); String rangeFrom = rangeCollection.getString(i); - int facetRangeCount = rangeCollection.getInt(i+1); - String rangeTo = (i+2 < rangeCollection.length() ? rangeCollection.getString(i+2):end); + int facetRangeCount = rangeCollection.getInt(i + 1); + String rangeTo = (i + 2 < rangeCollection.length() ? rangeCollection.getString(i + 2) : end); String label = rangeFrom + " - " + rangeTo; rangeMap.put(GenericFacetResponse.LABEL, label); rangeMap.put(GenericFacetResponse.COUNT, String.valueOf(facetRangeCount)); @@ -550,19 +489,15 @@ protected Map>> buildRanges(JSONObject facet_rang return ranges; } - protected Map> buildStats(JSONObject statsObj) throws JSONException - { - if(statsObj.has("stats_fields")) - { + protected Map> buildStats(JSONObject statsObj) throws JSONException { + if (statsObj.has("stats_fields")) { Map> statsMap = new HashMap<>(); JSONObject statsFields = statsObj.getJSONObject("stats_fields"); - for(Iterator itk = statsFields.keys(); itk.hasNext(); /**/) - { + for (Iterator itk = statsFields.keys(); itk.hasNext(); /**/) { String fieldName = (String) itk.next(); JSONObject theStats = statsFields.getJSONObject(fieldName); Map fieldStats = new HashMap<>(statsFields.length()); - for(Iterator it = theStats.keys(); it.hasNext(); /**/) - { + for (Iterator it = theStats.keys(); it.hasNext(); /**/) { String key = (String) it.next(); Object val = theStats.get(key); if ("count".equals(key)) key = METRIC_TYPE.countValues.toString(); @@ -575,22 +510,19 @@ protected Map> buildStats(JSONObject statsObj) throw return Collections.emptyMap(); } - protected List buildPivot(JSONObject facet_pivot, String pivotName, List rangeParameters) throws JSONException - { + protected List buildPivot(JSONObject facet_pivot, String pivotName, List rangeParameters) throws JSONException { if (!facet_pivot.has(pivotName)) return Collections.emptyList(); JSONArray pivots = facet_pivot.getJSONArray(pivotName); - Map> pivotBuckets = new HashMap<>(pivots.length()); + Map> pivotBuckets = new HashMap<>(pivots.length()); List facetResponses = new ArrayList<>(); - for(int i = 0; i < pivots.length(); i++) - { + for (int i = 0; i < pivots.length(); i++) { JSONObject piv = pivots.getJSONObject(i); Set metrics = new HashSet<>(1); List nested = new ArrayList<>(); String field = piv.getString("field"); String value = piv.getString("value"); - if (piv.has("stats")) - { + if (piv.has("stats")) { JSONObject stats = piv.getJSONObject("stats"); Map> pivotStats = buildStats(stats); pivotStats.forEach((pKey, pVal) -> { @@ -599,25 +531,24 @@ protected List buildPivot(JSONObject facet_pivot, String p } Integer count = Integer.valueOf(piv.getInt("count")); - metrics.add(new SimpleMetric(METRIC_TYPE.count,count)); + metrics.add(new SimpleMetric(METRIC_TYPE.count, count)); nested.addAll(buildPivot(piv, "pivot", rangeParameters)); - if (piv.has("ranges")) - { + if (piv.has("ranges")) { JSONObject ranges = piv.getJSONObject("ranges"); Map>> builtRanges = buildRanges(ranges); - List rangefacets = RangeResultMapper.getGenericFacetsForRanges(builtRanges,rangeParameters); + List rangefacets = RangeResultMapper.getGenericFacetsForRanges(builtRanges, rangeParameters); nested.addAll(rangefacets); } - GenericBucket buck = new GenericBucket(value, field+":\""+value+"\"", null, metrics, nested); - List listBucks = pivotBuckets.containsKey(field)?pivotBuckets.get(field):new ArrayList<>(); + GenericBucket buck = new GenericBucket(value, field + ":\"" + value + "\"", null, metrics, nested); + List listBucks = pivotBuckets.containsKey(field) ? pivotBuckets.get(field) : new ArrayList<>(); listBucks.add(buck); pivotBuckets.put(field, listBucks); } for (Map.Entry> entry : pivotBuckets.entrySet()) { - facetResponses.add(new GenericFacetResponse(FACET_TYPE.pivot,entry.getKey(),entry.getValue())); + facetResponses.add(new GenericFacetResponse(FACET_TYPE.pivot, entry.getKey(), entry.getValue())); } if (!facetResponses.isEmpty()) return facetResponses; @@ -625,17 +556,14 @@ protected List buildPivot(JSONObject facet_pivot, String p return Collections.emptyList(); } - protected Set getMetrics(Map metrics) - { - if(metrics != null && !metrics.isEmpty()) - { + protected Set getMetrics(Map metrics) { + if (metrics != null && !metrics.isEmpty()) { return metrics.entrySet().stream().map(aStat -> { METRIC_TYPE metricType = METRIC_TYPE.valueOf(aStat.getKey()); Object val = aStat.getValue(); if (JSONObject.NULL.equals(val)) return null; - switch (metricType) - { + switch (metricType) { case distinctValues: return new ListMetric(metricType, val); case percentiles: @@ -652,8 +580,7 @@ protected Set getMetrics(Map metrics) return Collections.emptySet(); } - public NodeService getNodeService() - { + public NodeService getNodeService() { return nodeService; } @@ -663,8 +590,7 @@ public NodeService getNodeService() * @see org.alfresco.service.cmr.search.ResultSetSPI#close() */ @Override - public void close() - { + public void close() { // NO OP } @@ -673,8 +599,7 @@ public void close() * @see org.alfresco.service.cmr.search.ResultSetSPI#getBulkFetch() */ @Override - public boolean getBulkFetch() - { + public boolean getBulkFetch() { return true; } @@ -683,8 +608,7 @@ public boolean getBulkFetch() * @see org.alfresco.service.cmr.search.ResultSetSPI#getBulkFetchSize() */ @Override - public int getBulkFetchSize() - { + public int getBulkFetchSize() { return Integer.MAX_VALUE; } @@ -693,15 +617,11 @@ public int getBulkFetchSize() * @see org.alfresco.service.cmr.search.ResultSetSPI#getChildAssocRef(int) */ @Override - public ChildAssociationRef getChildAssocRef(int n) - { + public ChildAssociationRef getChildAssocRef(int n) { ChildAssociationRef primaryParentAssoc = nodeService.getPrimaryParent(getNodeRef(n)); - if(primaryParentAssoc != null) - { + if (primaryParentAssoc != null) { return primaryParentAssoc; - } - else - { + } else { return null; } } @@ -711,12 +631,10 @@ public ChildAssociationRef getChildAssocRef(int n) * @see org.alfresco.service.cmr.search.ResultSetSPI#getChildAssocRefs() */ @Override - public List getChildAssocRefs() - { - ArrayList refs = new ArrayList(page.size()); - for(int i = 0; i < page.size(); i++ ) - { - refs.add( getChildAssocRef(i)); + public List getChildAssocRefs() { + ArrayList refs = new ArrayList<>(page.size()); + for (int i = 0; i < page.size(); i++) { + refs.add(getChildAssocRef(i)); } return refs; } @@ -726,8 +644,7 @@ public List getChildAssocRefs() * @see org.alfresco.service.cmr.search.ResultSetSPI#getNodeRef(int) */ @Override - public NodeRef getNodeRef(int n) - { + public NodeRef getNodeRef(int n) { return refs.get(n); } @@ -736,8 +653,7 @@ public NodeRef getNodeRef(int n) * @see org.alfresco.service.cmr.search.ResultSetSPI#getNodeRefs() */ @Override - public List getNodeRefs() - { + public List getNodeRefs() { return Collections.unmodifiableList(refs); } @@ -746,8 +662,7 @@ public List getNodeRefs() * @see org.alfresco.service.cmr.search.ResultSetSPI#getResultSetMetaData() */ @Override - public ResultSetMetaData getResultSetMetaData() - { + public ResultSetMetaData getResultSetMetaData() { return resultSetMetaData; } @@ -756,8 +671,7 @@ public ResultSetMetaData getResultSetMetaData() * @see org.alfresco.service.cmr.search.ResultSetSPI#getRow(int) */ @Override - public ResultSetRow getRow(int i) - { + public ResultSetRow getRow(int i) { return new SolrJSONResultSetRow(this, i); } @@ -766,8 +680,7 @@ public ResultSetRow getRow(int i) * @see org.alfresco.service.cmr.search.ResultSetSPI#getScore(int) */ @Override - public float getScore(int n) - { + public float getScore(int n) { return page.get(n).getSecond(); } @@ -776,8 +689,7 @@ public float getScore(int n) * @see org.alfresco.service.cmr.search.ResultSetSPI#getStart() */ @Override - public int getStart() - { + public int getStart() { return start.intValue(); } @@ -786,8 +698,7 @@ public int getStart() * @see org.alfresco.service.cmr.search.ResultSetSPI#hasMore() */ @Override - public boolean hasMore() - { + public boolean hasMore() { return numberFound.longValue() > (start.longValue() + page.size()); } @@ -796,8 +707,7 @@ public boolean hasMore() * @see org.alfresco.service.cmr.search.ResultSetSPI#length() */ @Override - public int length() - { + public int length() { return page.size(); } @@ -806,8 +716,7 @@ public int length() * @see org.alfresco.service.cmr.search.ResultSetSPI#setBulkFetch(boolean) */ @Override - public boolean setBulkFetch(boolean bulkFetch) - { + public boolean setBulkFetch(boolean bulkFetch) { return bulkFetch; } @@ -816,8 +725,7 @@ public boolean setBulkFetch(boolean bulkFetch) * @see org.alfresco.service.cmr.search.ResultSetSPI#setBulkFetchSize(int) */ @Override - public int setBulkFetchSize(int bulkFetchSize) - { + public int setBulkFetchSize(int bulkFetchSize) { return bulkFetchSize; } @@ -826,8 +734,7 @@ public int setBulkFetchSize(int bulkFetchSize) * @see java.lang.Iterable#iterator() */ @Override - public Iterator iterator() - { + public Iterator iterator() { return new SolrJSONResultSetRowIterator(this); } @@ -836,8 +743,7 @@ public Iterator iterator() * @return the queryTime */ @Override - public Long getQueryTime() - { + public Long getQueryTime() { return queryTime; } @@ -846,83 +752,68 @@ public Long getQueryTime() * @return the numberFound */ @Override - public long getNumberFound() - { + public long getNumberFound() { return numberFound.longValue(); } @Override - public List> getFieldFacet(String field) - { + public List> getFieldFacet(String field) { List> answer = fieldFacets.get(field); - if(answer != null) - { + if (answer != null) { return answer; - } - else - { + } else { return Collections.>emptyList(); } } @Override - public Map>> getFieldFacets() - { + public Map>> getFieldFacets() { return Collections.unmodifiableMap(fieldFacets); } @Override - public Map>> getFacetIntervals() - { + public Map>> getFacetIntervals() { return Collections.unmodifiableMap(facetIntervals); } @Override - public List getPivotFacets() - { + public List getPivotFacets() { return pivotFacets; } @Override - public Map> getStats() - { + public Map> getStats() { return Collections.unmodifiableMap(stats); } @Override - public long getLastIndexedTxId() - { + public long getLastIndexedTxId() { return lastIndexedTxId; } @Override - public Map getFacetQueries() - { + public Map getFacetQueries() { return Collections.unmodifiableMap(facetQueries); } @Override - public Map>>> getHighlighting() - { + public Map>>> getHighlighting() { return Collections.unmodifiableMap(highlighting); } @Override - public SpellCheckResult getSpellCheckResult() - { + public SpellCheckResult getSpellCheckResult() { return this.spellCheckResult; } @Override - public boolean getProcessedDenies() - { + public boolean getProcessedDenies() { return processedDenies; } @Override - public Map>> getFacetRanges() - { + public Map>> getFacetRanges() { return facetRanges; } -} \ No newline at end of file +} diff --git a/Backend/alfresco/module/src/main/java/org/alfresco/repo/search/impl/solr/SolrQueryHTTPClient.java b/Backend/alfresco/module/src/main/java/org/alfresco/repo/search/impl/solr/SolrQueryHTTPClient.java index 6d5f8b5204..869ccb590c 100644 --- a/Backend/alfresco/module/src/main/java/org/alfresco/repo/search/impl/solr/SolrQueryHTTPClient.java +++ b/Backend/alfresco/module/src/main/java/org/alfresco/repo/search/impl/solr/SolrQueryHTTPClient.java @@ -122,7 +122,7 @@ public class SolrQueryHTTPClient extends AbstractSolrQueryHTTPClient implements private List storeMappings; - private HashMap mappingLookup = new HashMap(); + private Map mappingLookup = new HashMap<>(); private String alternativeDictionary = CMISStrictDictionaryService.DEFAULT; @@ -292,7 +292,7 @@ public SolrStatsResult executeStatsQuery(final StatsParameters searchParameters) StoreRef store = SolrClientUtil.extractStoreRef(searchParameters); SolrStoreMappingWrapper mapping = SolrClientUtil.extractMapping(store, - mappingLookup, + (HashMap) mappingLookup, shardRegistry, useDynamicShardRegistration, beanFactory); @@ -372,7 +372,8 @@ protected void buildShards(StringBuilder url, List storeRefs) boolean requiresSeparator = false; for(StoreRef storeRef : storeRefs) { - SolrStoreMappingWrapper storeMapping = SolrClientUtil.extractMapping(storeRef, mappingLookup, shardRegistry, useDynamicShardRegistration, beanFactory); + SolrStoreMappingWrapper storeMapping = SolrClientUtil.extractMapping(storeRef, (HashMap) mappingLookup, shardRegistry, useDynamicShardRegistration, beanFactory); + if(requiresSeparator) { @@ -414,7 +415,7 @@ public ResultSet executeQuery(final SearchParameters searchParameters, String la { StoreRef store = SolrClientUtil.extractStoreRef(searchParameters); SolrStoreMappingWrapper mapping = SolrClientUtil.extractMapping(store, - mappingLookup, + (HashMap) mappingLookup, shardRegistry, useDynamicShardRegistration, beanFactory); @@ -471,7 +472,7 @@ else if(searchParameters.getLimitBy() == LimitBy.FINAL_SIZE && searchParameters. { SolrStoreMappingWrapper storeMapping = SolrClientUtil.extractMapping(storeRef, - mappingLookup, shardRegistry, + (HashMap) mappingLookup, shardRegistry, useDynamicShardRegistration, beanFactory); if(requiresSeparator) @@ -1230,11 +1231,11 @@ public void afterPropertiesSet() throws Exception * @param params * @return */ - public JSONObject execute(StoreRef storeRef, String handler, HashMap params) + public JSONObject execute(StoreRef storeRef, String handler, Map params) { try { - SolrStoreMappingWrapper mapping = SolrClientUtil.extractMapping(storeRef, mappingLookup, shardRegistry, useDynamicShardRegistration, beanFactory); + SolrStoreMappingWrapper mapping = SolrClientUtil.extractMapping(storeRef, (HashMap) mappingLookup, shardRegistry, useDynamicShardRegistration, beanFactory); URLCodec encoder = new URLCodec(); StringBuilder url = new StringBuilder(); diff --git a/Backend/alfresco/module/src/main/java/org/alfresco/repo/version/EduVersion2ServiceImpl.java b/Backend/alfresco/module/src/main/java/org/alfresco/repo/version/EduVersion2ServiceImpl.java index 6dde39166f..82484191ec 100644 --- a/Backend/alfresco/module/src/main/java/org/alfresco/repo/version/EduVersion2ServiceImpl.java +++ b/Backend/alfresco/module/src/main/java/org/alfresco/repo/version/EduVersion2ServiceImpl.java @@ -124,7 +124,7 @@ public void revert(NodeRef nodeRef, Version version, boolean deep) if (needToRestoreDiscussion) { Map currentVersionProp = this.nodeService.getProperties(nodeRef); - forumProps = new HashMap(); + forumProps = new HashMap<>(); for (QName key : currentVersionProp.keySet()) { if (key.getNamespaceURI().equals(NamespaceService.FORUMS_MODEL_1_0_URI)) @@ -144,8 +144,8 @@ public void revert(NodeRef nodeRef, Version version, boolean deep) revertDetails.setNodeType(oldNodeTypeQName); // Do we want to maintain any existing property values? - Collection propsToLeaveAlone = new ArrayList(); - Collection assocsToLeaveAlone = new ArrayList(); + Collection propsToLeaveAlone = new ArrayList<>(); + Collection assocsToLeaveAlone = new ArrayList<>(); TypeDefinition typeDef = dictionaryService.getType(oldNodeTypeQName); if(typeDef != null) @@ -276,7 +276,7 @@ public void revert(NodeRef nodeRef, Version version, boolean deep) this.nodeService.setProperty(nodeRef, ContentModel.PROP_VERSION_LABEL, currentVersionLabel); // Add/remove the child nodes - List children = new ArrayList(this.nodeService.getChildAssocs(nodeRef)); + List children = new ArrayList<>(this.nodeService.getChildAssocs(nodeRef)); List versionedChildren = this.nodeService.getChildAssocs(versionNodeRef); for (ChildAssociationRef versionedChild : versionedChildren) { @@ -354,7 +354,7 @@ public void revert(NodeRef nodeRef, Version version, boolean deep) // Don't remove forum children if (needToRestoreDiscussion) { - List ignoredChildren = new ArrayList(); + List ignoredChildren = new ArrayList<>(); for (ChildAssociationRef childForCheck : children) { if (childForCheck.getTypeQName().getNamespaceURI().equals(NamespaceService.FORUMS_MODEL_1_0_URI)) diff --git a/Backend/alfresco/module/src/main/java/org/alfresco/repo/web/scripts/solr/NodesMetaDataGet.java b/Backend/alfresco/module/src/main/java/org/alfresco/repo/web/scripts/solr/NodesMetaDataGet.java index 7b7cb087fe..4858b8d1bf 100644 --- a/Backend/alfresco/module/src/main/java/org/alfresco/repo/web/scripts/solr/NodesMetaDataGet.java +++ b/Backend/alfresco/module/src/main/java/org/alfresco/repo/web/scripts/solr/NodesMetaDataGet.java @@ -104,7 +104,7 @@ protected Map executeImpl(WebScriptRequest req, Status status) if(o.has("nodeIds")) { JSONArray jsonNodeIds = o.getJSONArray("nodeIds"); - nodeIds = new ArrayList(jsonNodeIds.length()); + nodeIds = new ArrayList<>(jsonNodeIds.length()); for(int i = 0; i < jsonNodeIds.length(); i++) { Long nodeId = jsonNodeIds.getLong(i); @@ -187,7 +187,7 @@ else if(fromNodeId != null && toNodeId != null) } final ArrayList nodesMetaData = - new ArrayList(size > 0 ? size : INITIAL_DEFAULT_SIZE); + new ArrayList<>(size > 0 ? size : INITIAL_DEFAULT_SIZE); NodeMetaDataParameters params = new NodeMetaDataParameters(); params.setNodeIds(nodeIds); params.setFromNodeId(fromNodeId); @@ -224,7 +224,7 @@ public boolean handleNodeMetaData(NodeMetaData nodeMetaData) } }); - Map model = new HashMap(1, 1.0f); + Map model = new HashMap<>(1, 1.0f); model.put("nodes", nodesMetaData); model.put("filter", filter); @@ -282,8 +282,8 @@ public FreemarkerNodeMetaData(final SOLRSerializer solrSerializer, final NodeMet this.childAssocs = new ArrayList<>(); // convert Paths to Strings - List paths = new ArrayList(); - List ancestorPaths = new ArrayList(); + List paths = new ArrayList<>(); + List ancestorPaths = new ArrayList<>(); HashSet ancestors = new HashSet(); if(nodeMetaData.getPaths() != null) { @@ -310,7 +310,7 @@ public FreemarkerNodeMetaData(final SOLRSerializer solrSerializer, final NodeMet // convert name Paths to Strings - List namePaths = new ArrayList(); + List namePaths = new ArrayList<>(); if(nodeMetaData.getNamePaths() != null) { for(Collection namePath : nodeMetaData.getNamePaths()) @@ -352,7 +352,7 @@ public FreemarkerNodeMetaData(final SOLRSerializer solrSerializer, final NodeMet final Map props = nodeMetaData.getProperties(); if (props != null) { - final Map properties = new HashMap(props.size()); + final Map properties = new HashMap<>(props.size()); for (final QName propName : props.keySet()) { // need to run this in tenant context because types may be in a tenant-specific @@ -443,7 +443,7 @@ public String getTenantDomain() } private ArrayList getAncestors(Path path) { - ArrayList ancestors = new ArrayList(8); + ArrayList ancestors = new ArrayList<>(8); for (Iterator elit = path.iterator(); elit.hasNext(); /**/) { Path.Element element = elit.next(); diff --git a/Backend/alfresco/module/src/main/java/org/edu_sharing/alfresco/HasPermissionsWork.java b/Backend/alfresco/module/src/main/java/org/edu_sharing/alfresco/HasPermissionsWork.java index 7c85bb72ed..b22856d354 100644 --- a/Backend/alfresco/module/src/main/java/org/edu_sharing/alfresco/HasPermissionsWork.java +++ b/Backend/alfresco/module/src/main/java/org/edu_sharing/alfresco/HasPermissionsWork.java @@ -28,6 +28,7 @@ package org.edu_sharing.alfresco; import java.util.HashMap; +import java.util.Map; import org.alfresco.repo.security.authentication.AuthenticationUtil; import org.alfresco.service.cmr.repository.NodeRef; @@ -37,7 +38,7 @@ import org.apache.log4j.Logger; -public class HasPermissionsWork implements AuthenticationUtil.RunAsWork>{ +public class HasPermissionsWork implements AuthenticationUtil.RunAsWork>{ Logger logger = Logger.getLogger( HasPermissionsWork.class); String userId = null; @@ -55,8 +56,8 @@ public HasPermissionsWork(PermissionService _permissionService, String _userId, permissionService = _permissionService; } @Override - public java.util.HashMap doWork() throws Exception { - HashMap result = new HashMap(); + public Map doWork() throws Exception { + Map result = new HashMap<>(); for(String permission:permissions){ logger.debug("NEWnodeId:"+nodeId); diff --git a/Backend/alfresco/module/src/main/java/org/edu_sharing/alfresco/StoreArchiveMap.java b/Backend/alfresco/module/src/main/java/org/edu_sharing/alfresco/StoreArchiveMap.java index c282f79869..e34b4527e1 100644 --- a/Backend/alfresco/module/src/main/java/org/edu_sharing/alfresco/StoreArchiveMap.java +++ b/Backend/alfresco/module/src/main/java/org/edu_sharing/alfresco/StoreArchiveMap.java @@ -72,7 +72,7 @@ public class StoreArchiveMap extends org.alfresco.repo.node.StoreArchiveMap{ public StoreArchiveMap() { - storeArchiveMap = new HashMap(0); + storeArchiveMap = new HashMap<>(0); logger.info("archiving of Nodes is disabled by this class"); } diff --git a/Backend/alfresco/module/src/main/java/org/edu_sharing/alfresco/action/RessourceInfoExecuter.java b/Backend/alfresco/module/src/main/java/org/edu_sharing/alfresco/action/RessourceInfoExecuter.java index 988f094f36..f729d25c64 100644 --- a/Backend/alfresco/module/src/main/java/org/edu_sharing/alfresco/action/RessourceInfoExecuter.java +++ b/Backend/alfresco/module/src/main/java/org/edu_sharing/alfresco/action/RessourceInfoExecuter.java @@ -289,7 +289,7 @@ private void process(InputStream is, ContentReader contentreader, NodeRef action nodeService.setProperty(actionedUponNodeRef, QName.createQName(CCM_PROP_IO_RESSOURCEVERSION), ressourceVersion); if (isQtiList.size() > 0) { - ArrayList qtiInfoSubtypeList = new ArrayList(); + ArrayList qtiInfoSubtypeList = new ArrayList<>(); for (RessourceInfoTool.QTIInfo qtiInfo : isQtiList) { String subtype = qtiInfo.getSubtype(); if (subtype != null && !subtype.trim().equals("") diff --git a/Backend/alfresco/module/src/main/java/org/edu_sharing/alfresco/action/RessourceInfoTool.java b/Backend/alfresco/module/src/main/java/org/edu_sharing/alfresco/action/RessourceInfoTool.java index ea5f128c9f..e970ddd7e4 100644 --- a/Backend/alfresco/module/src/main/java/org/edu_sharing/alfresco/action/RessourceInfoTool.java +++ b/Backend/alfresco/module/src/main/java/org/edu_sharing/alfresco/action/RessourceInfoTool.java @@ -56,7 +56,7 @@ public void setSubtype(String subtype) { */ public ArrayList isQti(Document doc, XPath xpath){ - ArrayList qtiInfos = new ArrayList(); + ArrayList qtiInfos = new ArrayList<>(); try{ String ressourceTypeExp = "/manifest/resources/resource[@type]"; NodeList nodeList = (NodeList) xpath.evaluate(ressourceTypeExp, doc, XPathConstants.NODESET); diff --git a/Backend/alfresco/module/src/main/java/org/edu_sharing/alfresco/action/ZipContentIndexer.java b/Backend/alfresco/module/src/main/java/org/edu_sharing/alfresco/action/ZipContentIndexer.java index 06bd0c6f95..bde74e1e1a 100644 --- a/Backend/alfresco/module/src/main/java/org/edu_sharing/alfresco/action/ZipContentIndexer.java +++ b/Backend/alfresco/module/src/main/java/org/edu_sharing/alfresco/action/ZipContentIndexer.java @@ -129,8 +129,8 @@ private void indexResourceBody(NodeRef actionedUponNodeRef) { String contentToIdx = ""; - ArrayList theInputStreams = new ArrayList(); - ArrayList fileNamesToIndex = new ArrayList(); + ArrayList theInputStreams = new ArrayList<>(); + ArrayList fileNamesToIndex = new ArrayList<>(); try { diff --git a/Backend/alfresco/module/src/main/java/org/edu_sharing/alfresco/apache/tika/parser/mp4/MP4Parser.java b/Backend/alfresco/module/src/main/java/org/edu_sharing/alfresco/apache/tika/parser/mp4/MP4Parser.java index 3e3ea891c3..dcbabf9f64 100644 --- a/Backend/alfresco/module/src/main/java/org/edu_sharing/alfresco/apache/tika/parser/mp4/MP4Parser.java +++ b/Backend/alfresco/module/src/main/java/org/edu_sharing/alfresco/apache/tika/parser/mp4/MP4Parser.java @@ -74,7 +74,7 @@ public class MP4Parser extends AbstractParser { DURATION_FORMAT.applyPattern("0.0#"); } // Ensure this stays in Sync with the entries in tika-mimetypes.xml - private static final Map> typesMap = new HashMap>(); + private static final Map> typesMap = new HashMap<>(); static { // All types should be 4 bytes long, space padded as needed typesMap.put(MediaType.audio("mp4"), Arrays.asList( @@ -361,4 +361,4 @@ private static T getOrNull(Container box, Class clazz) { } return boxes.get(0); } -} \ No newline at end of file +} diff --git a/Backend/alfresco/module/src/main/java/org/edu_sharing/alfresco/fixes/MetadataPresettingPolicy.java b/Backend/alfresco/module/src/main/java/org/edu_sharing/alfresco/fixes/MetadataPresettingPolicy.java index 4f56b2d38e..815214b632 100644 --- a/Backend/alfresco/module/src/main/java/org/edu_sharing/alfresco/fixes/MetadataPresettingPolicy.java +++ b/Backend/alfresco/module/src/main/java/org/edu_sharing/alfresco/fixes/MetadataPresettingPolicy.java @@ -46,7 +46,7 @@ public class MetadataPresettingPolicy implements private static final QName ASPECT_ASSOC = QName .createQName(CCConstants.CCM_ASSOC_METADATA_PRESETTING_TEMPLATE); - private final List defaultQNames = new ArrayList(); + private final List defaultQNames = new ArrayList<>(); /** * The common node service diff --git a/Backend/alfresco/module/src/main/java/org/edu_sharing/alfresco/fixes/VirtualEduGroupFolderTool.java b/Backend/alfresco/module/src/main/java/org/edu_sharing/alfresco/fixes/VirtualEduGroupFolderTool.java index 5d57fd6f58..b94c7a7a02 100644 --- a/Backend/alfresco/module/src/main/java/org/edu_sharing/alfresco/fixes/VirtualEduGroupFolderTool.java +++ b/Backend/alfresco/module/src/main/java/org/edu_sharing/alfresco/fixes/VirtualEduGroupFolderTool.java @@ -45,7 +45,7 @@ public VirtualEduGroupFolderTool(ServiceRegistry serviceRegistry, NodeService no Collection eduGroupNodeRefs = getEduGroupNodeRefs(); - List children = new ArrayList(); + List children = new ArrayList<>(); for (NodeRef eduGroupNodeRef : eduGroupNodeRefs) { try { @@ -80,7 +80,7 @@ public List getGroupMapChildren(NodeRef nodeRef) { NodeService nodeService = serviceRegistry.getNodeService(); Set authorities = authorityService.getContainingAuthorities(AuthorityType.GROUP, user, true); - List children = new ArrayList(); + List children = new ArrayList<>(); for (String authority : authorities) { NodeRef nodeRefAuthority = authorityService.getAuthorityNodeRef(authority); diff --git a/Backend/alfresco/module/src/main/java/org/edu_sharing/alfresco/metadata/TikaAutoMetadataExtracter.java b/Backend/alfresco/module/src/main/java/org/edu_sharing/alfresco/metadata/TikaAutoMetadataExtracter.java index 4eb5526582..fae8e2ec26 100644 --- a/Backend/alfresco/module/src/main/java/org/edu_sharing/alfresco/metadata/TikaAutoMetadataExtracter.java +++ b/Backend/alfresco/module/src/main/java/org/edu_sharing/alfresco/metadata/TikaAutoMetadataExtracter.java @@ -55,7 +55,7 @@ public class TikaAutoMetadataExtracter //extends org.alfresco.transformer.metada // */ // // -// SUPPORTED_MIMETYPES = new ArrayList(); +// SUPPORTED_MIMETYPES = new ArrayList<>(); // for(MediaType mt : parser.getParsers().keySet()) // { // // Add the canonical mime type diff --git a/Backend/alfresco/module/src/main/java/org/edu_sharing/alfresco/monitoring/MonitoringDao.java b/Backend/alfresco/module/src/main/java/org/edu_sharing/alfresco/monitoring/MonitoringDao.java index f7ab5b8c7b..c0af375f15 100644 --- a/Backend/alfresco/module/src/main/java/org/edu_sharing/alfresco/monitoring/MonitoringDao.java +++ b/Backend/alfresco/module/src/main/java/org/edu_sharing/alfresco/monitoring/MonitoringDao.java @@ -1,9 +1,6 @@ package org.edu_sharing.alfresco.monitoring; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Set; +import java.util.*; import javax.management.MBeanAttributeInfo; import javax.management.MBeanInfo; @@ -34,8 +31,8 @@ public class MonitoringDao { - public HashMap getDataBasePoolInfo(){ - HashMap map = new HashMap(); + public Map getDataBasePoolInfo(){ + Map map = new HashMap<>(); map.put(MAX_TOTAL, "" + dataSource.getMaxTotal()); map.put(MAX_IDLE, "" + dataSource.getMaxIdle()); map.put(NUM_ACTIVE, "" + dataSource.getNumActive()); @@ -55,7 +52,7 @@ public String[] getMBeans() throws Exception { Set set = mBeanServer.queryMBeans(objectName, null); Iterator iterator = set.iterator(); - ArrayList names = new ArrayList(); + ArrayList names = new ArrayList<>(); while (iterator.hasNext()) { ObjectInstance oi = iterator.next(); ObjectName objName = oi.getObjectName(); @@ -74,7 +71,7 @@ public String[] getMBeans() throws Exception { * @return * @throws Exception */ - public HashMap getMBeanAttributes(String mbeanName, String[] attributes) throws Exception { + public Map getMBeanAttributes(String mbeanName, String[] attributes) throws Exception { MBeanServer mBeanServer = Registry.getRegistry(null, null).getMBeanServer(); String onStr = "*:type=ThreadPool,*"; @@ -82,7 +79,7 @@ public HashMap getMBeanAttributes(String mbeanName, String[] att Set set = mBeanServer.queryMBeans(objectName, null); Iterator iterator = set.iterator(); - HashMap result = new HashMap(); + Map result = new HashMap<>(); while (iterator.hasNext()) { ObjectInstance oi = iterator.next(); @@ -118,7 +115,7 @@ public HashMap getMBeanAttributes(String mbeanName, String[] att } - public HashMap getSessionCount(String host) throws Exception{ + public Map getSessionCount(String host) throws Exception{ return new TomcatUtil().getSessionCount(host); } diff --git a/Backend/alfresco/module/src/main/java/org/edu_sharing/alfresco/monitoring/TomcatUtil.java b/Backend/alfresco/module/src/main/java/org/edu_sharing/alfresco/monitoring/TomcatUtil.java index a1c1b80f0c..d8fed507a8 100644 --- a/Backend/alfresco/module/src/main/java/org/edu_sharing/alfresco/monitoring/TomcatUtil.java +++ b/Backend/alfresco/module/src/main/java/org/edu_sharing/alfresco/monitoring/TomcatUtil.java @@ -1,9 +1,6 @@ package org.edu_sharing.alfresco.monitoring; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; +import java.util.*; import javax.management.*; @@ -17,9 +14,9 @@ import org.apache.tomcat.util.modeler.Registry; public class TomcatUtil { - - - /** + + + /** * The application prefix. */ private static final String APP_PREFIX = "/"; @@ -32,148 +29,148 @@ public class TomcatUtil { */ private static final String ROOT_ID = ""; - - public static org.apache.catalina.Session[] getTomcatSessions(Service service, String host, String webApp) { + + public static org.apache.catalina.Session[] getTomcatSessions(Service service, String host, String webApp) { org.apache.catalina.Session[] result = null; StandardContext context = getContext(service, host, webApp); result = getSessions(context); return result; - } - - private static StandardContext getContext(Service service, String host, String webApp) { + } + + private static StandardContext getContext(Service service, String host, String webApp) { StandardContext result = null; StandardHost hostContainer = getHost(service, host); if (hostContainer != null) { - + result = (StandardContext) hostContainer.findChild(webApp); } else { System.out.println("No host {0} found" + new Object[]{host}); } return result; } - - private static Container[] getContexts(Service service) { - List result = new ArrayList(); - Container root = service.getContainer(); - if (root != null) { - Container[] hosts = root.findChildren(); - if (hosts != null) { - for (Container host : hosts) { - Container[] items = host.findChildren(); - result.addAll(Arrays.asList(items)); - } - } - } - return result.toArray(new Container[result.size()]); - } - - private static StandardHost getHost(Service service, String host) { - StandardHost result = null; - Engine engineService = (Engine) service.getContainer(); - if (engineService != null) { - result = (StandardHost) engineService.findChild(host); - } - return result; - } - - private static org.apache.catalina.Session[] getSessions(StandardContext context) { - org.apache.catalina.Session[] result = null; - if (context != null) { - Manager manager = context.getManager(); - if (manager != null) { - try { - result = manager.findSessions(); - } catch (Exception ex) { - //LOGGER.log(Level.SEVERE, "Error by reading the list of sessions", ex); - } - } else { - // LOGGER.log(Level.SEVERE, "No mananager found for web application"); - } - } else { - //LOGGER.log(Level.SEVERE, "No context found for web application"); - } - return result; - } - - - public HashMap getSessionCount(String host) throws Exception{ - - Service service = getService(); - - HashMap result = new HashMap(); - - List apps = getApplications(service); - for(Application app:apps){ - Session[] sessions = getTomcatSessions(service, host, "/" + app.getName()); - - result.put(app, sessions.length); - } - - - return result; - } - - public Session[] getSessions(String host, String webapp) throws Exception{ - Service service = getService(); - List apps = getApplications(service); - Application app = apps.stream().filter(a -> a.getName().equals(webapp)).findFirst().get(); - return getTomcatSessions(service, host, "/" + app.getName()); - } - - private Service getService() throws MalformedObjectNameException, ReflectionException, AttributeNotFoundException, InstanceNotFoundException, MBeanException { - MBeanServer mBeanServer = Registry.getRegistry(null, null).getMBeanServer(); - org.apache.catalina.Server server = (org.apache.catalina.Server) mBeanServer.getAttribute(new ObjectName("Catalina", "type", "Server"), "managedResource"); - - return server.findService("Catalina"); - } - - public static List getApplications(Service service) { - Container[] contexts = getContexts(service); - List result = new ArrayList(); - if (contexts != null) { - for (Container tmp : contexts) { - Application app = createApplication(tmp); - if (app != null) { - result.add(app); - } - } - } - return result; - } - - private static Application createApplication(Container context) { - Application result = null; - if (context != null) { - result = new Application(); - result.setId(getTomcatApplicationId(context)); - Container parent = context.getParent(); - if (parent != null) { - result.setHost(parent.getName()); - } - // The name string (suitable for use by humans) - result.setName(getApplicationName(context.getName())); - } - return result; - } - - - private static String getTomcatApplicationId(Container container) { - String result = null; - if (container != null) { - result = getApplicationName(container.getName()); - } - return result; - } - - private static String getApplicationName(String name) { - String result = name; - if (name == null || name.isEmpty()) { - result = ROOT_NAME; - } else { - if (name.startsWith(APP_PREFIX)) { - result = name.substring(APP_PREFIX.length()); - } - } - return result; - } + + private static Container[] getContexts(Service service) { + List result = new ArrayList<>(); + Container root = service.getContainer(); + if (root != null) { + Container[] hosts = root.findChildren(); + if (hosts != null) { + for (Container host : hosts) { + Container[] items = host.findChildren(); + result.addAll(Arrays.asList(items)); + } + } + } + return result.toArray(new Container[result.size()]); + } + + private static StandardHost getHost(Service service, String host) { + StandardHost result = null; + Engine engineService = (Engine) service.getContainer(); + if (engineService != null) { + result = (StandardHost) engineService.findChild(host); + } + return result; + } + + private static org.apache.catalina.Session[] getSessions(StandardContext context) { + org.apache.catalina.Session[] result = null; + if (context != null) { + Manager manager = context.getManager(); + if (manager != null) { + try { + result = manager.findSessions(); + } catch (Exception ex) { + //LOGGER.log(Level.SEVERE, "Error by reading the list of sessions", ex); + } + } else { + // LOGGER.log(Level.SEVERE, "No mananager found for web application"); + } + } else { + //LOGGER.log(Level.SEVERE, "No context found for web application"); + } + return result; + } + + + public Map getSessionCount(String host) throws Exception { + + Service service = getService(); + + Map result = new HashMap<>(); + + List apps = getApplications(service); + for (Application app : apps) { + Session[] sessions = getTomcatSessions(service, host, "/" + app.getName()); + + result.put(app, sessions.length); + } + + + return result; + } + + public Session[] getSessions(String host, String webapp) throws Exception { + Service service = getService(); + List apps = getApplications(service); + Application app = apps.stream().filter(a -> a.getName().equals(webapp)).findFirst().get(); + return getTomcatSessions(service, host, "/" + app.getName()); + } + + private Service getService() throws MalformedObjectNameException, ReflectionException, AttributeNotFoundException, InstanceNotFoundException, MBeanException { + MBeanServer mBeanServer = Registry.getRegistry(null, null).getMBeanServer(); + org.apache.catalina.Server server = (org.apache.catalina.Server) mBeanServer.getAttribute(new ObjectName("Catalina", "type", "Server"), "managedResource"); + + return server.findService("Catalina"); + } + + public static List getApplications(Service service) { + Container[] contexts = getContexts(service); + List result = new ArrayList<>(); + if (contexts != null) { + for (Container tmp : contexts) { + Application app = createApplication(tmp); + if (app != null) { + result.add(app); + } + } + } + return result; + } + + private static Application createApplication(Container context) { + Application result = null; + if (context != null) { + result = new Application(); + result.setId(getTomcatApplicationId(context)); + Container parent = context.getParent(); + if (parent != null) { + result.setHost(parent.getName()); + } + // The name string (suitable for use by humans) + result.setName(getApplicationName(context.getName())); + } + return result; + } + + + private static String getTomcatApplicationId(Container container) { + String result = null; + if (container != null) { + result = getApplicationName(container.getName()); + } + return result; + } + + private static String getApplicationName(String name) { + String result = name; + if (name == null || name.isEmpty()) { + result = ROOT_NAME; + } else { + if (name.startsWith(APP_PREFIX)) { + result = name.substring(APP_PREFIX.length()); + } + } + return result; + } } diff --git a/Backend/alfresco/module/src/main/java/org/edu_sharing/alfresco/policy/HomeFolderTool.java b/Backend/alfresco/module/src/main/java/org/edu_sharing/alfresco/policy/HomeFolderTool.java index 7ccd58ffc4..19cf16d890 100644 --- a/Backend/alfresco/module/src/main/java/org/edu_sharing/alfresco/policy/HomeFolderTool.java +++ b/Backend/alfresco/module/src/main/java/org/edu_sharing/alfresco/policy/HomeFolderTool.java @@ -97,7 +97,7 @@ private NodeRef createMap(NodeRef parent, String mapType, String nameI18nKey, St List childAssocs = nodeService.getChildAssocsByPropertyValue(parent, QName.createQName(CCConstants.CCM_PROP_MAP_TYPE), mapType); if(childAssocs == null || childAssocs.size() == 0){ String userDataFolderName = I18nServer.getTranslationDefaultResourcebundle(nameI18nKey); - Map props = new HashMap(); + Map props = new HashMap<>(); props.put(ContentModel.PROP_NAME,userDataFolderName); MLText mlTitle = new MLText(); mlTitle.addValue(new Locale("de","DE"),I18nServer.getTranslationDefaultResourcebundle(nameI18nKey, "de_DE")); diff --git a/Backend/alfresco/module/src/main/java/org/edu_sharing/alfresco/policy/NodeCustomizationPolicies.java b/Backend/alfresco/module/src/main/java/org/edu_sharing/alfresco/policy/NodeCustomizationPolicies.java index c70a045084..6a4cc13b33 100644 --- a/Backend/alfresco/module/src/main/java/org/edu_sharing/alfresco/policy/NodeCustomizationPolicies.java +++ b/Backend/alfresco/module/src/main/java/org/edu_sharing/alfresco/policy/NodeCustomizationPolicies.java @@ -365,8 +365,8 @@ private void verifyFileLimit(ContentReader reader, Long sizeLimit) throws NodeFi } } - private static HashMap> getMimetypeAllowList() { - HashMap> allowList = LightbendConfigLoader.get(). + private static Map> getMimetypeAllowList() { + Map> allowList = LightbendConfigLoader.get(). getConfig("security.fileManagement.mimetypeVerification.list").entrySet().stream().collect( Collectors.toMap(e -> StringUtils.strip(e.getKey(), "\""), e -> (List) e.getValue().unwrapped(), (a, b) -> b, HashMap::new) @@ -479,7 +479,7 @@ public void onCreateNode(ChildAssociationRef childAssocRef) { * only do this with local created objects. contributer info is delivered by importer */ if(replicationSourceId == null || replicationSourceId.trim().equals("")){ - HashMap vcardMap = new HashMap(); + Map vcardMap = new HashMap<>(); if(personRef!=null) { vcardMap.put(CCConstants.VCARD_URN_UID, uid); vcardMap.put(CCConstants.VCARD_GIVENNAME, givenName); @@ -843,7 +843,7 @@ public void generateWebsitePreview(NodeRef nodeRef, String url) { * @return */ Map transformQNameKeyToString(Map props){ - Map result = new HashMap(); + Map result = new HashMap<>(); for(Map.Entry entry : props.entrySet()){ result.put(entry.getKey().toString(), entry.getValue()); } diff --git a/Backend/alfresco/module/src/main/java/org/edu_sharing/alfresco/policy/OnCopyTinymcePolicy.java b/Backend/alfresco/module/src/main/java/org/edu_sharing/alfresco/policy/OnCopyTinymcePolicy.java index 0294392785..1c751a6c21 100644 --- a/Backend/alfresco/module/src/main/java/org/edu_sharing/alfresco/policy/OnCopyTinymcePolicy.java +++ b/Backend/alfresco/module/src/main/java/org/edu_sharing/alfresco/policy/OnCopyTinymcePolicy.java @@ -61,7 +61,7 @@ public void onCopyComplete(QName classRef, NodeRef sourceNodeRef, NodeRef target } Map transformQNameKeyToString(Map props) { - Map result = new HashMap(); + Map result = new HashMap<>(); for (Map.Entry entry : props.entrySet()) { result.put(entry.getKey().toString(), entry.getValue()); } diff --git a/Backend/alfresco/module/src/main/java/org/edu_sharing/alfresco/service/OrganisationService.java b/Backend/alfresco/module/src/main/java/org/edu_sharing/alfresco/service/OrganisationService.java index 71e6358131..a3d56d1909 100644 --- a/Backend/alfresco/module/src/main/java/org/edu_sharing/alfresco/service/OrganisationService.java +++ b/Backend/alfresco/module/src/main/java/org/edu_sharing/alfresco/service/OrganisationService.java @@ -222,7 +222,7 @@ public void bindEduGroupFolder(String groupName, NodeRef folder) throws Exceptio throw new Exception("Folder does not exist"); } - Map params = new HashMap(); + Map params = new HashMap<>(); params.put(QName.createQName(CCM_PROP_EDUGROUP_EDU_HOMEDIR), folder); params.put(QName.createQName(CCM_PROP_EDUGROUP_EDU_UNIQUENAME), groupName); @@ -230,7 +230,7 @@ public void bindEduGroupFolder(String groupName, NodeRef folder) throws Exceptio } private NodeRef createNode(NodeRef parent, String type, String name) { - Map propsOrgFolder = new HashMap(); + Map propsOrgFolder = new HashMap<>(); propsOrgFolder.put(ContentModel.PROP_NAME, name); String assocName = "{" + CCConstants.NAMESPACE_CCM + "}" + name; return nodeService.createNode(parent, ContentModel.ASSOC_CONTAINS, QName.createQName(assocName), QName.createQName(type), propsOrgFolder).getChildRef(); @@ -358,7 +358,7 @@ public String getAuthorityName(String organisationName) { public List getMyOrganisations(boolean scoped){ Set authorities = authorityService.getContainingAuthorities(AuthorityType.GROUP, AuthenticationUtil.getFullyAuthenticatedUser(), true); - List organisations = new ArrayList(); + List organisations = new ArrayList<>(); for (String authority : authorities) { NodeRef nodeRefAuthority = authorityService.getAuthorityNodeRef(authority); if (nodeService.hasAspect(nodeRefAuthority, QName.createQName(CCConstants.CCM_ASPECT_EDUGROUP))) { diff --git a/Backend/alfresco/module/src/main/java/org/edu_sharing/alfresco/service/search/CMISSearchHelper.java b/Backend/alfresco/module/src/main/java/org/edu_sharing/alfresco/service/search/CMISSearchHelper.java index 9933cc6869..467bcae290 100644 --- a/Backend/alfresco/module/src/main/java/org/edu_sharing/alfresco/service/search/CMISSearchHelper.java +++ b/Backend/alfresco/module/src/main/java/org/edu_sharing/alfresco/service/search/CMISSearchHelper.java @@ -116,7 +116,7 @@ private static void prepareWhere(StringBuilder where) { } public static List fetchNodesByTypeAndFilters(String nodeType, Map filters, List aspects, CMISSearchData data, int maxPermissionChecks, StoreRef storeRef){ - List result = new ArrayList(); + List result = new ArrayList<>(); int from = 0; diff --git a/Backend/alfresco/module/src/main/java/org/edu_sharing/alfresco/service/search/cmis/QueryBuilder.java b/Backend/alfresco/module/src/main/java/org/edu_sharing/alfresco/service/search/cmis/QueryBuilder.java index 62b9fe66fe..e803412e6c 100644 --- a/Backend/alfresco/module/src/main/java/org/edu_sharing/alfresco/service/search/cmis/QueryBuilder.java +++ b/Backend/alfresco/module/src/main/java/org/edu_sharing/alfresco/service/search/cmis/QueryBuilder.java @@ -17,7 +17,7 @@ public class QueryBuilder { private final DictionaryService dictionaryService; - private static final Map cmisAlfMapping = new HashMap(){{ + private static final Map cmisAlfMapping = new HashMap<>(){{ put(CCConstants.SYS_PROP_NODE_UID, "objectId"); put(CCConstants.CM_NAME, "name"); put(CCConstants.CM_PROP_VERSIONABLELABEL, "versionLabel"); diff --git a/Backend/alfresco/module/src/main/java/org/edu_sharing/alfresco/service/toolpermission/ToolPermissionBaseService.java b/Backend/alfresco/module/src/main/java/org/edu_sharing/alfresco/service/toolpermission/ToolPermissionBaseService.java index e9d02392b1..a6fe8e7a03 100644 --- a/Backend/alfresco/module/src/main/java/org/edu_sharing/alfresco/service/toolpermission/ToolPermissionBaseService.java +++ b/Backend/alfresco/module/src/main/java/org/edu_sharing/alfresco/service/toolpermission/ToolPermissionBaseService.java @@ -133,7 +133,7 @@ public NodeRef getEdu_SharingSystemFolderBase() throws Throwable{ private NodeRef createNewFolder(NodeRef parentRef, String name, String mapType) { NodeRef result; String folderName = I18nServer.getTranslationDefaultResourcebundle(name); - HashMap props = new HashMap<>(); + Map props = new HashMap<>(); props.put(QName.createQName(CCConstants.CM_NAME), folderName); MLText i18nTitle = new MLText(); @@ -160,7 +160,7 @@ public Collection getAllToolPermissions(boolean refresh){ AuthenticationUtil.RunAsWork> runas = new AuthenticationUtil.RunAsWork>() { @Override public List doWork() throws Exception { - List result = new ArrayList(); + List result = new ArrayList<>(); try { List childAssocRefs = nodeService.getChildAssocs(getEdu_SharingToolPermissionsFolder()); for(ChildAssociationRef childAssocRef : childAssocRefs) { @@ -284,7 +284,7 @@ public String getToolPermissionNodeId(String toolPermission) throws Throwable{ protected NodeRef createToolpermission(String toolPermission) throws Throwable { logger.info("ToolPermission" + toolPermission+ " does not exists. will create it."); - HashMap props = new HashMap(); + Map props = new HashMap(); props.put(QName.createQName(CCConstants.CM_NAME), toolPermission); NodeRef result = nodeService.createNode(getEdu_SharingToolPermissionsFolder(), @@ -331,7 +331,7 @@ public List getAllDefaultAllowedToolpermissions(){ return toInit; } public List getAllPredefinedToolPermissions(){ - List toInit=new ArrayList(); + List toInit=new ArrayList<>(); toInit.add(CCConstants.CCM_VALUE_TOOLPERMISSION_GLOBAL_AUTHORITY_SEARCH); toInit.add(CCConstants.CCM_VALUE_TOOLPERMISSION_GLOBAL_AUTHORITY_SEARCH_FUZZY); toInit.add(CCConstants.CCM_VALUE_TOOLPERMISSION_GLOBAL_AUTHORITY_SEARCH_SHARE); diff --git a/Backend/alfresco/module/src/main/java/org/edu_sharing/alfresco/tools/UsageTool.java b/Backend/alfresco/module/src/main/java/org/edu_sharing/alfresco/tools/UsageTool.java index e704509945..73888c5bfe 100644 --- a/Backend/alfresco/module/src/main/java/org/edu_sharing/alfresco/tools/UsageTool.java +++ b/Backend/alfresco/module/src/main/java/org/edu_sharing/alfresco/tools/UsageTool.java @@ -61,7 +61,7 @@ public void removeUsage(String lmsId, String courseId, String parentNodeId, Stri } } public void createUsage(String lmsId, String courseId, String parentNodeId, String resourceId){ - HashMap properties = new HashMap<>(); + Map properties = new HashMap<>(); properties.put(QName.createQName(CCConstants.CCM_PROP_USAGE_APPID), lmsId); properties.put(QName.createQName(CCConstants.CCM_PROP_USAGE_COURSEID), courseId); properties.put(QName.createQName(CCConstants.CCM_PROP_USAGE_PARENTNODEID), parentNodeId); diff --git a/Backend/alfresco/module/src/main/java/org/edu_sharing/alfresco/webscripts/tracker/PermissionsGet.java b/Backend/alfresco/module/src/main/java/org/edu_sharing/alfresco/webscripts/tracker/PermissionsGet.java index c53b8678d5..df8b796241 100644 --- a/Backend/alfresco/module/src/main/java/org/edu_sharing/alfresco/webscripts/tracker/PermissionsGet.java +++ b/Backend/alfresco/module/src/main/java/org/edu_sharing/alfresco/webscripts/tracker/PermissionsGet.java @@ -70,7 +70,7 @@ else if (aclIdsJSON.length() == 0) "Parameter 'aclIds' must hold from 1 or more IDs."); } - aclIds = new ArrayList(aclIdsJSON.length()); + aclIds = new ArrayList<>(aclIdsJSON.length()); for (int i = 0; i < aclIdsJSON.length(); i++) { aclIds.add(aclIdsJSON.getLong(i)); @@ -103,7 +103,7 @@ else if (aclIdsJSON.length() == 0) } - Map model = new HashMap(1, 1.0f); + Map model = new HashMap<>(1, 1.0f); model.put("accessControlLists", accessControlLists); if (logger.isDebugEnabled()) diff --git a/Backend/alfresco/module/src/main/java/org/edu_sharing/alfresco/workspace_administration/NodeServiceInterceptor.java b/Backend/alfresco/module/src/main/java/org/edu_sharing/alfresco/workspace_administration/NodeServiceInterceptor.java index 829411563f..e089089608 100644 --- a/Backend/alfresco/module/src/main/java/org/edu_sharing/alfresco/workspace_administration/NodeServiceInterceptor.java +++ b/Backend/alfresco/module/src/main/java/org/edu_sharing/alfresco/workspace_administration/NodeServiceInterceptor.java @@ -71,7 +71,7 @@ public Object invoke(MethodInvocation invocation) throws Throwable { String currentScope = NodeServiceInterceptor.eduSharingScope.get(); logger.info("runAsUser:" + runAsUser + " currentScope:" + currentScope); List childAssocs = (List) invocation.proceed(); - List childAssocsResult = new ArrayList(); + List childAssocsResult = new ArrayList<>(); for (ChildAssociationRef childRef : childAssocs) { NodeRef nodeRef = childRef.getChildRef(); diff --git a/Backend/alfresco/module/src/main/java/org/edu_sharing/metadataset/v2/MetadataReader.java b/Backend/alfresco/module/src/main/java/org/edu_sharing/metadataset/v2/MetadataReader.java index e62760e93b..6ed362dec8 100644 --- a/Backend/alfresco/module/src/main/java/org/edu_sharing/metadataset/v2/MetadataReader.java +++ b/Backend/alfresco/module/src/main/java/org/edu_sharing/metadataset/v2/MetadataReader.java @@ -268,7 +268,7 @@ private Map getQueries(MetadataSet mds) throws Exceptio if (attributes.getNamedItem("asFilter") != null && attributes.getNamedItem("asFilter").getTextContent() != null) { parameter.setAsFilter(new Boolean(attributes.getNamedItem("asFilter").getTextContent())); } - Map statements = new HashMap(); + Map statements = new HashMap<>(); for (int k = 0; k < list3.getLength(); k++) { Node data = list3.item(k); String name = data.getNodeName(); diff --git a/Backend/alfresco/module/src/main/java/org/edu_sharing/repository/client/tools/forms/CCForms.java b/Backend/alfresco/module/src/main/java/org/edu_sharing/repository/client/tools/forms/CCForms.java index 1677402e2b..b4c6b022e4 100644 --- a/Backend/alfresco/module/src/main/java/org/edu_sharing/repository/client/tools/forms/CCForms.java +++ b/Backend/alfresco/module/src/main/java/org/edu_sharing/repository/client/tools/forms/CCForms.java @@ -28,6 +28,7 @@ package org.edu_sharing.repository.client.tools.forms; import java.util.HashMap; +import java.util.Map; import org.edu_sharing.repository.client.tools.CCConstants; @@ -212,7 +213,7 @@ public class CCForms { public static HashMap getClasses(){ if(classes == null){ - classes = new HashMap(); + classes = new HashMap<>(); classes.put(CCConstants.CCM_TYPE_IO, io); classes.put(CCConstants.CCM_TYPE_MAP, map); //classes.put(CCConstants.CCM_TYPE_MAPLINK, maplink); @@ -250,11 +251,11 @@ public static String[] getRow(String type, String property){ return null; } - private static HashMap propFormMapper = null; + private static Map propFormMapper = null; private static void initFormMapper(){ if(propFormMapper == null){ - propFormMapper = new HashMap(); + propFormMapper = new HashMap<>(); propFormMapper.put(CCConstants.CCM_TYPE_IO+"#"+CCConstants.CM_PROP_CONTENT, CCConstants.CCM_TYPE_IO+"#"+CCConstants.CM_PROP_CONTENT); propFormMapper.put(CCConstants.CM_TYPE_THUMBNAIL+"#"+CCConstants.CM_PROP_CONTENT, CCConstants.CM_TYPE_THUMBNAIL+"#"+CCConstants.CM_PROP_CONTENT); propFormMapper.put(CCConstants.CCM_TYPE_MAP+"#"+CCConstants.CCM_PROP_MAP_ICON, CCConstants.CCM_TYPE_MAP+"#"+CCConstants.CCM_PROP_MAP_ICON); @@ -316,11 +317,11 @@ public static String getPropByFormEle(String type, String formElementName){ /** * Child Assocition the ParentNode gots to it's childs */ - private static HashMap childAssocs = null; + private static Map childAssocs = null; public static String getChildAssoc(String type){ if(childAssocs == null){ - childAssocs = new HashMap(); + childAssocs = new HashMap<>(); childAssocs.put(CCConstants.LOM_TYPE_CONTRIBUTE, CCConstants.LOM_ASSOC_LIFECYCLE_CONTRIBUTE); childAssocs.put(CCConstants.LOM_TYPE_RELATION, CCConstants.LOM_ASSOC_SCHEMA_RELATION); } @@ -331,11 +332,11 @@ public static String getChildAssoc(String type){ /** * is multivalue */ - private static HashMap isMultiValue = null; + private static Map isMultiValue = null; public static Boolean isMultiValue(String property){ if(isMultiValue == null){ - isMultiValue = new HashMap(); + isMultiValue = new HashMap<>(); isMultiValue.put(CCConstants.LOM_PROP_GENERAL_LANGUAGE, new Boolean(true)); isMultiValue.put(CCConstants.LOM_PROP_EDUCATIONAL_LEARNINGRESOURCETYPE, new Boolean(true)); } diff --git a/Backend/alfresco/module/src/main/java/org/edu_sharing/repository/client/tools/forms/VCardTool.java b/Backend/alfresco/module/src/main/java/org/edu_sharing/repository/client/tools/forms/VCardTool.java index c1ff9cdc6b..c17e2c6160 100644 --- a/Backend/alfresco/module/src/main/java/org/edu_sharing/repository/client/tools/forms/VCardTool.java +++ b/Backend/alfresco/module/src/main/java/org/edu_sharing/repository/client/tools/forms/VCardTool.java @@ -35,11 +35,11 @@ public class VCardTool { public static String nameToVCard(String name){ - HashMap map=new HashMap(); + Map map = new HashMap<>(); map.put(CCConstants.VCARD_GIVENNAME, name); return hashMap2VCard(map); } - public static String hashMap2VCard(HashMap map){ + public static String hashMap2VCard(Map map){ String uid = getValid(map.get(CCConstants.VCARD_URN_UID)); String surname = getValid(map.get(CCConstants.VCARD_SURNAME)); diff --git a/Backend/alfresco/module/src/main/java/org/edu_sharing/repository/server/tools/ActionObserver.java b/Backend/alfresco/module/src/main/java/org/edu_sharing/repository/server/tools/ActionObserver.java index a254927072..91521a7df2 100644 --- a/Backend/alfresco/module/src/main/java/org/edu_sharing/repository/server/tools/ActionObserver.java +++ b/Backend/alfresco/module/src/main/java/org/edu_sharing/repository/server/tools/ActionObserver.java @@ -49,7 +49,7 @@ private ActionObserver() { } public Map> nodeActionsMap = Collections - .synchronizedMap(new HashMap>()); + .synchronizedMap(new HashMap<>()); /** * calls removeInactiveActions @@ -70,7 +70,7 @@ public void addAction(NodeRef nodeRef, Action action) { List actions = nodeActionsMap.get(nodeRef); if (actions == null) { synchronized (nodeActionsMap) { - actions = Collections.synchronizedList(new ArrayList()); + actions = Collections.synchronizedList(new ArrayList<>()); nodeActionsMap.put(nodeRef, actions); } } @@ -115,7 +115,7 @@ public synchronized void removeInactiveActions() { RunAsWork runAs = new RunAsWork() { @Override public Void doWork() throws Exception { - ArrayList toRemove = new ArrayList(); + ArrayList toRemove = new ArrayList<>(); synchronized (nodeActionsMap) { for (Map.Entry> entry : nodeActionsMap.entrySet()) { @@ -142,7 +142,7 @@ public Void doWork() throws Exception { if (entry.getValue() != null && entry.getValue().size() > 0) { List actions = entry.getValue(); - List toRemoveActions = new ArrayList(); + List toRemoveActions = new ArrayList<>(); for (Action action : actions) { Date addDate = (Date) action.getParameterValue(ACTION_OBSERVER_ADD_DATE); diff --git a/Backend/alfresco/module/src/main/java/org/edu_sharing/repository/server/tools/ApplicationInfo.java b/Backend/alfresco/module/src/main/java/org/edu_sharing/repository/server/tools/ApplicationInfo.java index e51afb1daa..4567dc830e 100644 --- a/Backend/alfresco/module/src/main/java/org/edu_sharing/repository/server/tools/ApplicationInfo.java +++ b/Backend/alfresco/module/src/main/java/org/edu_sharing/repository/server/tools/ApplicationInfo.java @@ -939,7 +939,7 @@ public String getHostAliases() { * @return */ public boolean isTrustedHost(String hostName){ - List hostList = new ArrayList(); + List hostList = new ArrayList<>(); hostList.add(host); if(this.getDomain() != null && !this.getDomain().equals("")){ hostList.add(this.getDomain()); diff --git a/Backend/alfresco/module/src/main/java/org/edu_sharing/repository/server/tools/ApplicationInfoList.java b/Backend/alfresco/module/src/main/java/org/edu_sharing/repository/server/tools/ApplicationInfoList.java index 5fed0295a4..ee33ecddcd 100644 --- a/Backend/alfresco/module/src/main/java/org/edu_sharing/repository/server/tools/ApplicationInfoList.java +++ b/Backend/alfresco/module/src/main/java/org/edu_sharing/repository/server/tools/ApplicationInfoList.java @@ -123,7 +123,7 @@ public static Map getApplicationInfos(){ /** * @TODO refactor calls to this methode so that hashmap building is not needed */ - HashMap result = new HashMap<>(); + Map result = new HashMap<>(); appInfos.getKeys().forEach(appId -> result.put(appId,appInfos.get(appId))); return Collections.synchronizedMap(result); } @@ -199,7 +199,7 @@ private static synchronized void initAppInfos(){ */ public static ArrayList getRepositoryInfosOrdered(){ //set home reporsitory as the first one - ArrayList appInfoList = new ArrayList(); + ArrayList appInfoList = new ArrayList<>(); for(String key : ApplicationInfoList.getApplicationInfos().keySet()){ ApplicationInfo repInfo = ApplicationInfoList.getApplicationInfos().get(key); appInfoList.add(repInfo); diff --git a/Backend/alfresco/module/src/main/java/org/edu_sharing/repository/server/tools/I18nServer.java b/Backend/alfresco/module/src/main/java/org/edu_sharing/repository/server/tools/I18nServer.java index 1fcfec0c45..f5b2ba77b2 100644 --- a/Backend/alfresco/module/src/main/java/org/edu_sharing/repository/server/tools/I18nServer.java +++ b/Backend/alfresco/module/src/main/java/org/edu_sharing/repository/server/tools/I18nServer.java @@ -29,6 +29,7 @@ import java.util.HashMap; import java.util.Locale; +import java.util.Map; import java.util.ResourceBundle; import org.apache.commons.logging.Log; @@ -107,10 +108,10 @@ public static String getTranslationDefaultResourcebundle(String key,String langu return getTranslation(key,language,country,defaultResourceBundle); } - public static HashMap permViewMapper = null; + public static Map permViewMapper = null; public final static String getPermissionCaption(String permKey){ if(permViewMapper == null){ - permViewMapper = new HashMap(); + permViewMapper = new HashMap<>(); permViewMapper.put(CCConstants.PERMISSION_READ, "dialog_inviteusers_perm_read"); permViewMapper.put(CCConstants.PERMISSION_READ_PREVIEW, "dialog_inviteusers_perm_readpreview"); permViewMapper.put(CCConstants.PERMISSION_READ_ALL, "dialog_inviteusers_perm_readall"); diff --git a/Backend/alfresco/module/src/main/java/org/edu_sharing/repository/server/tools/cache/EduGroupCache.java b/Backend/alfresco/module/src/main/java/org/edu_sharing/repository/server/tools/cache/EduGroupCache.java index c4779b5c90..d6f4f26a7b 100644 --- a/Backend/alfresco/module/src/main/java/org/edu_sharing/repository/server/tools/cache/EduGroupCache.java +++ b/Backend/alfresco/module/src/main/java/org/edu_sharing/repository/server/tools/cache/EduGroupCache.java @@ -83,7 +83,7 @@ public static Collection getKeysEduGroupFolder(){ } public static String[] getNames(){ - ArrayList names = new ArrayList(); + ArrayList names = new ArrayList<>(); for(NodeRef nodeRef : cache.getKeys()){ names.add((String)cache.get(nodeRef).get(ContentModel.PROP_AUTHORITY_NAME)); } @@ -134,7 +134,7 @@ private static List getEduGroupNodeRefs(){ logger.info("starting"); AuthorityService authorityService =serviceRegistry.getAuthorityService(); NodeService nodeServiceAlfresco = (NodeService) AlfAppContextGate.getApplicationContext().getBean("alfrescoDefaultDbNodeService"); - List result = new ArrayList(); + List result = new ArrayList<>(); Set allGroups = authorityService.getAllAuthoritiesInZone(AuthorityService.ZONE_APP_DEFAULT, AuthorityType.GROUP); for(String authority : allGroups) { NodeRef authorityNodeRef = authorityService.getAuthorityNodeRef(authority); diff --git a/Backend/alfresco/module/src/main/java/org/edu_sharing/repository/server/tools/cache/PreviewCache.java b/Backend/alfresco/module/src/main/java/org/edu_sharing/repository/server/tools/cache/PreviewCache.java index 8630cdadb9..b6ab77a9fb 100644 --- a/Backend/alfresco/module/src/main/java/org/edu_sharing/repository/server/tools/cache/PreviewCache.java +++ b/Backend/alfresco/module/src/main/java/org/edu_sharing/repository/server/tools/cache/PreviewCache.java @@ -73,7 +73,7 @@ public static void purgeCache(String nodeId){ ServiceRegistry serviceRegistry = (ServiceRegistry) applicationContext.getBean(ServiceRegistry.SERVICE_REGISTRY); NodeService nodeService = serviceRegistry.getNodeService(); - ArrayList ids=new ArrayList(); + ArrayList ids=new ArrayList<>(); ids.add(nodeId); //check if node exists to prevent InvalidNodeRefException: Node does not exist when calling nodeService.getType on startup with clean database diff --git a/Backend/alfresco/module/src/main/java/org/edu_sharing/repository/server/tools/cache/RepositoryCache.java b/Backend/alfresco/module/src/main/java/org/edu_sharing/repository/server/tools/cache/RepositoryCache.java index 2d9f508dc7..b4f323e9dc 100644 --- a/Backend/alfresco/module/src/main/java/org/edu_sharing/repository/server/tools/cache/RepositoryCache.java +++ b/Backend/alfresco/module/src/main/java/org/edu_sharing/repository/server/tools/cache/RepositoryCache.java @@ -127,7 +127,7 @@ public boolean isShared() { // Local Cache over HashMap final Map>> localCache = - new HashMap>>(); + new HashMap<>(); CACHE = new InternalCache() { diff --git a/Backend/alfresco/module/src/main/java/org/edu_sharing/repository/server/tools/cache/UserCache.java b/Backend/alfresco/module/src/main/java/org/edu_sharing/repository/server/tools/cache/UserCache.java index 5803440e93..02d5602b7f 100644 --- a/Backend/alfresco/module/src/main/java/org/edu_sharing/repository/server/tools/cache/UserCache.java +++ b/Backend/alfresco/module/src/main/java/org/edu_sharing/repository/server/tools/cache/UserCache.java @@ -59,7 +59,7 @@ public User getUser(String username){ user.setGivenName((String)props.get(QName.createQName(CCConstants.CM_PROP_PERSON_FIRSTNAME))); user.setSurname(((String)props.get(QName.createQName(CCConstants.CM_PROP_PERSON_LASTNAME)))); user.setNodeId(persNoderef.getId()); - HashMap userProperties = new HashMap<>(); + Map userProperties = new HashMap<>(); for (Map.Entry entry : props.entrySet()) { Serializable value = entry.getValue(); userProperties.put( diff --git a/Backend/alfresco/module/src/main/java/org/edu_sharing/repository/server/tools/security/ShibbolethSessions.java b/Backend/alfresco/module/src/main/java/org/edu_sharing/repository/server/tools/security/ShibbolethSessions.java index c33c4dbdf9..9b09232a35 100644 --- a/Backend/alfresco/module/src/main/java/org/edu_sharing/repository/server/tools/security/ShibbolethSessions.java +++ b/Backend/alfresco/module/src/main/java/org/edu_sharing/repository/server/tools/security/ShibbolethSessions.java @@ -73,7 +73,7 @@ private static Map getInstance(){ writeLock.lock(); //check for null again to prevent the Map is created once mor by a waiter on write lock if(shibSessionAlfTicketMap == null){ - shibSessionAlfTicketMap = Collections.synchronizedMap(new HashMap()); + shibSessionAlfTicketMap = Collections.synchronizedMap(new HashMap<>()); } }finally{ diff --git a/Backend/alfresco/module/src/main/java/org/edu_sharing/utils/TreeNode.java b/Backend/alfresco/module/src/main/java/org/edu_sharing/utils/TreeNode.java index 51b02b8249..f71bcabac7 100644 --- a/Backend/alfresco/module/src/main/java/org/edu_sharing/utils/TreeNode.java +++ b/Backend/alfresco/module/src/main/java/org/edu_sharing/utils/TreeNode.java @@ -139,7 +139,7 @@ public static TreeNode of(Collection collection, Function key public static TreeNode of(V rootElement, Collection collection, Function keyProvider, Function parentKeyProvider) { TreeNode root = new TreeNode<>(rootElement); - LinkedHashMap> nodes = new LinkedHashMap<>(); + Map> nodes = new LinkedHashMap<>(); collection.forEach(x -> { K parentKey = parentKeyProvider.apply(x); TreeNode node = new TreeNode<>(x); diff --git a/Backend/alfresco/module/src/test/java/org/edu_sharing/alfresco/policy/NodeCustomizationPoliciesTest.java b/Backend/alfresco/module/src/test/java/org/edu_sharing/alfresco/policy/NodeCustomizationPoliciesTest.java index cbff21f1e8..4b5ec7fe9c 100644 --- a/Backend/alfresco/module/src/test/java/org/edu_sharing/alfresco/policy/NodeCustomizationPoliciesTest.java +++ b/Backend/alfresco/module/src/test/java/org/edu_sharing/alfresco/policy/NodeCustomizationPoliciesTest.java @@ -1,19 +1,9 @@ package org.edu_sharing.alfresco.policy; -import com.typesafe.config.Config; import org.alfresco.service.cmr.repository.ContentReader; import org.apache.tika.mime.MediaType; -import org.edu_sharing.alfresco.lightbend.LightbendConfigLoader; -import org.edu_sharing.alfrescocontext.gate.AlfAppContextGate; -import org.edu_sharing.repository.server.tools.ApplicationInfo; -import org.edu_sharing.repository.server.tools.ApplicationInfoList; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.mockito.ArgumentMatchers; -import org.mockito.MockedStatic; import org.mockito.Mockito; -import org.springframework.context.ApplicationContext; import java.io.ByteArrayInputStream; import java.io.UnsupportedEncodingException; @@ -26,12 +16,12 @@ class NodeCustomizationPoliciesTest { @Test void verifyMimetypeByMagicBytes() throws UnsupportedEncodingException { - Map LIST = new HashMap() {{ - put("image/jpeg", new byte[]{ (byte)0xFF, (byte)0xD8, (byte)0xFF, (byte)0xE0 }); + Map LIST = new HashMap<>() {{ + put("image/jpeg", new byte[]{(byte) 0xFF, (byte) 0xD8, (byte) 0xFF, (byte) 0xE0}); put("text/plain", "TEST".getBytes(StandardCharsets.UTF_8)); put("application/xml", "".getBytes(StandardCharsets.UTF_8)); //put("text/xml", "".getBytes(StandardCharsets.UTF_8)); - put("application/zip", new byte[]{ (byte)0x50, (byte)0x4B, (byte)0x05, (byte)0x06 }); + put("application/zip", new byte[]{(byte) 0x50, (byte) 0x4B, (byte) 0x05, (byte) 0x06}); }}; LIST.forEach((mimetype, magic) -> { @@ -42,7 +32,7 @@ void verifyMimetypeByMagicBytes() throws UnsupportedEncodingException { ); String filename = UUID.randomUUID() + "." + mimetype.split("/")[1]; Mockito.when(contentReader.getMimetype()).thenReturn(mimetype); - Map> allowList = new HashMap>() {{ + Map> allowList = new HashMap<>() {{ put(mimetype, Collections.singletonList(mimetype.split("/")[1])); }}; NodeCustomizationPolicies.verifyMimetype( @@ -50,7 +40,7 @@ void verifyMimetypeByMagicBytes() throws UnsupportedEncodingException { filename, allowList, false); - HashMap> allowListWrongMimetype = new HashMap>() {{ + Map> allowListWrongMimetype = new HashMap<>() {{ put("test/sample", Collections.singletonList(mimetype.split("/")[1])); }}; Mockito.when(contentReader.getContentInputStream()).thenReturn( @@ -61,7 +51,7 @@ void verifyMimetypeByMagicBytes() throws UnsupportedEncodingException { filename, allowListWrongMimetype, false)); - HashMap> allowListWrongFileExtension = new HashMap>() {{ + Map> allowListWrongFileExtension = new HashMap<>() {{ put(mimetype, Collections.singletonList("wrong")); }}; Mockito.when(contentReader.getContentInputStream()).thenReturn( @@ -96,4 +86,4 @@ void verifyMimetypeUnknown() { }}, true)); } -} \ No newline at end of file +} diff --git a/Backend/services/core/src/main/java/org/alfresco/repo/webdav/Edu_SharingPropFindMethod.java b/Backend/services/core/src/main/java/org/alfresco/repo/webdav/Edu_SharingPropFindMethod.java index ad1879505f..e1e25b2200 100644 --- a/Backend/services/core/src/main/java/org/alfresco/repo/webdav/Edu_SharingPropFindMethod.java +++ b/Backend/services/core/src/main/java/org/alfresco/repo/webdav/Edu_SharingPropFindMethod.java @@ -91,14 +91,14 @@ public class Edu_SharingPropFindMethod extends WebDAVMethod protected ArrayList m_properties = null; // Available namespaces list - protected HashMap m_namespaces = null; + protected Map m_namespaces = null; /** * Default constructor */ public Edu_SharingPropFindMethod() { - m_namespaces = new HashMap(); + m_namespaces = new HashMap<>(); } /** @@ -166,7 +166,7 @@ else if (currentNode.getNodeName().endsWith(WebDAV.XML_PROPNAME)) if (m_mode == GET_NAMED_PROPS) { - m_properties = new ArrayList(); + m_properties = new ArrayList<>(); childList = node.getChildNodes(); for (int i = 0; i < childList.getLength(); i++) @@ -256,7 +256,7 @@ protected void executeImpl() throws WebDAVServerException, Exception if (getDepth() != WebDAV.DEPTH_0 && pathNodeInfo.isFolder()) { // Create the initial list of nodes to report - List nodeInfos = new ArrayList(10); + List nodeInfos = new ArrayList<>(10); nodeInfos.add(pathNodeInfo); int curDepth = WebDAV.DEPTH_1; @@ -268,7 +268,7 @@ protected void executeImpl() throws WebDAVServerException, Exception List nextNodeInfos = null; if (getDepth() > WebDAV.DEPTH_1) { - nextNodeInfos = new ArrayList(10); + nextNodeInfos = new ArrayList<>(10); } // Loop reporting each level of nodes to the requested depth @@ -474,7 +474,7 @@ private void generateNamedPropertiesResponse(XMLWriter xml, FileInfo nodeInfo, b xml.startElement(WebDAV.DAV_NS, WebDAV.XML_PROPSTAT, WebDAV.XML_NS_PROPSTAT, nullAttr); xml.startElement(WebDAV.DAV_NS, WebDAV.XML_PROP, WebDAV.XML_NS_PROP, nullAttr); - ArrayList propertiesNotFound = new ArrayList(); + ArrayList propertiesNotFound = new ArrayList<>(); TypeConverter typeConv = DefaultTypeConverter.INSTANCE; @@ -1014,7 +1014,7 @@ protected Map loadDeadProperties(NodeRef nodeRef) if (deadProperties != null) { - result = new HashMap(deadProperties.size() * 2); + result = new HashMap<>(deadProperties.size() * 2); for (String deadProperty : deadProperties) { @@ -1041,7 +1041,7 @@ protected Map loadDeadProperties(NodeRef nodeRef) } else { - result = new HashMap(7); + result = new HashMap<>(7); } return result; @@ -1055,7 +1055,7 @@ protected Map loadDeadProperties(NodeRef nodeRef) */ protected void persistDeadProperties(NodeRef nodeRef, Map deadProperties) { - List listToPersist = new ArrayList(deadProperties.size()); + List listToPersist = new ArrayList<>(deadProperties.size()); for (Map.Entry entry: deadProperties.entrySet()) { diff --git a/Backend/services/core/src/main/java/org/alfresco/repo/webdav/GetMethod.java b/Backend/services/core/src/main/java/org/alfresco/repo/webdav/GetMethod.java index 9510a3c682..5da06c344d 100644 --- a/Backend/services/core/src/main/java/org/alfresco/repo/webdav/GetMethod.java +++ b/Backend/services/core/src/main/java/org/alfresco/repo/webdav/GetMethod.java @@ -457,7 +457,7 @@ private void checkPreConditions(FileInfo nodeInfo) throws WebDAVServerException */ private ArrayList parseETags(String strETagHeader) { - ArrayList list = new ArrayList(); + ArrayList list = new ArrayList<>(); StringTokenizer tokenizer = new StringTokenizer(strETagHeader, WebDAV.HEADER_VALUE_SEPARATOR); while (tokenizer.hasMoreTokens()) diff --git a/Backend/services/core/src/main/java/org/alfresco/repo/webdav/LockMethod.java b/Backend/services/core/src/main/java/org/alfresco/repo/webdav/LockMethod.java index ec74e4b8c9..d30aa7229d 100644 --- a/Backend/services/core/src/main/java/org/alfresco/repo/webdav/LockMethod.java +++ b/Backend/services/core/src/main/java/org/alfresco/repo/webdav/LockMethod.java @@ -527,7 +527,7 @@ protected void generateResponse(FileInfo lockNodeInfo, String userName) throws E /** * Generates a list of namespace declarations for the response */ - protected String generateNamespaceDeclarations(HashMap nameSpaces) + protected String generateNamespaceDeclarations(Map nameSpaces) { StringBuilder ns = new StringBuilder(); diff --git a/Backend/services/core/src/main/java/org/alfresco/repo/webdav/PropFindMethod.java b/Backend/services/core/src/main/java/org/alfresco/repo/webdav/PropFindMethod.java index 1a70966218..7fdcd597cf 100644 --- a/Backend/services/core/src/main/java/org/alfresco/repo/webdav/PropFindMethod.java +++ b/Backend/services/core/src/main/java/org/alfresco/repo/webdav/PropFindMethod.java @@ -72,14 +72,14 @@ public class PropFindMethod extends WebDAVMethod protected ArrayList m_properties = null; // Available namespaces list - protected HashMap m_namespaces = null; + protected Map m_namespaces = null; /** * Default constructor */ public PropFindMethod() { - m_namespaces = new HashMap(); + m_namespaces = new HashMap<>(); } /** @@ -147,7 +147,7 @@ else if (currentNode.getNodeName().endsWith(WebDAV.XML_PROPNAME)) if (m_mode == GET_NAMED_PROPS) { - m_properties = new ArrayList(); + m_properties = new ArrayList<>(); childList = node.getChildNodes(); for (int i = 0; i < childList.getLength(); i++) @@ -237,7 +237,7 @@ protected void executeImpl() throws WebDAVServerException, Exception if (getDepth() != WebDAV.DEPTH_0 && pathNodeInfo.isFolder()) { // Create the initial list of nodes to report - List nodeInfos = new ArrayList(10); + List nodeInfos = new ArrayList<>(10); nodeInfos.add(pathNodeInfo); int curDepth = WebDAV.DEPTH_1; @@ -249,7 +249,7 @@ protected void executeImpl() throws WebDAVServerException, Exception List nextNodeInfos = null; if (getDepth() > WebDAV.DEPTH_1) { - nextNodeInfos = new ArrayList(10); + nextNodeInfos = new ArrayList<>(10); } // Loop reporting each level of nodes to the requested depth @@ -448,7 +448,7 @@ private void generateNamedPropertiesResponse(XMLWriter xml, FileInfo nodeInfo, b xml.startElement(WebDAV.DAV_NS, WebDAV.XML_PROPSTAT, WebDAV.XML_NS_PROPSTAT, nullAttr); xml.startElement(WebDAV.DAV_NS, WebDAV.XML_PROP, WebDAV.XML_NS_PROP, nullAttr); - ArrayList propertiesNotFound = new ArrayList(); + ArrayList propertiesNotFound = new ArrayList<>(); TypeConverter typeConv = DefaultTypeConverter.INSTANCE; @@ -970,7 +970,7 @@ protected Map loadDeadProperties(NodeRef nodeRef) if (deadProperties != null) { - result = new HashMap(deadProperties.size() * 2); + result = new HashMap<>(deadProperties.size() * 2); for (String deadProperty : deadProperties) { @@ -997,7 +997,7 @@ protected Map loadDeadProperties(NodeRef nodeRef) } else { - result = new HashMap(7); + result = new HashMap<>(7); } return result; @@ -1011,7 +1011,7 @@ protected Map loadDeadProperties(NodeRef nodeRef) */ protected void persistDeadProperties(NodeRef nodeRef, Map deadProperties) { - List listToPersist = new ArrayList(deadProperties.size()); + List listToPersist = new ArrayList<>(deadProperties.size()); for (Map.Entry entry: deadProperties.entrySet()) { diff --git a/Backend/services/core/src/main/java/org/alfresco/repo/webdav/PropPatchMethod.java b/Backend/services/core/src/main/java/org/alfresco/repo/webdav/PropPatchMethod.java index f0b7e274ce..6aff8b1000 100644 --- a/Backend/services/core/src/main/java/org/alfresco/repo/webdav/PropPatchMethod.java +++ b/Backend/services/core/src/main/java/org/alfresco/repo/webdav/PropPatchMethod.java @@ -168,7 +168,7 @@ protected void parseRequestBody() throws WebDAVServerException Element rootElement = body.getDocumentElement(); NodeList childList = rootElement.getChildNodes(); - m_propertyActions = new ArrayList(); + m_propertyActions = new ArrayList<>(); for (int i = 0; i < childList.getLength(); i++) { diff --git a/Backend/services/core/src/main/java/org/alfresco/repo/webdav/WebDAVHelper.java b/Backend/services/core/src/main/java/org/alfresco/repo/webdav/WebDAVHelper.java index 7ae1e0a0ab..d5d8471b50 100644 --- a/Backend/services/core/src/main/java/org/alfresco/repo/webdav/WebDAVHelper.java +++ b/Backend/services/core/src/main/java/org/alfresco/repo/webdav/WebDAVHelper.java @@ -475,7 +475,7 @@ public List splitAllPaths(String path) // split the path StringTokenizer token = new StringTokenizer(path, PathSeperator); - List results = new ArrayList(10); + List results = new ArrayList<>(10); while (token.hasMoreTokens()) { results.add(token.nextToken()); diff --git a/Backend/services/core/src/main/java/org/alfresco/repo/webdav/WebDAVMethod.java b/Backend/services/core/src/main/java/org/alfresco/repo/webdav/WebDAVMethod.java index 168ed53838..5a11f5a772 100644 --- a/Backend/services/core/src/main/java/org/alfresco/repo/webdav/WebDAVMethod.java +++ b/Backend/services/core/src/main/java/org/alfresco/repo/webdav/WebDAVMethod.java @@ -90,7 +90,7 @@ public abstract class WebDAVMethod // Mapping of User-Agent pattern to response status code // used to determine which status code should be returned for AccessDeniedException - private static final Map accessDeniedStatusCodes = new LinkedHashMap(); + private static final Map accessDeniedStatusCodes = new LinkedHashMap<>(); static { accessDeniedStatusCodes.put("^WebDAVLib/" + VERSION_NUM_PATTERN + "$", @@ -139,8 +139,8 @@ public abstract class WebDAVMethod protected int m_depth = WebDAV.DEPTH_INFINITY; // request scope - protected Map m_childToParent = new HashMap(); - protected Map m_parentLockInfo = new HashMap(); + protected Map m_childToParent = new HashMap<>(); + protected Map m_parentLockInfo = new HashMap<>(); private String siteId; @@ -978,7 +978,7 @@ protected void generateLockDiscoveryXML(XMLWriter xml, FileInfo lockNodeInfo, bo /** * Generates a list of namespace declarations for the response */ - protected String generateNamespaceDeclarations(HashMap nameSpaces) + protected String generateNamespaceDeclarations(Map nameSpaces) { StringBuilder ns = new StringBuilder(); diff --git a/Backend/services/core/src/main/java/org/alfresco/repo/webdav/auth/LDAPAuthenticationFilter.java b/Backend/services/core/src/main/java/org/alfresco/repo/webdav/auth/LDAPAuthenticationFilter.java index 1d1de1bd63..24415bba2c 100644 --- a/Backend/services/core/src/main/java/org/alfresco/repo/webdav/auth/LDAPAuthenticationFilter.java +++ b/Backend/services/core/src/main/java/org/alfresco/repo/webdav/auth/LDAPAuthenticationFilter.java @@ -124,7 +124,7 @@ public class LDAPAuthenticationFilter implements Filter, DependencyInjectedFilte static { - Map decoders = new LinkedHashMap(ENCODINGS.length * 2); + Map decoders = new LinkedHashMap<>(ENCODINGS.length * 2); for (String encoding : ENCODINGS) { if (!decoders.containsKey(encoding)) diff --git a/Backend/services/core/src/main/java/org/edu_sharing/metadataset/v2/tools/MetadataHelper.java b/Backend/services/core/src/main/java/org/edu_sharing/metadataset/v2/tools/MetadataHelper.java index bdd80d74f0..de259fbdf5 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/metadataset/v2/tools/MetadataHelper.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/metadataset/v2/tools/MetadataHelper.java @@ -102,7 +102,7 @@ public static boolean checkConditionTrue(MetadataCondition condition) { * attach any available translations/display names for keys of a given property set and attach them with the postfix DISPLAYNAME in this set * The current locale will be used */ - public static void addVirtualDisplaynameProperties(MetadataSet mds, HashMap props) { + public static void addVirtualDisplaynameProperties(MetadataSet mds, Map props) { for(MetadataWidget widget: mds.getWidgets()) { Map values = widget.getValuesAsMap(); String id = CCConstants.getValidGlobalName(widget.getId()); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/metadataset/v2/tools/MetadataTemplateRenderer.java b/Backend/services/core/src/main/java/org/edu_sharing/metadataset/v2/tools/MetadataTemplateRenderer.java index 116535d341..872adb031d 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/metadataset/v2/tools/MetadataTemplateRenderer.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/metadataset/v2/tools/MetadataTemplateRenderer.java @@ -45,7 +45,7 @@ */ public class MetadataTemplateRenderer { - private final HashMap propertiesNative; + private final Map propertiesNative; public enum RenderingMode{ HTML, @@ -81,8 +81,8 @@ public MetadataTemplateRenderer(MetadataSet mds, NodeRef nodeRef, String userNam public Map getProcessedProperties(){ return this.properties; } - public static HashMap convertProps(Map props) { - HashMap propsConverted = new HashMap<>(); + public static Map convertProps(Map props) { + Map propsConverted = new HashMap<>(); for(String key : props.keySet()){ String keyLocal= CCConstants.getValidLocalName(key); @@ -212,9 +212,9 @@ private String renderTemplate(MetadataTemplate template) throws IllegalArgumentE int i = 0; for (String value : values) { String rawValue = value; - HashMap vcardData = null; + Map vcardData = null; if ("vcard".equals(widget.getType())) { - ArrayList> map = VCardConverter.vcardToHashMap( + ArrayList> map = VCardConverter.vcardToMap( // html in vcards gets escaped beforehand for security reason, unescape special chars to not break the format org.apache.commons.lang.StringEscapeUtils.unescapeHtml(value) ); @@ -621,8 +621,8 @@ public static Map cleanupTextProperties(MetadataSetV2 mds, Map cleanupTextMultivalueProperties(Map properties, boolean htmlMode) { - HashMap cleaned=new HashMap<>(); + public Map cleanupTextMultivalueProperties(Map properties, boolean htmlMode) { + Map cleaned=new HashMap<>(); for(Map.Entry entry : properties.entrySet()){ if(entry.getValue()==null) { cleaned.put(entry.getKey(), null); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/client/exception/CCException.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/client/exception/CCException.java index effba159d7..16538742f8 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/client/exception/CCException.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/client/exception/CCException.java @@ -29,6 +29,7 @@ import java.io.Serializable; import java.util.HashMap; +import java.util.Map; public class CCException extends Exception implements Serializable { @@ -75,7 +76,7 @@ public class CCException extends Exception implements Serializable { public static String SHARE_SERVICE_NOPERMISSIONS = "SHARE_SERVICE_NOPERMISSIONS"; public static String SHARE_SERVICE_EXPIRYDATETOOLD = "SHARE_SERVICE_EXPIRYDATETOOLD"; - HashMap messageParams = new HashMap(); + Map messageParams = new HashMap<>(); String id = null; @@ -109,7 +110,7 @@ public void setMessageParam(String key,String val){ messageParams.put(key, val); } - public HashMap getMessageParams() { + public Map getMessageParams() { return messageParams; } } diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/client/rpc/RepositoryInfo.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/client/rpc/RepositoryInfo.java index 697a37d10b..046fd738da 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/client/rpc/RepositoryInfo.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/client/rpc/RepositoryInfo.java @@ -29,6 +29,7 @@ import java.io.Serializable; import java.util.HashMap; +import java.util.Map; /** * @author rudolph @@ -38,7 +39,7 @@ public class RepositoryInfo implements Serializable { /** * repositoryId, repository Properties */ - HashMap> repInfoMap; + Map> repInfoMap; /** * Help URLs @@ -57,14 +58,14 @@ public RepositoryInfo() { /** * @return the repInfoMap */ - public HashMap> getRepInfoMap() { + public Map> getRepInfoMap() { return repInfoMap; } /** * @param repInfoMap the repInfoMap to set */ - public void setRepInfoMap(HashMap> repInfoMap) { + public void setRepInfoMap(Map> repInfoMap) { this.repInfoMap = repInfoMap; } diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/client/rpc/SchoolContextValues.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/client/rpc/SchoolContextValues.java index 1b85509db1..11be237f69 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/client/rpc/SchoolContextValues.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/client/rpc/SchoolContextValues.java @@ -2,16 +2,17 @@ import java.io.Serializable; import java.util.HashMap; +import java.util.Map; public class SchoolContextValues implements Serializable{ Boolean resultBasedOnCombination = false; - HashMap federalState = new HashMap(); - HashMap typeOfSchool = new HashMap(); - HashMap schoolSubject = new HashMap(); - HashMap ageGroup = new HashMap(); - HashMap topic = new HashMap(); + Map federalState = new HashMap<>(); + Map typeOfSchool = new HashMap<>(); + Map schoolSubject = new HashMap<>(); + Map ageGroup = new HashMap<>(); + Map topic = new HashMap<>(); public SchoolContextValues() { } @@ -20,7 +21,7 @@ public SchoolContextValues() { * * @return */ - public HashMap getFederalState() { + public Map getFederalState() { return federalState; } @@ -28,7 +29,7 @@ public HashMap getFederalState() { * * @return */ - public HashMap getTypeOfSchool() { + public Map getTypeOfSchool() { return typeOfSchool; } @@ -36,7 +37,7 @@ public HashMap getTypeOfSchool() { * * @return */ - public HashMap getSchoolSubject() { + public Map getSchoolSubject() { return schoolSubject; } @@ -44,7 +45,7 @@ public HashMap getSchoolSubject() { * * @return */ - public HashMap getAgeGroup() { + public Map getAgeGroup() { return ageGroup; } @@ -52,7 +53,7 @@ public HashMap getAgeGroup() { * * @return */ - public HashMap getTopic() { + public Map getTopic() { return topic; } diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/client/rpc/SearchResult.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/client/rpc/SearchResult.java index f0d23d6554..fd7c425831 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/client/rpc/SearchResult.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/client/rpc/SearchResult.java @@ -32,7 +32,7 @@ import java.util.HashMap; import java.util.Map; -public class SearchResult extends Result>>{ +public class SearchResult extends Result>>{ Map> countedProps = null; @@ -42,15 +42,15 @@ public SearchResult(){ } - public HashMap> getData() { + public Map> getData() { return data; } - public void setData(HashMap> data) { + public void setData(Map> data) { this.data = data; } /** - * HashMap> + * Map> * @return */ public Map> getCountedProps() { diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/client/rpc/SearchToken.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/client/rpc/SearchToken.java index 072b0f2b4f..5c92688cf3 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/client/rpc/SearchToken.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/client/rpc/SearchToken.java @@ -32,6 +32,7 @@ import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; +import java.util.Map; public class SearchToken implements Serializable { //private String query = ""; @@ -54,7 +55,7 @@ public class SearchToken implements Serializable { /** * */ - private HashMap countPropsSubString = null; + private Map countPropsSubString = null; private SearchCriterias searchCriterias = null; @@ -104,7 +105,7 @@ public ArrayList getCountProps() { return countProps; } - public HashMap getCountPropsSubString() { + public Map getCountPropsSubString() { return countPropsSubString; } @@ -118,7 +119,7 @@ public HashMap getCountPropsSubString() { * * @param countPropsSubString */ - public void setCountPropsSubString(HashMap countPropsSubString) { + public void setCountPropsSubString(Map countPropsSubString) { this.countPropsSubString = countPropsSubString; } diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/client/rpc/SetPermissionsAndMail.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/client/rpc/SetPermissionsAndMail.java index 06d00c02bc..b2771dc76a 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/client/rpc/SetPermissionsAndMail.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/client/rpc/SetPermissionsAndMail.java @@ -29,13 +29,14 @@ import java.io.Serializable; import java.util.HashMap; +import java.util.Map; public class SetPermissionsAndMail implements Serializable { String nodeId = null; // - HashMap authPerm = null; + Map authPerm = null; Boolean inheritPermissions = null; @@ -80,14 +81,14 @@ public void setNodeId(String nodeId) { /** * @return the authPerm */ - public HashMap getAuthPerm() { + public Map getAuthPerm() { return authPerm; } /** * @param authPerm the authPerm to set */ - public void setAuthPerm(HashMap authPerm) { + public void setAuthPerm(Map authPerm) { this.authPerm = authPerm; } diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/client/tools/MimeTypes.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/client/tools/MimeTypes.java index 6ecd3504f7..f19bb4d32b 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/client/tools/MimeTypes.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/client/tools/MimeTypes.java @@ -61,7 +61,7 @@ public class MimeTypes { //private static final Object[] allMime = {mime_doc, mime_pic, mime_audio, mime_video}; - static HashMap extensionMimeMap = null; + static Map extensionMimeMap = null; String basePath; @@ -111,10 +111,10 @@ public static String getAsString(Object[] wishlist){ return result; } - public static HashMap getExtensionMimeMap() { + public static Map getExtensionMimeMap() { if(extensionMimeMap == null){ - extensionMimeMap = new HashMap(); + extensionMimeMap = new HashMap<>(); extensionMimeMap.put("jpg", "image/jpeg"); extensionMimeMap.put("jpeg", "image/jpeg"); extensionMimeMap.put("png", "image/png"); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/client/tools/UrlTool.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/client/tools/UrlTool.java index 970246ac36..48026fb004 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/client/tools/UrlTool.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/client/tools/UrlTool.java @@ -83,7 +83,7 @@ public static String removeParam(String url, String param){ if(!queryPart.contains(param)) return url; String[] params = queryPart.split("\\&"); - List newParams = new ArrayList(); + List newParams = new ArrayList<>(); for(String p : params){ if(!p.contains(param)){ newParams.add(p); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/client/tools/metadata/ValueTool.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/client/tools/metadata/ValueTool.java index 3318cf50fa..4935327bd4 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/client/tools/metadata/ValueTool.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/client/tools/metadata/ValueTool.java @@ -31,7 +31,6 @@ import org.edu_sharing.repository.client.tools.CCConstants; import java.util.Arrays; -import java.util.HashMap; import java.util.List; import java.util.Map; @@ -50,7 +49,7 @@ public static String[] getMultivalue(String mvValue){ public static String toMultivalue(String[] multivalue){ return StringUtils.join(multivalue,CCConstants.MULTIVALUE_SEPARATOR); } - public static HashMap getMultivalue(HashMap data){ + public static Map getMultivalue(Map data){ for(Map.Entry entry : data.entrySet()) { if(entry.getValue() instanceof String) { List list = Arrays.asList(StringUtils.splitByWholeSeparator((String) entry.getValue(), CCConstants.MULTIVALUE_SEPARATOR)); @@ -61,7 +60,7 @@ public static HashMap getMultivalue(HashMap data } return data; } - public static HashMap toMultivalue(HashMap data){ + public static Map toMultivalue(Map data){ for(Map.Entry entry : data.entrySet()) { if(entry.getValue() instanceof Iterable) { if(((Iterable) entry.getValue()).iterator().hasNext() && ((Iterable) entry.getValue()).iterator().next() instanceof String) { diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/AuthenticationTool.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/AuthenticationTool.java index 50a6238cbe..3ce8c2761b 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/AuthenticationTool.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/AuthenticationTool.java @@ -27,12 +27,12 @@ */ package org.edu_sharing.repository.server; -import java.util.HashMap; +import java.util.Map; import jakarta.servlet.http.HttpSession; public interface AuthenticationTool { - public HashMap createNewSession(String userName, String password) throws Exception; + Map createNewSession(String userName, String password) throws Exception; /** * username and ticket are stored in a ThreadLocal variable in Both implementations API and WS Client @@ -43,9 +43,9 @@ public interface AuthenticationTool { * @return * @throws Exception */ - public HashMap getUserInfo(String userName, String ticket) throws Exception; + Map getUserInfo(String userName, String ticket) throws Exception; - public void logout(String ticket); + void logout(String ticket); /** * @@ -59,7 +59,7 @@ public interface AuthenticationTool { * @param ticket * @param session */ - public void storeAuthInfoInSession(String username, String ticket, String authType, HttpSession session); + void storeAuthInfoInSession(String username, String ticket, String authType, HttpSession session); /** * returns validated AuthenticationInfo @@ -67,26 +67,26 @@ public interface AuthenticationTool { * @param session * @return */ - public HashMap validateAuthentication(HttpSession session); + Map validateAuthentication(HttpSession session); /** * returns AuthenticationInfo without validation * @param session * @return */ - public HashMap getAuthentication(HttpSession session); + Map getAuthentication(HttpSession session); /** * * @param session * @return */ - public String getTicketFromSession(HttpSession session); + String getTicketFromSession(HttpSession session); /** * * @param ticket * @return */ - public boolean validateTicket(String ticket); + boolean validateTicket(String ticket); } diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/AuthenticationToolAPI.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/AuthenticationToolAPI.java index 86d6deba3c..711386158e 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/AuthenticationToolAPI.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/AuthenticationToolAPI.java @@ -28,6 +28,7 @@ package org.edu_sharing.repository.server; import java.util.HashMap; +import java.util.Map; import jakarta.servlet.http.HttpSession; @@ -77,10 +78,10 @@ public AuthenticationToolAPI() { public AuthenticationToolAPI(String appId) { } - public java.util.HashMap createNewSession(String userName, String password) throws Exception { + public Map createNewSession(String userName, String password) throws Exception { authenticationService.authenticate(userName, password.toCharArray()); - HashMap returnval = new HashMap(); + Map returnval = new HashMap<>(); returnval.put(CCConstants.AUTH_USERNAME, authenticationService.getCurrentUserName()); returnval.put(CCConstants.AUTH_TICKET, authenticationService.getCurrentTicket()); @@ -95,9 +96,9 @@ public java.util.HashMap createNewSession(String userName, String }; @Override - public HashMap getUserInfo(String userName, String ticket) throws Exception { + public Map getUserInfo(String userName, String ticket) throws Exception { serviceRegistry.getAuthenticationService().validate(ticket); - HashMap returnval = new HashMap(); + Map returnval = new HashMap<>(); returnval.put(CCConstants.AUTH_USERNAME, authenticationService.getCurrentUserName()); returnval.put(CCConstants.AUTH_TICKET, authenticationService.getCurrentTicket()); @@ -118,10 +119,10 @@ public String getScope(){ return (String)session.getAttribute(CCConstants.AUTH_SCOPE); } - private void addClientUserInfo(HashMap authInfo) throws Exception{ + private void addClientUserInfo(Map authInfo) throws Exception{ MCAlfrescoAPIClient mcAlfrescoAPIClient = new MCAlfrescoAPIClient(authInfo); - HashMap repositoryUseInfo = mcAlfrescoAPIClient.getUserInfo(authenticationService.getCurrentUserName()); + Map repositoryUseInfo = mcAlfrescoAPIClient.getUserInfo(authenticationService.getCurrentUserName()); String userNameCaption = repositoryUseInfo.get(CCConstants.CM_PROP_PERSON_EMAIL); if(userNameCaption == null || userNameCaption.trim().equals("")) userNameCaption = authInfo.get(CCConstants.AUTH_USERNAME); @@ -181,10 +182,10 @@ public Void doWork() throws Exception { * - ticket and user name will be returned * * @param session - * @return null when no valid ticket was found else user name / ticket as HashMap + * @return null when no valid ticket was found else user name / ticket as Map */ - public HashMap validateAuthentication(HttpSession session){ - HashMap result = null; + public Map validateAuthentication(HttpSession session){ + Map result = null; String currentTicket = (String)session.getAttribute(CCConstants.AUTH_TICKET); if(currentTicket != null){ try{ @@ -234,7 +235,7 @@ public void storeAuthInfoInSession(String username, String ticket, String authTy //ToolPermissionServiceFactory.getInstance().getAllAvailableToolPermissions(); try { - HashMap userInfo = getUserInfo(authenticationService.getCurrentUserName(), ticket); + Map userInfo = getUserInfo(authenticationService.getCurrentUserName(), ticket); session.setAttribute(CCConstants.AUTH_USERNAME_CAPTION, userInfo.get(CCConstants.AUTH_USERNAME_CAPTION)); }catch(Exception e) { diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/AuthenticationToolAbstract.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/AuthenticationToolAbstract.java index 4f00fb3d0a..3e6dea12b7 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/AuthenticationToolAbstract.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/AuthenticationToolAbstract.java @@ -44,8 +44,8 @@ public String getTicketFromSession(HttpSession session) { } @Override - public HashMap getAuthentication(HttpSession session) { - HashMap result = new HashMap(); + public Map getAuthentication(HttpSession session) { + Map result = new HashMap<>(); String currentTicket = (String)session.getAttribute(CCConstants.AUTH_TICKET); String userName = (String)session.getAttribute(CCConstants.AUTH_USERNAME); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/AuthenticationToolWikimedia.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/AuthenticationToolWikimedia.java index 643893c3f7..dd419c1f11 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/AuthenticationToolWikimedia.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/AuthenticationToolWikimedia.java @@ -1,6 +1,7 @@ package org.edu_sharing.repository.server; import java.util.HashMap; +import java.util.Map; import jakarta.servlet.http.HttpSession; @@ -12,12 +13,12 @@ public AuthenticationToolWikimedia(String repId){ } @Override - public HashMap createNewSession(String userName, String password) throws Exception { + public Map createNewSession(String userName, String password) throws Exception { return null; } @Override - public HashMap getUserInfo(String userName, String ticket) throws Exception { + public Map getUserInfo(String userName, String ticket) throws Exception { return null; } @@ -26,8 +27,8 @@ public void logout(String ticket) { } @Override - public HashMap validateAuthentication(HttpSession session) { - HashMap authInfo = new HashMap(); + public Map validateAuthentication(HttpSession session) { + Map authInfo = new HashMap<>(); authInfo.put(CCConstants.AUTH_USERNAME, "wikimedia"); authInfo.put(CCConstants.AUTH_TICKET, "wikimedia"); return authInfo; diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/AuthenticationToolYouTube.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/AuthenticationToolYouTube.java index db9b4517d9..c2f809665e 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/AuthenticationToolYouTube.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/AuthenticationToolYouTube.java @@ -1,6 +1,7 @@ package org.edu_sharing.repository.server; import java.util.HashMap; +import java.util.Map; import jakarta.servlet.http.HttpSession; @@ -12,12 +13,12 @@ public AuthenticationToolYouTube(String repId){ } @Override - public HashMap createNewSession(String userName, String password) throws Exception { + public Map createNewSession(String userName, String password) throws Exception { return null; } @Override - public HashMap getUserInfo(String userName, String ticket) throws Exception { + public Map getUserInfo(String userName, String ticket) throws Exception { return null; } @@ -26,8 +27,8 @@ public void logout(String ticket) { } @Override - public HashMap validateAuthentication(HttpSession session) { - HashMap authInfo = new HashMap(); + public Map validateAuthentication(HttpSession session) { + Map authInfo = new HashMap<>(); authInfo.put(CCConstants.AUTH_USERNAME, "youtube"); authInfo.put(CCConstants.AUTH_TICKET, "youtube"); return authInfo; diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/CCConfirmActivation.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/CCConfirmActivation.java index e56d81625f..f17de94560 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/CCConfirmActivation.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/CCConfirmActivation.java @@ -103,11 +103,11 @@ protected void doGet(HttpServletRequest request, HttpServletResponse resp) throw try { AuthenticationTool authTool = RepoFactory.getAuthenticationToolInstance(homeRepository.getAppId()); - HashMap authInfo = authTool.createNewSession(adminUn, password); + Map authInfo = authTool.createNewSession(adminUn, password); MCAlfrescoBaseClient mcAlfrescoBaseClient = (MCAlfrescoBaseClient) RepoFactory.getInstance(null, authInfo); - HashMap> userResult = mcAlfrescoBaseClient.search("@cm\\:userName:" + repositoryUsername); + Map> userResult = mcAlfrescoBaseClient.search("@cm\\:userName:" + repositoryUsername); if(userResult.size() > 0){ if(userResult.size() > 1){ @@ -115,13 +115,13 @@ protected void doGet(HttpServletRequest request, HttpServletResponse resp) throw log.error("UserId:" + repositoryUsername + " is used by more than one users. This is not allowed!!!"); return; }else{ - HashMap userProps = userResult.get(userResult.keySet().iterator().next()); + Map userProps = userResult.get(userResult.keySet().iterator().next()); String nodeId = (String)userProps.get(CCConstants.SYS_PROP_NODE_UID); - HashMap> childMap = mcAlfrescoBaseClient.getChildrenByType(nodeId, + Map> childMap = mcAlfrescoBaseClient.getChildrenByType(nodeId, CCConstants.CM_TYPE_PERSONACCESSELEMENT); - for (Map.Entry> entry : childMap.entrySet()) { - HashMap childProps = entry.getValue(); + for (Map.Entry> entry : childMap.entrySet()) { + Map childProps = entry.getValue(); String tmpAppId = (String) childProps.get(CCConstants.CM_PROP_PERSONACCESSELEMENT_CCAPPID); String tmpappUserId = (String) childProps.get(CCConstants.CM_PROP_PERSONACCESSELEMENT_CCUSERID); String tmpActivateKey = (String) childProps.get(CCConstants.CM_PROP_PERSONACCESSELEMENT_CCACTIVATEKEY); @@ -135,7 +135,7 @@ protected void doGet(HttpServletRequest request, HttpServletResponse resp) throw // one retrieved by getChildrenByType // cause there are properties that are not part // of the type definition - HashMap propsToSafe = new HashMap(); + Map propsToSafe = new HashMap<>(); propsToSafe.put(CCConstants.CM_PROP_PERSONACCESSELEMENT_CCAPPID, tmpAppId); propsToSafe.put(CCConstants.CM_PROP_PERSONACCESSELEMENT_CCUSERID, tmpappUserId); propsToSafe.put(CCConstants.CM_PROP_PERSONACCESSELEMENT_CCACTIVATEKEY, tmpActivateKey); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/DownloadServlet.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/DownloadServlet.java index 0dada1c75a..5a4931d3e8 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/DownloadServlet.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/DownloadServlet.java @@ -43,10 +43,7 @@ import org.springframework.web.servlet.support.RequestContextUtils; import java.io.*; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.List; +import java.util.*; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; @@ -429,7 +426,7 @@ private static MetadataTemplateRenderer getMetadataRenderer(NodeRef nodeRef) thr // inherit the props so childobjects will get all properties // only local nodes are supported right now NodeDao nodeDao = NodeDao.getNode(RepositoryDao.getHomeRepository(), nodeRef.getId()); - HashMap props = nodeDao.getInheritedPropertiesFromParent(); + Map props = nodeDao.getInheritedPropertiesFromParent(); MetadataTemplateRenderer render = new MetadataTemplateRenderer( MetadataHelper.getMetadataset(nodeRef), nodeRef diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/ExcelImportServlet.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/ExcelImportServlet.java index 3571627893..ccd42fafa4 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/ExcelImportServlet.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/ExcelImportServlet.java @@ -3,6 +3,7 @@ import java.io.IOException; import java.util.HashMap; import java.util.List; +import java.util.Map; import jakarta.servlet.ServletException; import jakarta.servlet.ServletOutputStream; @@ -38,7 +39,7 @@ protected void doPost(HttpServletRequest request, HttpServletResponse resp) thro JakartaServletFileUpload upload = new JakartaServletFileUpload(factory); - HashMap authInfo = new AuthenticationToolAPI().validateAuthentication(request.getSession()); + Map authInfo = new AuthenticationToolAPI().validateAuthentication(request.getSession()); if(authInfo == null){ logger.error("not authenticated"); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/FolderTemplateServlet.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/FolderTemplateServlet.java index c8cdf32f74..c0d5c2b5af 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/FolderTemplateServlet.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/FolderTemplateServlet.java @@ -39,7 +39,7 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws Se String homeAppId = ApplicationInfoList.getHomeRepository().getAppId(); AuthenticationTool authTool = RepoFactory.getAuthenticationToolInstance(homeAppId); - // HashMap authInfo = authTool.createNewSession(userName, password); + // Map authInfo = authTool.createNewSession(userName, password); MCAlfrescoBaseClient baseclient = (MCAlfrescoBaseClient)RepoFactory.getInstance(homeAppId, req.getSession()); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/MCAlfrescoAPIClient.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/MCAlfrescoAPIClient.java index 370300e357..b76921a761 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/MCAlfrescoAPIClient.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/MCAlfrescoAPIClient.java @@ -1,34 +1,11 @@ /** - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * * */ package org.edu_sharing.repository.server; import com.google.common.base.CharMatcher; import jakarta.transaction.UserTransaction; +import lombok.extern.slf4j.Slf4j; import net.sf.acegisecurity.AuthenticationCredentialsNotFoundException; import org.alfresco.error.AlfrescoRuntimeException; import org.alfresco.model.ContentModel; @@ -128,491 +105,490 @@ import java.util.function.Consumer; import java.util.stream.Collectors; +@Slf4j public class MCAlfrescoAPIClient extends MCAlfrescoBaseClient { - private static Logger logger = Logger.getLogger(MCAlfrescoAPIClient.class); + private static ApplicationContext applicationContext = null; + private final UserCache userCache; - private static ApplicationContext applicationContext = null; - private final UserCache userCache; + private ServiceRegistry serviceRegistry = null; - private ServiceRegistry serviceRegistry = null; + private NodeService nodeService = null; - private NodeService nodeService = null; + private ContentService contentService = null; - private ContentService contentService = null; + private AuthorityService authorityService = null; - private AuthorityService authorityService = null; + private SearchService searchService = null; - private SearchService searchService = null; + private NamespaceService namespaceService = null; - private NamespaceService namespaceService = null; + private PersonService personService; - private PersonService personService; + private DictionaryService dictionaryService; - private DictionaryService dictionaryService; + org.edu_sharing.alfresco.service.AuthorityService eduAuthorityService; - org.edu_sharing.alfresco.service.AuthorityService eduAuthorityService; + org.edu_sharing.alfresco.service.OrganisationService eduOrganisationService; - org.edu_sharing.alfresco.service.OrganisationService eduOrganisationService; + public final static StoreRef storeRef = new StoreRef(StoreRef.PROTOCOL_WORKSPACE, "SpacesStore"); - public final static StoreRef storeRef = new StoreRef(StoreRef.PROTOCOL_WORKSPACE, "SpacesStore"); + public final static StoreRef userStoreRef = new StoreRef("user", "alfrescoUserStore"); - public final static StoreRef userStoreRef = new StoreRef("user", "alfrescoUserStore"); + public final static StoreRef versionStoreRef = new StoreRef("versionStore", "version2Store"); - public final static StoreRef versionStoreRef = new StoreRef("versionStore", "version2Store"); + public final static StoreRef archiveStoreRef = new StoreRef("archive", "SpacesStore"); - public final static StoreRef archiveStoreRef = new StoreRef("archive","SpacesStore"); + public static String propertyfile = CCConstants.REPOSITORY_FILE_HOME; - public static String propertyfile = CCConstants.REPOSITORY_FILE_HOME; + /** + * when it's true and getChildren or getChild is called the properties of + * the referenced object will be returned by asking the remote Repository. + * sometimes this behavior is not what we want for example getting the real + * RemoteObject Properties so you can use this prop. see getPropertiesBridge + */ + boolean resolveRemoteObjects = true; - /** - * when it's true and getChildren or getChild is called the properties of - * the referenced object will be returned by asking the remote Repository. - * sometimes this behavior is not what we want for example getting the real - * RemoteObject Properties so you can use this prop. see getPropertiesBridge - */ - boolean resolveRemoteObjects = true; + protected String repId = null; - protected String repId = null; + protected ApplicationInfo appInfo = null; - protected ApplicationInfo appInfo = null; + Repository repositoryHelper = null; - Repository repositoryHelper = null; + private static String alfrescoSearchSubsystem = null; - private static String alfrescoSearchSubsystem = null; + public static final String SEARCH_SUBSYSTEM_LUCENE = "lucene"; + public static final String SEARCH_SUBSYSTEM_SOLR = "solr"; - public static final String SEARCH_SUBSYSTEM_LUCENE = "lucene"; - public static final String SEARCH_SUBSYSTEM_SOLR = "solr"; - - /** - * this constructor can be used when the authentication at alfresco services - * was already done The AuthenticationInfo is taken from the current thread. - * - * Pay attention when using it. Cause of the thread pool in tomcat this can - * lead to the problem that the user becomes someone else when the thread - * was used by another user before and no new authentication with alfresco - * authenticationservice was processed - */ - public MCAlfrescoAPIClient() { - this(null); - } + /** + * this constructor can be used when the authentication at alfresco services + * was already done The AuthenticationInfo is taken from the current thread. + * + * Pay attention when using it. Cause of the thread pool in tomcat this can + * lead to the problem that the user becomes someone else when the thread + * was used by another user before and no new authentication with alfresco + * authenticationservice was processed + */ + public MCAlfrescoAPIClient() { + this(null); + } - public MCAlfrescoAPIClient(HashMap _authenticationInfo) { - this(ApplicationInfoList.getHomeRepository().getAppId(), _authenticationInfo); - } + public MCAlfrescoAPIClient(Map _authenticationInfo) { + this(ApplicationInfoList.getHomeRepository().getAppId(), _authenticationInfo); + } - /** - * TODO: change static methods to object methods, use class attributes - * repositoryFile and authenticationInfo - * - * @param _repositoryFile - * @param _authenticationInfo - */ - public MCAlfrescoAPIClient(String _repositoryFile, HashMap _authenticationInfo) { + /** + * TODO: change static methods to object methods, use class attributes + * repositoryFile and authenticationInfo + * + * @param _repositoryFile + * @param _authenticationInfo + */ + public MCAlfrescoAPIClient(String _repositoryFile, Map _authenticationInfo) { - appInfo = ApplicationInfoList.getHomeRepository(); - repId = appInfo.getAppId(); + appInfo = ApplicationInfoList.getHomeRepository(); + repId = appInfo.getAppId(); - applicationContext = AlfAppContextGate.getApplicationContext(); - userCache = AlfAppContextGate.getApplicationContext().getBean(UserCache.class); + applicationContext = AlfAppContextGate.getApplicationContext(); + userCache = AlfAppContextGate.getApplicationContext().getBean(UserCache.class); - serviceRegistry = (ServiceRegistry) applicationContext.getBean(ServiceRegistry.SERVICE_REGISTRY); + serviceRegistry = (ServiceRegistry) applicationContext.getBean(ServiceRegistry.SERVICE_REGISTRY); - repositoryHelper = (Repository) applicationContext.getBean("repositoryHelper"); + repositoryHelper = (Repository) applicationContext.getBean("repositoryHelper"); - nodeService = serviceRegistry.getNodeService(); + nodeService = serviceRegistry.getNodeService(); - contentService = serviceRegistry.getContentService(); + contentService = serviceRegistry.getContentService(); - authorityService = serviceRegistry.getAuthorityService(); + authorityService = serviceRegistry.getAuthorityService(); - searchService = (SearchService)applicationContext.getBean("scopedSearchService");//serviceRegistry.getSearchService(); + searchService = (SearchService) applicationContext.getBean("scopedSearchService");//serviceRegistry.getSearchService(); - namespaceService = serviceRegistry.getNamespaceService(); + namespaceService = serviceRegistry.getNamespaceService(); - personService = serviceRegistry.getPersonService(); + personService = serviceRegistry.getPersonService(); - dictionaryService = serviceRegistry.getDictionaryService(); + dictionaryService = serviceRegistry.getDictionaryService(); - eduAuthorityService = (org.edu_sharing.alfresco.service.AuthorityService)applicationContext.getBean("eduAuthorityService"); + eduAuthorityService = (org.edu_sharing.alfresco.service.AuthorityService) applicationContext.getBean("eduAuthorityService"); - eduOrganisationService = (org.edu_sharing.alfresco.service.OrganisationService)applicationContext.getBean("eduOrganisationService"); + eduOrganisationService = (org.edu_sharing.alfresco.service.OrganisationService) applicationContext.getBean("eduOrganisationService"); - if (_authenticationInfo == null) { - try{ - HashMap authInfo = new HashMap(); - authInfo.put(CCConstants.AUTH_USERNAME, serviceRegistry.getAuthenticationService().getCurrentUserName()); - /** - * when authentication.ticket.useSingleTicketPerUser=false is set - * and the current user is the System user the call of - * serviceRegistry.getAuthenticationService().getCurrentTicket() leads to new ticket creation - */ - if(!AuthenticationUtil.isRunAsUserTheSystemUser()){ - authInfo.put(CCConstants.AUTH_TICKET, serviceRegistry.getAuthenticationService().getCurrentTicket()); - } - authenticationInfo = authInfo; - logger.debug("authinfo init parameter is null, using " + " " + authenticationInfo.get(CCConstants.AUTH_USERNAME) + " " + authenticationInfo.get(CCConstants.AUTH_TICKET)); - }catch(AuthenticationCredentialsNotFoundException e){ - // if session/user is not initalized, some methods may not work - // but still, we can initialize ApiClient - logger.warn("authinfo init parameter is null and no user session found"); - } + if (_authenticationInfo == null) { + try { + Map authInfo = new HashMap<>(); + authInfo.put(CCConstants.AUTH_USERNAME, serviceRegistry.getAuthenticationService().getCurrentUserName()); + /** + * when authentication.ticket.useSingleTicketPerUser=false is set + * and the current user is the System user the call of + * serviceRegistry.getAuthenticationService().getCurrentTicket() leads to new ticket creation + */ + if (!AuthenticationUtil.isRunAsUserTheSystemUser()) { + authInfo.put(CCConstants.AUTH_TICKET, serviceRegistry.getAuthenticationService().getCurrentTicket()); + } + authenticationInfo = authInfo; + log.debug("authinfo init parameter is null, using " + " " + authenticationInfo.get(CCConstants.AUTH_USERNAME) + " " + authenticationInfo.get(CCConstants.AUTH_TICKET)); + } catch (AuthenticationCredentialsNotFoundException e) { + // if session/user is not initalized, some methods may not work + // but still, we can initialize ApiClient + log.warn("authinfo init parameter is null and no user session found"); + } - /** - * do not call serviceRegistry.getAuthenticationService().validate - * here to allow runAs code using this class validate would - * overwrite the runAsUser - * - * this safe cause ContextmanagementFilter calls - * authservice.clearCurrentSecurityContext() after every request - * - * @TODO check if it is better to put run as user in authInfo than - * the fully authenticated user - */ - - } else { - authenticationInfo = _authenticationInfo; - logger.debug("authinfo is not null" + " " + authenticationInfo.get(CCConstants.AUTH_USERNAME) + " " - + authenticationInfo.get(CCConstants.AUTH_TICKET)); - serviceRegistry.getAuthenticationService().validate(authenticationInfo.get(CCConstants.AUTH_TICKET)); - } + /** + * do not call serviceRegistry.getAuthenticationService().validate + * here to allow runAs code using this class validate would + * overwrite the runAsUser + * + * this safe cause ContextmanagementFilter calls + * authservice.clearCurrentSecurityContext() after every request + * + * @TODO check if it is better to put run as user in authInfo than + * the fully authenticated user + */ + + } else { + authenticationInfo = _authenticationInfo; + log.debug("authinfo is not null" + " " + authenticationInfo.get(CCConstants.AUTH_USERNAME) + " " + + authenticationInfo.get(CCConstants.AUTH_TICKET)); + serviceRegistry.getAuthenticationService().validate(authenticationInfo.get(CCConstants.AUTH_TICKET)); + } - if (alfrescoSearchSubsystem == null) { - // SwitchableApplicationContextFactoryapp - SwitchableApplicationContextFactory sACF = (SwitchableApplicationContextFactory) applicationContext.getBean("Search"); - alfrescoSearchSubsystem = sACF.getCurrentSourceBeanName(); - } + if (alfrescoSearchSubsystem == null) { + // SwitchableApplicationContextFactoryapp + SwitchableApplicationContextFactory sACF = (SwitchableApplicationContextFactory) applicationContext.getBean("Search"); + alfrescoSearchSubsystem = sACF.getCurrentSourceBeanName(); + } - } + } - public SearchResult searchSolr(String query, int startIdx, int nrOfresults, List facettes, int facettesMinCount, int facettesLimit) - throws Throwable { - - SearchResultNodeRef srnr = searchSolrNodeRef(query, startIdx, nrOfresults, facettes, facettesMinCount, facettesLimit); - SearchResult result = new SearchResult(); - Map> countedProps = new HashMap<>(); - if(srnr.getFacets() != null){ - for(NodeSearch.Facet f : srnr.getFacets()){ - Map values = new HashMap<>(); - for(NodeSearch.Facet.Value value : f.getValues()){ - values.put(value.getValue(),value.getCount()); - } - countedProps.put(f.getProperty(),values); - } - } - result.setCountedProps(countedProps); - result.setNodeCount(srnr.getNodeCount()); - result.setStartIDX(startIdx); + public SearchResult searchSolr(String query, int startIdx, int nrOfresults, List facettes, int facettesMinCount, int facettesLimit) + throws Throwable { + + SearchResultNodeRef srnr = searchSolrNodeRef(query, startIdx, nrOfresults, facettes, facettesMinCount, facettesLimit); + SearchResult result = new SearchResult(); + Map> countedProps = new HashMap<>(); + if (srnr.getFacets() != null) { + for (NodeSearch.Facet f : srnr.getFacets()) { + Map values = new HashMap<>(); + for (NodeSearch.Facet.Value value : f.getValues()) { + values.put(value.getValue(), value.getCount()); + } + countedProps.put(f.getProperty(), values); + } + } + result.setCountedProps(countedProps); + result.setNodeCount(srnr.getNodeCount()); + result.setStartIDX(startIdx); - HashMap> returnVal = new LinkedHashMap>(); - List resultNodeRefs = srnr.getData(); - for (int i = 0; i < resultNodeRefs.size(); i++) { + Map> returnVal = new LinkedHashMap<>(); + List resultNodeRefs = srnr.getData(); + for (int i = 0; i < resultNodeRefs.size(); i++) { - org.edu_sharing.service.model.NodeRef nodeRefEdu = resultNodeRefs.get(i); - NodeRef actNode = new NodeRef(new StoreRef(nodeRefEdu.getStoreProtocol(),nodeRefEdu.getStoreId()), nodeRefEdu.getNodeId()); + org.edu_sharing.service.model.NodeRef nodeRefEdu = resultNodeRefs.get(i); + NodeRef actNode = new NodeRef(new StoreRef(nodeRefEdu.getStoreProtocol(), nodeRefEdu.getStoreId()), nodeRefEdu.getNodeId()); - HashMap properties = getProperties(actNode); - returnVal.put(actNode.getId(), properties); - } + Map properties = getProperties(actNode); + returnVal.put(actNode.getId(), properties); + } - result.setData(returnVal); - return result; - } + result.setData(returnVal); + return result; + } - public SearchResultNodeRef searchSolrNodeRef(String query, int startIdx, int nrOfresults, List facettes, int facettesMinCount, int facettesLimit) - throws Throwable { + public SearchResultNodeRef searchSolrNodeRef(String query, int startIdx, int nrOfresults, List facettes, int facettesMinCount, int facettesLimit) + throws Throwable { - SearchResultNodeRef searchResult = new SearchResultNodeRef(); + SearchResultNodeRef searchResult = new SearchResultNodeRef(); - SearchParameters searchParameters = new SearchParameters(); - searchParameters.addStore(storeRef); + SearchParameters searchParameters = new SearchParameters(); + searchParameters.addStore(storeRef); - searchParameters.setLanguage(SearchService.LANGUAGE_LUCENE); - searchParameters.setQuery(query); + searchParameters.setLanguage(SearchService.LANGUAGE_LUCENE); + searchParameters.setQuery(query); - searchParameters.setSkipCount(startIdx); - searchParameters.setMaxItems(nrOfresults); + searchParameters.setSkipCount(startIdx); + searchParameters.setMaxItems(nrOfresults); - if (facettes != null && facettes.size() > 0) { - for (String facetteProp : facettes) { - String fieldFacette = "@" + facetteProp; - FieldFacet fieldFacet = new FieldFacet(fieldFacette); - fieldFacet.setLimit(facettesLimit); - //fieldFacet.setMinCount(facettesMinCount); + if (facettes != null && facettes.size() > 0) { + for (String facetteProp : facettes) { + String fieldFacette = "@" + facetteProp; + FieldFacet fieldFacet = new FieldFacet(fieldFacette); + fieldFacet.setLimit(facettesLimit); + //fieldFacet.setMinCount(facettesMinCount); - System.out.println("MONCOUT reset to one"); - fieldFacet.setMinCount(1); - searchParameters.addFieldFacet(fieldFacet); - } - } + System.out.println("MONCOUT reset to one"); + fieldFacet.setMinCount(1); + searchParameters.addFieldFacet(fieldFacet); + } + } - ResultSet resultSet = searchService.query(searchParameters); + ResultSet resultSet = searchService.query(searchParameters); - long nrFound = ((SolrJSONResultSet) resultSet).getNumberFound(); + long nrFound = resultSet.getNumberFound(); - searchResult.setNodeCount((int) nrFound); + searchResult.setNodeCount((int) nrFound); - int startIDX = startIdx; + int startIDX = startIdx; - if (nrFound <= startIDX) { - startIDX = 0; - } - searchResult.setStartIDX(startIDX); - - // do the facette - if (facettes != null && facettes.size() > 0) { - List facetsResult = new ArrayList<>(); - - for (String facetteProp : facettes) { - NodeSearch.Facet facet = new NodeSearch.Facet(); - facet.setProperty(facetteProp); - facet.setValues(new ArrayList<>()); - facetsResult.add(facet); - - String fieldFacette = "@" + facetteProp; - - List> facettPairs = resultSet.getFieldFacet(fieldFacette); - Integer subStringCount = null; - - // plain solr - logger.info("found " + facettPairs.size() + " facette pairs for" + fieldFacette); - for (Pair pair : facettPairs) { - - // value contains language information i.e. {de} - String first = new String(pair.getFirst().replaceAll("\\{[a-z]*\\}", "").getBytes(), "UTF-8"); - // logger.info("pair.getFirst():"+first+" pair.getSecond():"+pair.getSecond()); - // why ever: no values will be counted to so filter them - - /** - *solr4 problem: delivers facetes that have count 0 and should not occur in the searchresult - * - * http://stackoverflow.com/questions/10069868/getting-facet-count-0-in-solr - * --> pair.getSecond() > 0 - */ - if (first != null && !first.trim().equals("") && pair.getSecond() > 0) { - NodeSearch.Facet.Value value = new NodeSearch.Facet.Value(); - value.setValue(first); - value.setCount(pair.getSecond()); - facet.getValues().add(value); - } - } + if (nrFound <= startIDX) { + startIDX = 0; + } + searchResult.setStartIDX(startIDX); + + // do the facette + if (facettes != null && facettes.size() > 0) { + List facetsResult = new ArrayList<>(); + + for (String facetteProp : facettes) { + NodeSearch.Facet facet = new NodeSearch.Facet(); + facet.setProperty(facetteProp); + facet.setValues(new ArrayList<>()); + facetsResult.add(facet); + + String fieldFacette = "@" + facetteProp; + + List> facettPairs = resultSet.getFieldFacet(fieldFacette); + Integer subStringCount = null; + + // plain solr + log.info("found " + facettPairs.size() + " facette pairs for" + fieldFacette); + for (Pair pair : facettPairs) { + + // value contains language information i.e. {de} + String first = new String(pair.getFirst().replaceAll("\\{[a-z]*\\}", "").getBytes(), "UTF-8"); + // logger.info("pair.getFirst():"+first+" pair.getSecond():"+pair.getSecond()); + // why ever: no values will be counted to so filter them + + /** + *solr4 problem: delivers facetes that have count 0 and should not occur in the searchresult + * + * http://stackoverflow.com/questions/10069868/getting-facet-count-0-in-solr + * --> pair.getSecond() > 0 + */ + if (first != null && !first.trim().equals("") && pair.getSecond() > 0) { + NodeSearch.Facet.Value value = new NodeSearch.Facet.Value(); + value.setValue(first); + value.setCount(pair.getSecond()); + facet.getValues().add(value); + } + } - } - searchResult.setFacets(facetsResult); - } + } + searchResult.setFacets(facetsResult); + } - searchResult.setData(AlfrescoDaoHelper.unmarshall(resultSet.getNodeRefs(), this.repId)); - logger.info("returns"); - return searchResult; + searchResult.setData(AlfrescoDaoHelper.unmarshall(resultSet.getNodeRefs(), this.repId)); + log.info("returns"); + return searchResult; - } + } - public HashMap> search(String luceneString, String type) throws Exception { + public Map> search(String luceneString, String type) throws Exception { - String queryString = "TYPE:\"" + type + "\""; - if (luceneString != null && !luceneString.trim().equals("")) { - queryString = queryString + " AND " + luceneString; - } + String queryString = "TYPE:\"" + type + "\""; + if (luceneString != null && !luceneString.trim().equals("")) { + queryString = queryString + " AND " + luceneString; + } - HashMap> result = new HashMap>(); - ResultSet resultSet = searchService.query(storeRef, SearchService.LANGUAGE_LUCENE, queryString); + Map> result = new HashMap<>(); + ResultSet resultSet = searchService.query(storeRef, SearchService.LANGUAGE_LUCENE, queryString); - List nodeRefs = resultSet.getNodeRefs(); - for (NodeRef nodeRef : nodeRefs) { - HashMap props = getPropertiesSimple(nodeRef.getId()); - result.put(nodeRef.getId(), props); - } - return result; - } + List nodeRefs = resultSet.getNodeRefs(); + for (NodeRef nodeRef : nodeRefs) { + Map props = getPropertiesSimple(nodeRef.getId()); + result.put(nodeRef.getId(), props); + } + return result; + } - public HashMap> search(String luceneString) throws Throwable { - return this.search(luceneString, storeRef.getProtocol(), storeRef.getIdentifier(),0, 10000).getData(); - } + public Map> search(String luceneString) throws Throwable { + return this.search(luceneString, storeRef.getProtocol(), storeRef.getIdentifier(), 0, 10000).getData(); + } - public SearchResult search(String luceneString, String storeProtocol, String storeName, int from, int maxResult) throws Throwable { + public SearchResult search(String luceneString, String storeProtocol, String storeName, int from, int maxResult) throws Throwable { - StoreRef storeRef = new StoreRef(storeProtocol, storeName); - HashMap> result = new LinkedHashMap>(); + StoreRef storeRef = new StoreRef(storeProtocol, storeName); + Map> result = new LinkedHashMap<>(); - SearchParameters searchParameters = new SearchParameters(); - searchParameters.addStore(storeRef); + SearchParameters searchParameters = new SearchParameters(); + searchParameters.addStore(storeRef); - searchParameters.setLanguage(SearchService.LANGUAGE_LUCENE); + searchParameters.setLanguage(SearchService.LANGUAGE_LUCENE); - searchParameters.setQuery(luceneString); + searchParameters.setQuery(luceneString); - searchParameters.setSkipCount(from); - searchParameters.setMaxItems(maxResult); + searchParameters.setSkipCount(from); + searchParameters.setMaxItems(maxResult); - ResultSet resultSet = searchService.query(searchParameters); + ResultSet resultSet = searchService.query(searchParameters); - List nodeRefs = resultSet.getNodeRefs(); - for (NodeRef nodeRef : nodeRefs) { - HashMap props = getProperties(new NodeRef(storeRef,nodeRef.getId())); - result.put(nodeRef.getId(), props); - } + List nodeRefs = resultSet.getNodeRefs(); + for (NodeRef nodeRef : nodeRefs) { + Map props = getProperties(new NodeRef(storeRef, nodeRef.getId())); + result.put(nodeRef.getId(), props); + } - SearchResult sr = new SearchResult(); - sr.setData(result); - sr.setStartIDX(from); - sr.setNodeCount(maxResult); - sr.setNodeCount((int)resultSet.getNumberFound()); + SearchResult sr = new SearchResult(); + sr.setData(result); + sr.setStartIDX(from); + sr.setNodeCount(maxResult); + sr.setNodeCount((int) resultSet.getNumberFound()); - return sr; - } + return sr; + } - @Override - public HashMap> search(String luceneString, ContextSearchMode mode) - throws Throwable { - HashMap> result = new HashMap>(); - SearchParameters token=new SearchParameters(); - token.setQuery(luceneString); - List nodeRefs = searchNodeRefs(token,mode); - for (NodeRef nodeRef : nodeRefs) { - try{ - HashMap props = getProperties(nodeRef.getId()); - result.put(nodeRef.getId(), props); - }catch(AccessDeniedException e){ - logger.error("found node but can not access node properties:" + nodeRef.getId()); - } - } - return result; - } + @Override + public Map> search(String luceneString, ContextSearchMode mode) + throws Throwable { + Map> result = new HashMap<>(); + SearchParameters token = new SearchParameters(); + token.setQuery(luceneString); + List nodeRefs = searchNodeRefs(token, mode); + for (NodeRef nodeRef : nodeRefs) { + try { + Map props = getProperties(nodeRef.getId()); + result.put(nodeRef.getId(), props); + } catch (AccessDeniedException e) { + log.error("found node but can not access node properties:" + nodeRef.getId()); + } + } + return result; + } - public List searchNodeRefs(SearchParameters token, ContextSearchMode mode){ - Set authorities=null; - if(mode.equals(ContextSearchMode.UserAndGroups)) { + public List searchNodeRefs(SearchParameters token, ContextSearchMode mode) { + Set authorities = null; + if (mode.equals(ContextSearchMode.UserAndGroups)) { authorities = new HashSet<>(authorityService.getAuthorities()); authorities.remove(CCConstants.AUTHORITY_GROUP_EVERYONE); // remove the admin role, otherwise may results in inconsistent results authorities.remove(CCConstants.AUTHORITY_ROLE_ADMINISTRATOR); authorities.add(AuthenticationUtil.getFullyAuthenticatedUser()); - } - else if(mode.equals(ContextSearchMode.Public)){ - authorities=new HashSet<>(); + } else if (mode.equals(ContextSearchMode.Public)) { + authorities = new HashSet<>(); authorities.add(CCConstants.AUTHORITY_GROUP_EVERYONE); } SearchParameters essp = new SearchParameters(); - if(authorities!=null){ + if (authorities != null) { essp = new ESSearchParameters(); - ((ESSearchParameters)essp).setAuthorities(authorities.toArray(new String[authorities.size()])); + ((ESSearchParameters) essp).setAuthorities(authorities.toArray(new String[authorities.size()])); } essp.setQuery(token.getQuery()); - for(SearchParameters.SortDefinition sort : token.getSortDefinitions()){ + for (SearchParameters.SortDefinition sort : token.getSortDefinitions()) { essp.addSort(sort); } essp.setLanguage(SearchService.LANGUAGE_LUCENE); essp.addStore(storeRef); - for(SearchParameters.SortDefinition def : token.getSortDefinitions()) { + for (SearchParameters.SortDefinition def : token.getSortDefinitions()) { essp.addSort(def); } return searchService.query(essp).getNodeRefs(); - } + } - public String[] searchNodeIds(String luceneString) { - return searchNodeIds(luceneString, -1); - } + public String[] searchNodeIds(String luceneString) { + return searchNodeIds(luceneString, -1); + } - public String[] searchNodeIds(String luceneString, int limit) { - SearchParameters searchParameters = new SearchParameters(); - searchParameters.addStore(storeRef); - searchParameters.setLanguage(SearchService.LANGUAGE_LUCENE); - searchParameters.setQuery(luceneString); - if (limit > -1) { - searchParameters.setLimit(limit); - } - ResultSet resultSet = searchService.query(searchParameters); + public String[] searchNodeIds(String luceneString, int limit) { + SearchParameters searchParameters = new SearchParameters(); + searchParameters.addStore(storeRef); + searchParameters.setLanguage(SearchService.LANGUAGE_LUCENE); + searchParameters.setQuery(luceneString); + if (limit > -1) { + searchParameters.setLimit(limit); + } + ResultSet resultSet = searchService.query(searchParameters); - ArrayList result = new ArrayList(); - for (NodeRef nodeRef : resultSet.getNodeRefs()) { - result.add(nodeRef.getId()); - } - return result.toArray(new String[result.size()]); - } + ArrayList result = new ArrayList<>(); + for (NodeRef nodeRef : resultSet.getNodeRefs()) { + result.add(nodeRef.getId()); + } + return result.toArray(new String[result.size()]); + } - public String formatData(String type, String key, Object value, String metadataSetId) { - String returnValue = null; - if (key != null && value != null) { - boolean processed=false; - // value is date than put a String with a long value so that it can - // be formated with userInfo later - if(value instanceof List){ - List list = (List) value; - if(list.size()>0){ - if(list.get(0) instanceof Date) { - returnValue = ValueTool.toMultivalue( - list.stream(). - map((date) -> new Long(((Date)date).getTime()).toString()). - collect(Collectors.toList()).toArray(new String[0]) - ); - processed=true; - } - } - } - if (value instanceof Date) { + public String formatData(String type, String key, Object value, String metadataSetId) { + String returnValue = null; + if (key != null && value != null) { + boolean processed = false; + // value is date than put a String with a long value so that it can + // be formated with userInfo later + if (value instanceof List) { + List list = (List) value; + if (list.size() > 0) { + if (list.get(0) instanceof Date) { + returnValue = ValueTool.toMultivalue( + list.stream(). + map((date) -> new Long(((Date) date).getTime()).toString()). + collect(Collectors.toList()).toArray(new String[0]) + ); + processed = true; + } + } + } + if (value instanceof Date) { - Date date = (Date) value; - returnValue = new Long(date.getTime()).toString(); - processed=true; - } - if(!processed){ - returnValue = getValue(type, key, value, metadataSetId); - } - // !(value instanceof MLText || value instanceof List): prevent sth. - // like de_DE=null in gui - if (returnValue == null && value != null && !(value instanceof MLText || value instanceof List)) { - returnValue = value.toString(); - } - } - return returnValue; - } + Date date = (Date) value; + returnValue = new Long(date.getTime()).toString(); + processed = true; + } + if (!processed) { + returnValue = getValue(type, key, value, metadataSetId); + } + // !(value instanceof MLText || value instanceof List): prevent sth. + // like de_DE=null in gui + if (returnValue == null && value != null && !(value instanceof MLText || value instanceof List)) { + returnValue = value.toString(); + } + } + return returnValue; + } - protected String getValue(String type, String prop, Object _value, String metadataSetId) { - - //MetadataSetModelProperty mdsmProp = getMetadataSetModelProperty(metadataSetId, type, prop); - - if (_value instanceof List && ((List) _value).size() > 0) { - String result = null; - for (Object value : (List) _value) { - if (result != null) - result += CCConstants.MULTIVALUE_SEPARATOR; - if (value != null) { - if (value instanceof MLText) { - String tmpStr = getMLTextString(value); - if (result != null) - result += tmpStr; - else - result = tmpStr; - } else { - if (result != null) - result += value.toString(); - else - result = value.toString(); - } - } - } + protected String getValue(String type, String prop, Object _value, String metadataSetId) { + + //MetadataSetModelProperty mdsmProp = getMetadataSetModelProperty(metadataSetId, type, prop); + + if (_value instanceof List && ((List) _value).size() > 0) { + String result = null; + for (Object value : (List) _value) { + if (result != null) + result += CCConstants.MULTIVALUE_SEPARATOR; + if (value != null) { + if (value instanceof MLText) { + String tmpStr = getMLTextString(value); + if (result != null) + result += tmpStr; + else + result = tmpStr; + } else { + if (result != null) + result += value.toString(); + else + result = value.toString(); + } + } + } - return result; - } else if (_value instanceof List && ((List) _value).size() == 0) { - // cause empty list toString returns "[]" - return ""; - } else if (_value instanceof String) { - return (String) _value; - } else if (_value instanceof Number) { - return _value.toString(); - } else if (_value instanceof MLText) { - return getMLTextString(_value); - } else { - return _value.toString(); - } + return result; + } else if (_value instanceof List && ((List) _value).size() == 0) { + // cause empty list toString returns "[]" + return ""; + } else if (_value instanceof String) { + return (String) _value; + } else if (_value instanceof Number) { + return _value.toString(); + } else if (_value instanceof MLText) { + return getMLTextString(_value); + } else { + return _value.toString(); + } - } - /* + } + + /* MetadataSetModelProperty getMetadataSetModelProperty(String metadataSetId, String type, String prop) { MetadataSetModelProperty mdsmProp = null; @@ -621,7 +597,7 @@ MetadataSetModelProperty getMetadataSetModelProperty(String metadataSetId, Strin metadataSetId = CCConstants.metadatasetdefault_id; if (metadataSetId != null) { - + if (metadataSetsForRep == null) { metadataSetsForRep = RepoFactory.getMetadataSetsForRepository(repId); } @@ -637,181 +613,178 @@ MetadataSetModelProperty getMetadataSetModelProperty(String metadataSetId, Strin return mdsmProp; } */ - protected String getMLTextString(Object _mlText) { + protected String getMLTextString(Object _mlText) { - if (_mlText instanceof MLText) { + if (_mlText instanceof MLText) { - MLText mlText = (MLText) _mlText; + MLText mlText = (MLText) _mlText; - // when description does not exist then return default value - // when description exists bit there is no multilang the return value - if (true /*mdsmp == null || (mdsmp != null && !mdsmp.getMultilang())*/) { - return mlText.getDefaultValue(); - } + // when description does not exist then return default value + // when description exists bit there is no multilang the return value + if (true /*mdsmp == null || (mdsmp != null && !mdsmp.getMultilang())*/) { + return mlText.getDefaultValue(); + } - String mlValueString = null; + String mlValueString = null; - for (Locale locale : mlText.getLocales()) { - String mlValue = mlText.getValue(locale); + for (Locale locale : mlText.getLocales()) { + String mlValue = mlText.getValue(locale); - String localeStr = (locale.toString().equals(".default")) ? CCConstants.defaultLocale : locale.toString(); + String localeStr = (locale.toString().equals(".default")) ? CCConstants.defaultLocale : locale.toString(); - if (mlValueString == null) { - // for props that are declared multilang in alfresco model - // but not in cc metadataset then props are saved as default. - if (mlText.getLocales().size() == 1 && localeStr.equals(CCConstants.defaultLocale)) { - mlValueString = mlValue; - } else { - mlValueString = localeStr + "=" + mlValue; - } - } else { - mlValueString += "[,]" + localeStr + "=" + mlValue; - } - } - if (mlValueString != null && !mlValueString.trim().equals("") && !mlValueString.contains(CCConstants.defaultLocale)) { - mlValueString += "[,]default=" + mlText.getDefaultValue(); - } + if (mlValueString == null) { + // for props that are declared multilang in alfresco model + // but not in cc metadataset then props are saved as default. + if (mlText.getLocales().size() == 1 && localeStr.equals(CCConstants.defaultLocale)) { + mlValueString = mlValue; + } else { + mlValueString = localeStr + "=" + mlValue; + } + } else { + mlValueString += "[,]" + localeStr + "=" + mlValue; + } + } + if (mlValueString != null && !mlValueString.trim().equals("") && !mlValueString.contains(CCConstants.defaultLocale)) { + mlValueString += "[,]default=" + mlText.getDefaultValue(); + } - return mlValueString; - } else { - return _mlText.toString(); - } - } + return mlValueString; + } else { + return _mlText.toString(); + } + } - public HashMap> getChildren(String parentID) throws Throwable { - return getChildren(parentID, (String) null); - } + public Map> getChildren(String parentID) throws Throwable { + return getChildren(parentID, (String) null); + } - public HashMap> getChildren(String parentID, String[] permissionsOnChild) throws Throwable { + public Map> getChildren(String parentID, String[] permissionsOnChild) throws Throwable { - HashMap> result = getChildren(parentID); + Map> result = getChildren(parentID); - ArrayList toRemove = new ArrayList(); - if (result != null) { - for (String nodeId : result.keySet()) { - if (!hasPermissions(nodeId, permissionsOnChild)) { - toRemove.add(nodeId); - } - } - for (String nodeId : toRemove) { - result.remove(nodeId); - } - } + ArrayList toRemove = new ArrayList<>(); + if (result != null) { + for (String nodeId : result.keySet()) { + if (!hasPermissions(nodeId, permissionsOnChild)) { + toRemove.add(nodeId); + } + } + for (String nodeId : toRemove) { + result.remove(nodeId); + } + } - return result; - } + return result; + } - public HashMap> getChildrenRunAs(final String parentID, String runAs) throws Throwable { + public Map> getChildrenRunAs(final String parentID, String runAs) throws Throwable { - final String repoAdmin = ApplicationInfoList.getHomeRepository().getUsername(); + final String repoAdmin = ApplicationInfoList.getHomeRepository().getUsername(); - AuthenticationUtil.RunAsWork>> getChildrenWorker = new AuthenticationUtil.RunAsWork>>() { + AuthenticationUtil.RunAsWork>> getChildrenWorker = () -> { - @Override - public HashMap> doWork() throws Exception { + try { + return new MCAlfrescoAPIClient().getChildren(parentID); + } catch (Throwable e) { + log.error(e.getMessage(), e); + return null; + } - try { - return new MCAlfrescoAPIClient().getChildren(parentID); - } catch (Throwable e) { - logger.error(e.getMessage(), e); - return null; - } + }; - } - }; + return AuthenticationUtil.runAs(getChildrenWorker, repoAdmin); + } - return AuthenticationUtil.runAs(getChildrenWorker, repoAdmin); - } + public List getChildrenChildAssociationRef(String parentID) { + if (parentID == null) { - public List getChildrenChildAssociationRef(String parentID){ - if (parentID == null) { + String startParentId = getRootNodeId(); + if (startParentId == null || startParentId.trim().equals("")) { + parentID = nodeService.getRootNode(storeRef).getId(); + } else { + parentID = startParentId; + } + } + NodeRef parentNodeRef = new NodeRef(MCAlfrescoAPIClient.storeRef, parentID); + List childAssocList = nodeService.getChildAssocs(parentNodeRef); + return childAssocList; + } - String startParentId = getRootNodeId(); - if (startParentId == null || startParentId.trim().equals("")) { - parentID = nodeService.getRootNode(storeRef).getId(); - } else { - parentID = startParentId; - } - } - NodeRef parentNodeRef = new NodeRef(MCAlfrescoAPIClient.storeRef, parentID); - List childAssocList = nodeService.getChildAssocs(parentNodeRef); - return childAssocList; - } + public Map> getChildren(String parentID, String type) throws Throwable { - public HashMap> getChildren(String parentID, String type) throws Throwable { + Map> returnVal = new HashMap<>(); - HashMap> returnVal = new HashMap>(); + if (parentID == null) { + String startParentId = getRootNodeId(); + if (startParentId == null || startParentId.trim().equals("")) { + parentID = nodeService.getRootNode(storeRef).getId(); + } else { + parentID = startParentId; + } + } - if (parentID == null) { - String startParentId = getRootNodeId(); - if (startParentId == null || startParentId.trim().equals("")) { - parentID = nodeService.getRootNode(storeRef).getId(); - } else { - parentID = startParentId; - } - } + NodeRef parentNodeRef = new NodeRef(MCAlfrescoAPIClient.storeRef, parentID); + List childAssocList = nodeService.getChildAssocs(parentNodeRef); + for (ChildAssociationRef child : childAssocList) { + + /** + * Alfresco 4.0.e archiving on: - check if it's not the archive + * store (when a object was deleted and it was linked somwhere the + * link still exist and points to archive store) + */ + if (!child.getChildRef().getStoreRef().equals(MCAlfrescoAPIClient.storeRef)) + continue; + + if (type == null || type.equals(nodeService.getType(child.getChildRef()).toString())) { + Map properties = getProperties(child.getChildRef()); + if (properties == null) + continue; + + // to prevent performace issues in search we only put the + // publish right here, it's only needed in workspace list + String nodeId = properties.containsKey(CCConstants.VIRT_PROP_REMOTE_OBJECT_NODEID) ? (String) properties + .get(CCConstants.VIRT_PROP_REMOTE_OBJECT_NODEID) : (String) properties.get(CCConstants.SYS_PROP_NODE_UID); + + boolean hasPublishPermission = this.hasPermissions(nodeId, new String[]{CCConstants.PERMISSION_CC_PUBLISH}); + properties.put(CCConstants.PERMISSION_CC_PUBLISH, new Boolean(hasPublishPermission).toString()); + + // PrimaryParent? + ChildAssociationRef childAssocRef = nodeService.getPrimaryParent(child.getChildRef()); + NodeRef tmpParentRef = childAssocRef.getParentRef(); + if (tmpParentRef.equals(parentNodeRef)) { + properties.put(CCConstants.CCM_PROP_PRIMARY_PARENT, "true"); + } else { + properties.put(CCConstants.CCM_PROP_PRIMARY_PARENT, "false"); + } - NodeRef parentNodeRef = new NodeRef(MCAlfrescoAPIClient.storeRef, parentID); - List childAssocList = nodeService.getChildAssocs(parentNodeRef); - for (ChildAssociationRef child : childAssocList) { - - /** - * Alfresco 4.0.e archiving on: - check if it's not the archive - * store (when a object was deleted and it was linked somwhere the - * link still exist and points to archive store) - */ - if (!child.getChildRef().getStoreRef().equals(MCAlfrescoAPIClient.storeRef)) - continue; - - if (type == null || type.equals(nodeService.getType(child.getChildRef()).toString())) { - HashMap properties = getProperties(child.getChildRef()); - if (properties == null) - continue; - - // to prevent performace issues in search we only put the - // publish right here, it's only needed in workspace list - String nodeId = properties.containsKey(CCConstants.VIRT_PROP_REMOTE_OBJECT_NODEID) ? (String) properties - .get(CCConstants.VIRT_PROP_REMOTE_OBJECT_NODEID) : (String) properties.get(CCConstants.SYS_PROP_NODE_UID); - - boolean hasPublishPermission = this.hasPermissions(nodeId, new String[] { CCConstants.PERMISSION_CC_PUBLISH }); - properties.put(CCConstants.PERMISSION_CC_PUBLISH, new Boolean(hasPublishPermission).toString()); - - // PrimaryParent? - ChildAssociationRef childAssocRef = nodeService.getPrimaryParent(child.getChildRef()); - NodeRef tmpParentRef = childAssocRef.getParentRef(); - if (tmpParentRef.equals(parentNodeRef)) { - properties.put(CCConstants.CCM_PROP_PRIMARY_PARENT, "true"); - } else { - properties.put(CCConstants.CCM_PROP_PRIMARY_PARENT, "false"); - } + // put ChildassociationName + properties.put(CCConstants.CHILD_ASSOCIATION_NAME, child.getQName().getLocalName()); - // put ChildassociationName - properties.put(CCConstants.CHILD_ASSOCIATION_NAME, child.getQName().getLocalName()); + // filter stupid mac files + String name = (String) properties.get(CCConstants.CM_NAME); - // filter stupid mac files - String name = (String) properties.get(CCConstants.CM_NAME); + if (name != null && (name.startsWith("._") || name.startsWith(".DS_Store"))) { + log.debug("will not show system file " + name + " in webgui"); + } else { + returnVal.put(child.getChildRef().getId(), properties); + } + } + } - if (name != null && (name.startsWith("._") || name.startsWith(".DS_Store"))) { - logger.debug("will not show system file " + name + " in webgui"); - } else { - returnVal.put(child.getChildRef().getId(), properties); - } - } - } + return returnVal; + } - return returnVal; - } + public Map getProperties(String nodeId) throws Throwable { + return this.getProperties(new NodeRef(storeRef, nodeId)); + } - public HashMap getProperties(String nodeId) throws Throwable { - return this.getProperties(new NodeRef(storeRef, nodeId)); - } + public Map getProperties(String storeProtocol, String storeId, String nodeId) throws Throwable { + return getProperties(new NodeRef(new StoreRef(storeProtocol, storeId), nodeId)); + } - public HashMap getProperties(String storeProtocol, String storeId, String nodeId) throws Throwable { - return getProperties(new NodeRef(new StoreRef(storeProtocol,storeId),nodeId)); - } public String getDownloadUrl(String nodeId) throws Throwable { - HashMap props = getProperties(nodeId); + Map props = getProperties(nodeId); boolean downloadAllowed = downloadAllowed(nodeId); String redirectServletLink = this.getRedirectServletLink(repId, nodeId); if (props.get(CCConstants.ALFRESCO_MIMETYPE) != null && redirectServletLink != null && downloadAllowed) { @@ -821,489 +794,489 @@ public String getDownloadUrl(String nodeId) throws Throwable { } return null; } - public boolean downloadAllowed(String nodeId){ - NodeRef ref=new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE,nodeId); - return downloadAllowed(nodeId, - nodeService.getProperty(ref,QName.createQName(CCConstants.CCM_PROP_IO_COMMONLICENSE_KEY)), - (String)nodeService.getProperty(ref,QName.createQName(CCConstants.CCM_PROP_EDITOR_TYPE)) - ); - } - public boolean downloadAllowed(String nodeId,Serializable commonLicenseKey,String editorType){ - // when there is a signed request from the connector, the download (binary content delivery) is allowed - if(ContextManagementFilter.accessTool.get() != null && ApplicationInfo.TYPE_CONNECTOR.equals(ContextManagementFilter.accessTool.get().getApplicationInfo().getType())) { - return true; - } - boolean downloadAllowed; + + public boolean downloadAllowed(String nodeId) { + NodeRef ref = new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, nodeId); + return downloadAllowed(nodeId, + nodeService.getProperty(ref, QName.createQName(CCConstants.CCM_PROP_IO_COMMONLICENSE_KEY)), + (String) nodeService.getProperty(ref, QName.createQName(CCConstants.CCM_PROP_EDITOR_TYPE)) + ); + } + + public boolean downloadAllowed(String nodeId, Serializable commonLicenseKey, String editorType) { + // when there is a signed request from the connector, the download (binary content delivery) is allowed + if (ContextManagementFilter.accessTool.get() != null && ApplicationInfo.TYPE_CONNECTOR.equals(ContextManagementFilter.accessTool.get().getApplicationInfo().getType())) { + return true; + } + boolean downloadAllowed; // Array value - if(commonLicenseKey instanceof ArrayList) - downloadAllowed = (CCConstants.COMMON_LICENSE_EDU_P_NR_ND.equals(((ArrayList)commonLicenseKey).get(0))) ? false : true; - else - // string value + if (commonLicenseKey instanceof ArrayList) + downloadAllowed = (CCConstants.COMMON_LICENSE_EDU_P_NR_ND.equals(((ArrayList) commonLicenseKey).get(0))) ? false : true; + else + // string value downloadAllowed = (CCConstants.COMMON_LICENSE_EDU_P_NR_ND.equals(commonLicenseKey)) ? false : true; //allow download for owner, performance only check owner if download not allowed - if(!downloadAllowed && isOwner(nodeId, authenticationInfo.get(CCConstants.AUTH_USERNAME))){ - downloadAllowed = true; - } + if (!downloadAllowed && isOwner(nodeId, authenticationInfo.get(CCConstants.AUTH_USERNAME))) { + downloadAllowed = true; + } - // allow tinymce in safe but not in normal storage - if(editorType != null && editorType.toLowerCase().equals(ConnectorService.ID_TINYMCE.toLowerCase()) && (Context.getCurrentInstance() != null && !CCConstants.CCM_VALUE_SCOPE_SAFE.equals(Context.getCurrentInstance().getSessionAttribute(CCConstants.AUTH_SCOPE)))) { - downloadAllowed = false; - } + // allow tinymce in safe but not in normal storage + if (editorType != null && editorType.toLowerCase().equals(ConnectorService.ID_TINYMCE.toLowerCase()) && (Context.getCurrentInstance() != null && !CCConstants.CCM_VALUE_SCOPE_SAFE.equals(Context.getCurrentInstance().getSessionAttribute(CCConstants.AUTH_SCOPE)))) { + downloadAllowed = false; + } - if(downloadAllowed) { - downloadAllowed = hasPermissions(nodeId, new String[]{CCConstants.PERMISSION_READ_ALL, CCConstants.PERMISSION_DOWNLOAD_CONTENT}); - } - return downloadAllowed; - } - /** - * this method calls getPropertiesCached and makes a copy from the returned - * hashmap this hashmap will be modiefied with the data of the current - * user (i.e. ticket in contenturl, preview url and so on) - * - * @param nodeRef - * @return - * @throws Exception - */ - public HashMap getProperties(NodeRef nodeRef) throws Throwable { - logger.debug("starting"); - - // making a copy so that the cached map will not be influenced - final HashMap propsCopy = new HashMap(getPropertiesCached(nodeRef, true, true, false)); - - logger.debug("starting extend several props with authentication and permission data"); - - NodeServiceInterceptor.throwIfWrongScope(nodeService, nodeRef); - - String nodeType = (String) propsCopy.get(CCConstants.NODETYPE); - - // checking if it is form type content - boolean isSubOfContent = serviceRegistry.getDictionaryService().isSubClass(QName.createQName(nodeType), QName.createQName(CCConstants.CM_TYPE_CONTENT)); - - logger.debug("setting external URL"); - String contentUrl = URLTool.getNgRenderNodeUrl(nodeRef.getId(),null); - - contentUrl = URLTool.addOAuthAccessToken(contentUrl); - propsCopy.put(CCConstants.CONTENTURL, contentUrl); - - // external URL - if (isSubOfContent) { - - Serializable commonLicenseKey = (String)propsCopy.get(CCConstants.CCM_PROP_IO_COMMONLICENSE_KEY); - boolean downloadAllowed = downloadAllowed(nodeRef.getId(),commonLicenseKey,(String)propsCopy.get(CCConstants.CCM_PROP_EDITOR_TYPE)); - boolean isLink = propsCopy.get(CCConstants.CCM_PROP_IO_WWWURL) != null && ( - // should not happen cause of @NodeCustomizationPolicies interceptor - propsCopy.get(CCConstants.LOM_PROP_TECHNICAL_LOCATION) == null || - ((String)propsCopy.get(CCConstants.LOM_PROP_TECHNICAL_LOCATION)).startsWith(CCConstants.CCREP_PROTOCOL) - ); - boolean hasContentOrDownloadableUrl = - propsCopy.get(CCConstants.ALFRESCO_MIMETYPE) != null || - propsCopy.get(CCConstants.LOM_PROP_TECHNICAL_LOCATION)!=null; - if (!isLink && hasContentOrDownloadableUrl && downloadAllowed) { - propsCopy.put(CCConstants.DOWNLOADURL,URLTool.getDownloadServletUrl(nodeRef.getId(),null, true)); - } + if (downloadAllowed) { + downloadAllowed = hasPermissions(nodeId, new String[]{CCConstants.PERMISSION_READ_ALL, CCConstants.PERMISSION_DOWNLOAD_CONTENT}); + } + return downloadAllowed; + } - String commonLicensekey = (String)propsCopy.get(CCConstants.CCM_PROP_IO_COMMONLICENSE_KEY); - if(commonLicensekey != null){ - if(Context.getCurrentInstance() != null){ - String ccversion = (String)propsCopy.get(CCConstants.CCM_PROP_IO_COMMONLICENSE_CC_VERSION); - String licenseUrl = new LicenseService().getLicenseUrl(commonLicensekey, Context.getCurrentInstance().getLocale(),ccversion); - if(licenseUrl != null){ - propsCopy.put(CCConstants.VIRT_PROP_LICENSE_URL, licenseUrl); - } - } - String licenseIcon = new LicenseService().getIconUrl(commonLicensekey); - if(licenseIcon != null) propsCopy.put(CCConstants.VIRT_PROP_LICENSE_ICON, licenseIcon); + /** + * this method calls getPropertiesCached and makes a copy from the returned + * hashmap this hashmap will be modiefied with the data of the current + * user (i.e. ticket in contenturl, preview url and so on) + * + * @param nodeRef + * @return + * @throws Exception + */ + public Map getProperties(NodeRef nodeRef) throws Throwable { + log.debug("starting"); + + // making a copy so that the cached map will not be influenced + final Map propsCopy = new HashMap<>(getPropertiesCached(nodeRef, true, true, false)); + + log.debug("starting extend several props with authentication and permission data"); + + NodeServiceInterceptor.throwIfWrongScope(nodeService, nodeRef); + + String nodeType = (String) propsCopy.get(CCConstants.NODETYPE); + + // checking if it is form type content + boolean isSubOfContent = serviceRegistry.getDictionaryService().isSubClass(QName.createQName(nodeType), QName.createQName(CCConstants.CM_TYPE_CONTENT)); + + log.debug("setting external URL"); + String contentUrl = URLTool.getNgRenderNodeUrl(nodeRef.getId(), null); + + contentUrl = URLTool.addOAuthAccessToken(contentUrl); + propsCopy.put(CCConstants.CONTENTURL, contentUrl); + + // external URL + if (isSubOfContent) { + + Serializable commonLicenseKey = (String) propsCopy.get(CCConstants.CCM_PROP_IO_COMMONLICENSE_KEY); + boolean downloadAllowed = downloadAllowed(nodeRef.getId(), commonLicenseKey, (String) propsCopy.get(CCConstants.CCM_PROP_EDITOR_TYPE)); + boolean isLink = propsCopy.get(CCConstants.CCM_PROP_IO_WWWURL) != null && ( + // should not happen cause of @NodeCustomizationPolicies interceptor + propsCopy.get(CCConstants.LOM_PROP_TECHNICAL_LOCATION) == null || + ((String) propsCopy.get(CCConstants.LOM_PROP_TECHNICAL_LOCATION)).startsWith(CCConstants.CCREP_PROTOCOL) + ); + boolean hasContentOrDownloadableUrl = + propsCopy.get(CCConstants.ALFRESCO_MIMETYPE) != null || + propsCopy.get(CCConstants.LOM_PROP_TECHNICAL_LOCATION) != null; + if (!isLink && hasContentOrDownloadableUrl && downloadAllowed) { + propsCopy.put(CCConstants.DOWNLOADURL, URLTool.getDownloadServletUrl(nodeRef.getId(), null, true)); + } - } - } + String commonLicensekey = (String) propsCopy.get(CCConstants.CCM_PROP_IO_COMMONLICENSE_KEY); + if (commonLicensekey != null) { + if (Context.getCurrentInstance() != null) { + String ccversion = (String) propsCopy.get(CCConstants.CCM_PROP_IO_COMMONLICENSE_CC_VERSION); + String licenseUrl = new LicenseService().getLicenseUrl(commonLicensekey, Context.getCurrentInstance().getLocale(), ccversion); + if (licenseUrl != null) { + propsCopy.put(CCConstants.VIRT_PROP_LICENSE_URL, licenseUrl); + } + } + String licenseIcon = new LicenseService().getIconUrl(commonLicensekey); + if (licenseIcon != null) propsCopy.put(CCConstants.VIRT_PROP_LICENSE_ICON, licenseIcon); - /** Add the image dimensions to the common CCM fields */ - if (nodeType.equals(CCConstants.CCM_TYPE_IO)){ - if(propsCopy.containsKey(CCConstants.EXIF_PROP_PIXELXDIMENSION)){ - propsCopy.put(CCConstants.CCM_PROP_IO_WIDTH,propsCopy.get(CCConstants.EXIF_PROP_PIXELXDIMENSION)); - } - if(propsCopy.containsKey(CCConstants.EXIF_PROP_PIXELYDIMENSION)){ - propsCopy.put(CCConstants.CCM_PROP_IO_HEIGHT,propsCopy.get(CCConstants.EXIF_PROP_PIXELYDIMENSION)); - } + } + } - //Preview Url not longer in cache - String renderServiceUrlPreview = URLTool.getRenderServiceURL(nodeRef.getId(), true); - if (renderServiceUrlPreview != null) { - propsCopy.put(CCConstants.CM_ASSOC_THUMBNAILS, renderServiceUrlPreview); - } else { - propsCopy.put(CCConstants.CM_ASSOC_THUMBNAILS, NodeServiceHelper.getPreview(nodeRef, propsCopy).getUrl()); - } - } + /** Add the image dimensions to the common CCM fields */ + if (nodeType.equals(CCConstants.CCM_TYPE_IO)) { + if (propsCopy.containsKey(CCConstants.EXIF_PROP_PIXELXDIMENSION)) { + propsCopy.put(CCConstants.CCM_PROP_IO_WIDTH, propsCopy.get(CCConstants.EXIF_PROP_PIXELXDIMENSION)); + } + if (propsCopy.containsKey(CCConstants.EXIF_PROP_PIXELYDIMENSION)) { + propsCopy.put(CCConstants.CCM_PROP_IO_HEIGHT, propsCopy.get(CCConstants.EXIF_PROP_PIXELYDIMENSION)); + } - boolean hasMds = nodeType.equals(CCConstants.CCM_TYPE_IO) || nodeType.equals(CCConstants.CCM_TYPE_COMMENT) || nodeType.equals(CCConstants.CCM_TYPE_MATERIAL_FEEDBACK) || nodeType.equals(CCConstants.CCM_TYPE_MAP) || nodeType.equals(CCConstants.CM_TYPE_FOLDER); - String mdsId=CCConstants.metadatasetdefault_id; - MetadataSet mds = null; - /** - * run over all properties and format the date props with with current - * user locale - */ - if (hasMds) { - if(propsCopy.containsKey(CCConstants.CM_PROP_METADATASET_EDU_METADATASET)){ - mdsId=(String)propsCopy.get(CCConstants.CM_PROP_METADATASET_EDU_METADATASET); - } - mds = MetadataHelper.getMetadataset(ApplicationInfoList.getHomeRepository(),mdsId); - HashMap addAndOverwriteDateMap = new HashMap(); - for (Map.Entry entry : propsCopy.entrySet()) { - - PropertyDefinition propDef = dictionaryService.getProperty(QName.createQName(entry.getKey())); - - DataTypeDefinition dtd = null; - if (propDef != null) - dtd = propDef.getDataType(); - if (Context.getCurrentInstance() != null && dtd != null - && (dtd.getName().equals(DataTypeDefinition.DATE) || dtd.getName().equals(DataTypeDefinition.DATETIME))) { - String[] values = ValueTool.getMultivalue((String) entry.getValue()); - String[] formattedValues=new String[values.length]; - int i=0; - for(String value : values){ - formattedValues[i++]=new DateTool().formatDate(new Long(value)); - } - // put time as long i.e. for sorting or formating in gui - // this is basically just a copy of the real value for backward compatibility - addAndOverwriteDateMap.put(entry.getKey() + CCConstants.LONG_DATE_SUFFIX, entry.getValue()); - // put formated - addAndOverwriteDateMap.put(entry.getKey(), ValueTool.toMultivalue(formattedValues)); - } - try{ - MetadataWidget widget = mds.findWidget(CCConstants.getValidLocalName(entry.getKey())); - Map map = widget.getValuesAsMap(); - if(!map.isEmpty()){ - String[] keys=ValueTool.getMultivalue((String) entry.getValue()); - String[] values=new String[keys.length]; - for(int i=0;i addAndOverwriteDateMap = new HashMap<>(); + for (Map.Entry entry : propsCopy.entrySet()) { + + PropertyDefinition propDef = dictionaryService.getProperty(QName.createQName(entry.getKey())); + + DataTypeDefinition dtd = null; + if (propDef != null) + dtd = propDef.getDataType(); + if (Context.getCurrentInstance() != null && dtd != null + && (dtd.getName().equals(DataTypeDefinition.DATE) || dtd.getName().equals(DataTypeDefinition.DATETIME))) { + String[] values = ValueTool.getMultivalue((String) entry.getValue()); + String[] formattedValues = new String[values.length]; + int i = 0; + for (String value : values) { + formattedValues[i++] = new DateTool().formatDate(new Long(value)); + } + // put time as long i.e. for sorting or formating in gui + // this is basically just a copy of the real value for backward compatibility + addAndOverwriteDateMap.put(entry.getKey() + CCConstants.LONG_DATE_SUFFIX, entry.getValue()); + // put formated + addAndOverwriteDateMap.put(entry.getKey(), ValueTool.toMultivalue(formattedValues)); + } + try { + MetadataWidget widget = mds.findWidget(CCConstants.getValidLocalName(entry.getKey())); + Map map = widget.getValuesAsMap(); + if (!map.isEmpty()) { + String[] keys = ValueTool.getMultivalue((String) entry.getValue()); + String[] values = new String[keys.length]; + for (int i = 0; i < keys.length; i++) + values[i] = map.containsKey(keys[i]) ? map.get(keys[i]).getCaption() : keys[i]; + addAndOverwriteDateMap.put(entry.getKey() + CCConstants.DISPLAYNAME_SUFFIX, StringUtils.join(values, CCConstants.MULTIVALUE_SEPARATOR)); + } - for (Map.Entry entry : addAndOverwriteDateMap.entrySet()) { - propsCopy.put(entry.getKey(), entry.getValue()); - } - } - // Preview this was done already in getPropertiesCached (the heavy - // performance must be done in getPropertiesCached) - // but we need to set the ticket when it's an alfresco generated preview - // logger.info("setting Preview"); - String[] aspects = getAspects(nodeRef); - if (nodeType.equals(CCConstants.CCM_TYPE_IO)) { - String renderServiceUrlPreview = URLTool.getRenderServiceURL(nodeRef.getId(), true); - if (renderServiceUrlPreview == null) { - // prefer alfresco thumbnail - String thumbnailUrl = (String) propsCopy.get(CCConstants.CM_ASSOC_THUMBNAILS); - if (thumbnailUrl != null && !thumbnailUrl.trim().equals("")) { - - // prevent Browser Caching: - thumbnailUrl = UrlTool.setParam(thumbnailUrl, "dontcache", new Long(System.currentTimeMillis()).toString()); - propsCopy.put(CCConstants.CM_ASSOC_THUMBNAILS, thumbnailUrl); - } + } catch (Throwable t) { - } + } + } - /** - * for Collections Ref Objects return original nodeid - * @TODO its a association so it could be multivalue - */ - if(Arrays.asList(aspects).contains(CCConstants.CCM_ASPECT_COLLECTION_IO_REFERENCE)){ - AuthenticationUtil.runAsSystem(new RunAsWork() { - - @Override - public Void doWork() throws Exception{ - try { - List assocNode = getAssociationNodeIds(nodeRef, CCConstants.CM_ASSOC_ORIGINAL); - if(assocNode.size() > 0){ - String originalNodeId = assocNode.get(0).getId(); - propsCopy.put(CCConstants.CM_ASSOC_ORIGINAL, originalNodeId); - } - } catch (Throwable t) { - throw new Exception(t); - } - return null; - } - }); - } + for (Map.Entry entry : addAndOverwriteDateMap.entrySet()) { + propsCopy.put(entry.getKey(), entry.getValue()); + } + } + // Preview this was done already in getPropertiesCached (the heavy + // performance must be done in getPropertiesCached) + // but we need to set the ticket when it's an alfresco generated preview + // logger.info("setting Preview"); + String[] aspects = getAspects(nodeRef); + if (nodeType.equals(CCConstants.CCM_TYPE_IO)) { + String renderServiceUrlPreview = URLTool.getRenderServiceURL(nodeRef.getId(), true); + if (renderServiceUrlPreview == null) { + // prefer alfresco thumbnail + String thumbnailUrl = (String) propsCopy.get(CCConstants.CM_ASSOC_THUMBNAILS); + if (thumbnailUrl != null && !thumbnailUrl.trim().equals("")) { + + // prevent Browser Caching: + thumbnailUrl = UrlTool.setParam(thumbnailUrl, "dontcache", new Long(System.currentTimeMillis()).toString()); + propsCopy.put(CCConstants.CM_ASSOC_THUMBNAILS, thumbnailUrl); + } - } + } + + /** + * for Collections Ref Objects return original nodeid + * @TODO its a association so it could be multivalue + */ + if (Arrays.asList(aspects).contains(CCConstants.CCM_ASPECT_COLLECTION_IO_REFERENCE)) { + AuthenticationUtil.runAsSystem(new RunAsWork() { + + @Override + public Void doWork() throws Exception { + try { + List assocNode = getAssociationNodeIds(nodeRef, CCConstants.CM_ASSOC_ORIGINAL); + if (assocNode.size() > 0) { + String originalNodeId = assocNode.get(0).getId(); + propsCopy.put(CCConstants.CM_ASSOC_ORIGINAL, originalNodeId); + } + } catch (Throwable t) { + throw new Exception(t); + } + return null; + } + }); + } + + } - // setting ticket for map icon url - if (nodeType.equals(CCConstants.CCM_TYPE_MAP)) { - String iconUrl = (String) propsCopy.get(CCConstants.CCM_PROP_MAP_ICON); - if (iconUrl != null) { - String paramToken = (iconUrl.contains("?")) ? "&" : "?"; - iconUrl = iconUrl + paramToken + "ticket=" + authenticationInfo.get(CCConstants.AUTH_TICKET); - // prevent Browser Caching: - iconUrl = UrlTool.setParam(iconUrl, "dontcache", new Long(System.currentTimeMillis()).toString()); + // setting ticket for map icon url + if (nodeType.equals(CCConstants.CCM_TYPE_MAP)) { + String iconUrl = (String) propsCopy.get(CCConstants.CCM_PROP_MAP_ICON); + if (iconUrl != null) { + String paramToken = (iconUrl.contains("?")) ? "&" : "?"; + iconUrl = iconUrl + paramToken + "ticket=" + authenticationInfo.get(CCConstants.AUTH_TICKET); + // prevent Browser Caching: + iconUrl = UrlTool.setParam(iconUrl, "dontcache", new Long(System.currentTimeMillis()).toString()); - propsCopy.put(CCConstants.CCM_PROP_MAP_ICON, iconUrl); - } - } + propsCopy.put(CCConstants.CCM_PROP_MAP_ICON, iconUrl); + } + } - if (nodeType.equals(CCConstants.CCM_TYPE_MAP) || nodeType.equals(CCConstants.CM_TYPE_FOLDER)) { + if (nodeType.equals(CCConstants.CCM_TYPE_MAP) || nodeType.equals(CCConstants.CM_TYPE_FOLDER)) { - // Information if write is allowed (important for DragDropComponent) - // and drawRelations - HashMap permissions = hasAllPermissions(nodeRef.getId(), new String[] { PermissionService.WRITE, PermissionService.ADD_CHILDREN }); - for (Map.Entry entry : permissions.entrySet()) { - propsCopy.put(entry.getKey(), entry.getValue().toString()); - } + // Information if write is allowed (important for DragDropComponent) + // and drawRelations + Map permissions = hasAllPermissions(nodeRef.getId(), new String[]{PermissionService.WRITE, PermissionService.ADD_CHILDREN}); + for (Map.Entry entry : permissions.entrySet()) { + propsCopy.put(entry.getKey(), entry.getValue().toString()); + } - // for the system folder: these are created in german and english - // language. - // we can not cache it, cause cache mechanism is not able to handle - // multiple lang props - Object mlfolderTitleObject = nodeService.getProperty(nodeRef, QName.createQName(CCConstants.CM_PROP_C_TITLE)); - String mlFolderTitle = formatData(nodeType, CCConstants.CM_PROP_C_TITLE, mlfolderTitleObject, - (String) propsCopy.get(CCConstants.CM_PROP_METADATASET_EDU_METADATASET)); - propsCopy.put(CCConstants.CM_PROP_C_TITLE, mlFolderTitle); - } + // for the system folder: these are created in german and english + // language. + // we can not cache it, cause cache mechanism is not able to handle + // multiple lang props + Object mlfolderTitleObject = nodeService.getProperty(nodeRef, QName.createQName(CCConstants.CM_PROP_C_TITLE)); + String mlFolderTitle = formatData(nodeType, CCConstants.CM_PROP_C_TITLE, mlfolderTitleObject, + (String) propsCopy.get(CCConstants.CM_PROP_METADATASET_EDU_METADATASET)); + propsCopy.put(CCConstants.CM_PROP_C_TITLE, mlFolderTitle); + } - // remote object - if (nodeType.equals(CCConstants.CCM_TYPE_REMOTEOBJECT) && isResolveRemoteObjects()) { - logger.info("BEGIN TYPE is REMOTEOBJECT"); - - String remoteNodeId = (String) propsCopy.get(CCConstants.CCM_PROP_REMOTEOBJECT_NODEID); - String remoteRepository = (String) propsCopy.get(CCConstants.CCM_PROP_REMOTEOBJECT_REPOSITORYID); - // logger.info("THE MAGIC KEY"+CCConstants.CCM_PROP_REMOTEOBJECT_NODEID); - logger.info("remoteRepository: " + remoteRepository + " remoteNodeId:" + remoteNodeId); - ApplicationInfo remoteRepInfo = ApplicationInfoList.getRepositoryInfoById(remoteRepository); - if (remoteRepInfo == null) { - logger.error("No ApplicationInfo found for Repository:" + remoteRepository + " and remoteNodeId:" + remoteNodeId); - return null; - } - else if(remoteRepInfo.isRemoteAlfresco()){ - AuthenticatorRemoteRepository arr = new AuthenticatorRemoteRepository(); - // when repository got no Authentication - HashMap remoteAuthInfo = null; - if (remoteRepInfo.getAuthenticationwebservice() != null && !remoteRepInfo.getAuthenticationwebservice().equals("")) { - try { + // remote object + if (nodeType.equals(CCConstants.CCM_TYPE_REMOTEOBJECT) && isResolveRemoteObjects()) { + log.info("BEGIN TYPE is REMOTEOBJECT"); + + String remoteNodeId = (String) propsCopy.get(CCConstants.CCM_PROP_REMOTEOBJECT_NODEID); + String remoteRepository = (String) propsCopy.get(CCConstants.CCM_PROP_REMOTEOBJECT_REPOSITORYID); + // logger.info("THE MAGIC KEY"+CCConstants.CCM_PROP_REMOTEOBJECT_NODEID); + log.info("remoteRepository: " + remoteRepository + " remoteNodeId:" + remoteNodeId); + ApplicationInfo remoteRepInfo = ApplicationInfoList.getRepositoryInfoById(remoteRepository); + if (remoteRepInfo == null) { + log.error("No ApplicationInfo found for Repository:" + remoteRepository + " and remoteNodeId:" + remoteNodeId); + return null; + } else if (remoteRepInfo.isRemoteAlfresco()) { + AuthenticatorRemoteRepository arr = new AuthenticatorRemoteRepository(); + // when repository got no Authentication + if (remoteRepInfo.getAuthenticationwebservice() != null && !remoteRepInfo.getAuthenticationwebservice().equals("")) { + try { AuthenticatorRemoteAppResult arar = arr.getAuthInfoForApp(authenticationInfo.get(CCConstants.AUTH_USERNAME), remoteRepInfo); - remoteAuthInfo = arar.getAuthenticationInfo(); - } catch (Throwable e) { - logger.error("It seems that repository id:" + remoteRepInfo.getAppId() + " is not reachable:" + e.getMessage()+". Check the configured value of "+ApplicationInfo.KEY_AUTHENTICATIONWEBSERVICE); - return null; - } - } else { - // TODO check if that is right - remoteAuthInfo = authenticationInfo; - } + } catch (Throwable e) { + log.error("It seems that repository id:" + remoteRepInfo.getAppId() + " is not reachable:" + e.getMessage() + ". Check the configured value of " + ApplicationInfo.KEY_AUTHENTICATIONWEBSERVICE); + return null; + } + } else { + // TODO check if that is right + } - HashMap result = null; - try { - MCBaseClient mcBaseClient = RepoFactory.getInstance(remoteRepInfo.getAppId(), authenticationInfo); + Map result = null; + try { + MCBaseClient mcBaseClient = RepoFactory.getInstance(remoteRepInfo.getAppId(), authenticationInfo); - // only when the user got remote permissions - if (mcBaseClient instanceof MCAlfrescoBaseClient) { - if (((MCAlfrescoBaseClient) mcBaseClient).hasPermissions(remoteNodeId, authenticationInfo.get(CCConstants.AUTH_USERNAME), - new String[] { "Read" })) { + // only when the user got remote permissions + if (mcBaseClient instanceof MCAlfrescoBaseClient) { + if (((MCAlfrescoBaseClient) mcBaseClient).hasPermissions(remoteNodeId, authenticationInfo.get(CCConstants.AUTH_USERNAME), + new String[]{"Read"})) { - result = mcBaseClient.getProperties(remoteNodeId); - } - } else { - result = mcBaseClient.getProperties(remoteNodeId); - } + result = mcBaseClient.getProperties(remoteNodeId); + } + } else { + result = mcBaseClient.getProperties(remoteNodeId); + } - } catch (Exception e) { - logger.error(e.getMessage(), e); - } + } catch (Exception e) { + log.error(e.getMessage(), e); + } - if (result != null) { - result.put(CCConstants.VIRT_PROP_ISREMOTE_OBJECT, "true"); - result.put(CCConstants.VIRT_PROP_REMOTE_OBJECT_NODEID, nodeRef.getId()); - } + if (result != null) { + result.put(CCConstants.VIRT_PROP_ISREMOTE_OBJECT, "true"); + result.put(CCConstants.VIRT_PROP_REMOTE_OBJECT_NODEID, nodeRef.getId()); + } - // set AuthentificationInfo back to init values - serviceRegistry.getAuthenticationService().validate(authenticationInfo.get(CCConstants.AUTH_TICKET)); - logger.debug("returning remote object"); - return result; - } - } - HashMap propsOutput = propsCopy; - // @TODO: remove all of this from/to multivalue - ValueTool.getMultivalue(propsOutput); - for (PropertiesGetInterceptor i : PropertiesInterceptorFactory.getPropertiesGetInterceptors()) { - propsOutput = new HashMap<>(i.beforeDeliverProperties(PropertiesInterceptorFactory.getPropertiesContext( - nodeRef, - propsOutput, - Arrays.asList(aspects), - null, null) - )); - } + // set AuthentificationInfo back to init values + serviceRegistry.getAuthenticationService().validate(authenticationInfo.get(CCConstants.AUTH_TICKET)); + log.debug("returning remote object"); + return result; + } + } + Map propsOutput = propsCopy; + // @TODO: remove all of this from/to multivalue + ValueTool.getMultivalue(propsOutput); + for (PropertiesGetInterceptor i : PropertiesInterceptorFactory.getPropertiesGetInterceptors()) { + propsOutput = new HashMap<>(i.beforeDeliverProperties(PropertiesInterceptorFactory.getPropertiesContext( + nodeRef, + propsOutput, + Arrays.asList(aspects), + null, null) + )); + } - /** - * attach the display name suffix - */ - if(hasMds) { - MetadataHelper.addVirtualDisplaynameProperties(mds, propsOutput); - } + /** + * attach the display name suffix + */ + if (hasMds) { + MetadataHelper.addVirtualDisplaynameProperties(mds, propsOutput); + } - // @TODO: remove all of this from/to multivalue - ValueTool.toMultivalue(propsOutput); + // @TODO: remove all of this from/to multivalue + ValueTool.toMultivalue(propsOutput); - return propsOutput; - } + return propsOutput; + } - /** - * no user depended information like username and ticket will be set cause - * it will be cached so no (content url, icon url) will be set - * here (cause it contains the ticket info) also no user depended permission - * checks will be done - * - * @param nodeRef - * @return - * @throws Exception - */ - public HashMap getPropertiesCached(NodeRef nodeRef, boolean getFromCache, boolean checkModified, boolean ifNotInCacheReturnNull) throws Exception { - return getPropertiesCached(nodeRef, getFromCache, checkModified, ifNotInCacheReturnNull, nodeService); - } - public HashMap getPropertiesCached(NodeRef nodeRef, boolean getFromCache, boolean checkModified, boolean ifNotInCacheReturnNull, NodeService service) - throws Exception { - - Map propMap = null; - Cache repCache = new RepositoryCache(); - // only get object by cache for one storeRef cause we take only the - // nodeId as key - if (getFromCache && nodeRef.getStoreRef().equals(storeRef)) { - - HashMap propsFromCache = (HashMap) repCache.get(nodeRef.getId()); - - if (propsFromCache != null) { - - // check if thumbnail generation was processing if true - // occurs when i.e. when copying a node - boolean refreshThumbnail = new Boolean((String) propsFromCache.get(CCConstants.KEY_PREVIEW_GENERATION_RUNS)); - - if (checkModified) { - - Date mdate = (Date) nodeService.getProperty(nodeRef, QName.createQName(CCConstants.CM_PROP_C_MODIFIED)); - - Long orginalModTime = null; - if (mdate != null) { - orginalModTime = mdate.getTime(); - } - - String cacheModified = (String) propsFromCache.get(CCConstants.CC_CACHE_MILLISECONDS_KEY); - Long cachedModTime = null; - try { - cachedModTime = new Long(cacheModified); - } catch (Exception e) { - - } - - if (cachedModTime != null && orginalModTime != null && cachedModTime.longValue() == orginalModTime.longValue() && !refreshThumbnail) { - return propsFromCache; - } else { - logger.debug("CACHE modified Date changed! refreshing:" + nodeRef.getId() + " cachedModTime:" + cachedModTime + " orginalModTime:" - + orginalModTime + " refreshThumbnail:" + refreshThumbnail); - } - - } else { - return propsFromCache; - } - - } else if (ifNotInCacheReturnNull) { - return null; - } - - } + /** + * no user depended information like username and ticket will be set cause + * it will be cached so no (content url, icon url) will be set + * here (cause it contains the ticket info) also no user depended permission + * checks will be done + * + * @param nodeRef + * @return + * @throws Exception + */ + public Map getPropertiesCached(NodeRef nodeRef, boolean getFromCache, boolean checkModified, boolean ifNotInCacheReturnNull) throws Exception { + return getPropertiesCached(nodeRef, getFromCache, checkModified, ifNotInCacheReturnNull, nodeService); + } - if (propMap == null){ - propMap = service.getProperties(nodeRef); - } - - HashMap properties = new HashMap(); - String nodeType = service.getType(nodeRef).toString(); - - // Properties: - for (QName qname : propMap.keySet()) { - - String propName = qname.toString(); - - // Properties - Serializable object = propMap.get(qname); - - // allow only Number and String Types other Types will be handeled - // in the following code - if (object instanceof String || object instanceof Date || object instanceof Number || object instanceof List || object instanceof Boolean - || object instanceof MLText || object instanceof NodeRef) { - - String metadataSetId = (String) propMap.get(QName.createQName(CCConstants.CM_PROP_METADATASET_EDU_METADATASET)); - String value = formatData(nodeType, propName, object, metadataSetId); - - // add formated replicationsourcetimestamp - if (propName.equals(CCConstants.CCM_PROP_IO_REPLICATIONSOURCETIMESTAMP) && !value.equals("") && !value.trim().equals("0000-00-00T00:00:00Z")) { - - try { - - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:sss"); - Date date = sdf.parse((String) value); - DateFormat df = ServerConstants.DATEFORMAT_WITHOUT_TIME; - String formatedDate = df.format(date); - properties.put(CCConstants.CCM_PROP_IO_REPLICATIONSOURCETIMESTAMPFORMATED, formatedDate); - - } catch (ParseException e) { - logger.error(value + " was no valid date of format " + "yyyy-MM-dd'T'HH:mm:sss"); - } + public Map getPropertiesCached(NodeRef nodeRef, boolean getFromCache, boolean checkModified, boolean ifNotInCacheReturnNull, NodeService service) + throws Exception { - } + Map propMap = null; + Cache repCache = new RepositoryCache(); + // only get object by cache for one storeRef cause we take only the + // nodeId as key + if (getFromCache && nodeRef.getStoreRef().equals(storeRef)) { - properties.put(propName, value); + Map propsFromCache = repCache.get(nodeRef.getId()); - // put a ISO String when its a date value - if (object instanceof Date) { - properties.put(propName + CCConstants.ISODATE_SUFFIX, ISO8601DateFormat.format((Date) object)); - } + if (propsFromCache != null) { - // VCard - HashMap vcard = VCardConverter.getVCardHashMap(nodeType, propName, value); - if (vcard != null && vcard.size() > 0) properties.putAll(vcard); - - } + // check if thumbnail generation was processing if true + // occurs when i.e. when copying a node + boolean refreshThumbnail = new Boolean((String) propsFromCache.get(CCConstants.KEY_PREVIEW_GENERATION_RUNS)); - } + if (checkModified) { - if (properties.containsKey(CCConstants.CM_PROP_VERSIONABLELABEL)) { - properties.put(CCConstants.CM_ASPECT_VERSIONABLE, "true"); - } + Date mdate = (Date) nodeService.getProperty(nodeRef, QName.createQName(CCConstants.CM_PROP_C_MODIFIED)); - // MimeType - // we run as system because the current user may not has enough permissions to access content - properties.put(CCConstants.ALFRESCO_MIMETYPE, getAlfrescoMimetype(nodeRef)); - - - // MapRelations - if (nodeType.equals(CCConstants.CCM_TYPE_MAPRELATION)) { - List relSrcList = nodeService.getTargetAssocs(nodeRef, QName.createQName(CCConstants.CCM_ASSOC_RELSOURCE)); - List relTargetList = nodeService.getTargetAssocs(nodeRef, QName.createQName(CCConstants.CCM_ASSOC_RELTARGET)); - if ((relSrcList != null && relSrcList.size() > 0) && relTargetList != null && relTargetList.size() > 0) { - logger.debug("relSrcList.get(0).getTargetRef().getId():" + relSrcList.get(0).getTargetRef().getId() + " " - + nodeService.getType(relSrcList.get(0).getTargetRef())); - logger.debug("relTargetList.get(0).getTargetRef().getId():" + relTargetList.get(0).getTargetRef().getId() + " " - + nodeService.getType(relTargetList.get(0).getTargetRef())); - properties.put(CCConstants.CCM_ASSOC_RELSOURCE, relSrcList.get(0).getTargetRef().getId()); - properties.put(CCConstants.CCM_ASSOC_RELTARGET, relTargetList.get(0).getTargetRef().getId()); - } - } - Set aspects = service.getAspects(nodeRef); - NodeServiceHelper.addVirtualProperties( - nodeType, - aspects.stream().map(QName::toString).collect(Collectors.toList()), - properties - ); - - // Preview - if (nodeType.equals(CCConstants.CCM_TYPE_IO)) { - //@todo 5.1: check if this is needed since it only is used in the PreviewServlet - /* + Long orginalModTime = null; + if (mdate != null) { + orginalModTime = mdate.getTime(); + } + + String cacheModified = (String) propsFromCache.get(CCConstants.CC_CACHE_MILLISECONDS_KEY); + Long cachedModTime = null; + try { + cachedModTime = new Long(cacheModified); + } catch (Exception e) { + + } + + if (cachedModTime != null && orginalModTime != null && cachedModTime.longValue() == orginalModTime.longValue() && !refreshThumbnail) { + return propsFromCache; + } else { + log.debug("CACHE modified Date changed! refreshing:" + nodeRef.getId() + " cachedModTime:" + cachedModTime + " orginalModTime:" + + orginalModTime + " refreshThumbnail:" + refreshThumbnail); + } + + } else { + return propsFromCache; + } + + } else if (ifNotInCacheReturnNull) { + return null; + } + + } + + if (propMap == null) { + propMap = service.getProperties(nodeRef); + } + + Map properties = new HashMap<>(); + String nodeType = service.getType(nodeRef).toString(); + + // Properties: + for (QName qname : propMap.keySet()) { + + String propName = qname.toString(); + + // Properties + Serializable object = propMap.get(qname); + + // allow only Number and String Types other Types will be handeled + // in the following code + if (object instanceof String || object instanceof Date || object instanceof Number || object instanceof List || object instanceof Boolean + || object instanceof MLText || object instanceof NodeRef) { + + String metadataSetId = (String) propMap.get(QName.createQName(CCConstants.CM_PROP_METADATASET_EDU_METADATASET)); + String value = formatData(nodeType, propName, object, metadataSetId); + + // add formated replicationsourcetimestamp + if (propName.equals(CCConstants.CCM_PROP_IO_REPLICATIONSOURCETIMESTAMP) && !value.equals("") && !value.trim().equals("0000-00-00T00:00:00Z")) { + + try { + + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:sss"); + Date date = sdf.parse((String) value); + DateFormat df = ServerConstants.DATEFORMAT_WITHOUT_TIME; + String formatedDate = df.format(date); + properties.put(CCConstants.CCM_PROP_IO_REPLICATIONSOURCETIMESTAMPFORMATED, formatedDate); + + } catch (ParseException e) { + log.error(value + " was no valid date of format " + "yyyy-MM-dd'T'HH:mm:sss"); + } + + } + + properties.put(propName, value); + + // put a ISO String when its a date value + if (object instanceof Date) { + properties.put(propName + CCConstants.ISODATE_SUFFIX, ISO8601DateFormat.format((Date) object)); + } + + // VCard + Map vcard = VCardConverter.getVCardMap(nodeType, propName, value); + if (vcard != null && vcard.size() > 0) properties.putAll(vcard); + + } + + } + + if (properties.containsKey(CCConstants.CM_PROP_VERSIONABLELABEL)) { + properties.put(CCConstants.CM_ASPECT_VERSIONABLE, "true"); + } + + // MimeType + // we run as system because the current user may not has enough permissions to access content + properties.put(CCConstants.ALFRESCO_MIMETYPE, getAlfrescoMimetype(nodeRef)); + + + // MapRelations + if (nodeType.equals(CCConstants.CCM_TYPE_MAPRELATION)) { + List relSrcList = nodeService.getTargetAssocs(nodeRef, QName.createQName(CCConstants.CCM_ASSOC_RELSOURCE)); + List relTargetList = nodeService.getTargetAssocs(nodeRef, QName.createQName(CCConstants.CCM_ASSOC_RELTARGET)); + if ((relSrcList != null && relSrcList.size() > 0) && relTargetList != null && relTargetList.size() > 0) { + log.debug("relSrcList.get(0).getTargetRef().getId():" + relSrcList.get(0).getTargetRef().getId() + " " + + nodeService.getType(relSrcList.get(0).getTargetRef())); + log.debug("relTargetList.get(0).getTargetRef().getId():" + relTargetList.get(0).getTargetRef().getId() + " " + + nodeService.getType(relTargetList.get(0).getTargetRef())); + properties.put(CCConstants.CCM_ASSOC_RELSOURCE, relSrcList.get(0).getTargetRef().getId()); + properties.put(CCConstants.CCM_ASSOC_RELTARGET, relTargetList.get(0).getTargetRef().getId()); + } + } + Set aspects = service.getAspects(nodeRef); + NodeServiceHelper.addVirtualProperties( + nodeType, + aspects.stream().map(QName::toString).collect(Collectors.toList()), + properties + ); + + // Preview + if (nodeType.equals(CCConstants.CCM_TYPE_IO)) { + //@todo 5.1: check if this is needed since it only is used in the PreviewServlet + /* GetPreviewResult prevResult = getPreviewUrl(nodeRef.getStoreRef(), nodeRef.getId()); if (prevResult.getType().equals(GetPreviewResult.TYPE_USERDEFINED)) { @@ -1320,2437 +1293,2380 @@ public HashMap getPropertiesCached(NodeRef nodeRef, boolean getF properties.remove(CCConstants.KEY_PREVIEW_GENERATION_RUNS); } */ - Consumer fetchCounts = (ref) -> { - List usages = this.getChildrenByAssociationNodeIds(ref.getStoreRef(), ref.getId(), CCConstants.CCM_ASSOC_USAGEASPECT_USAGES); - if (usages != null) { - properties.put(CCConstants.VIRT_PROP_USAGECOUNT, "" + usages.size()); - } - List childs = this.getChildrenByAssociationNodeIds(ref.getStoreRef(), ref.getId(), CCConstants.CCM_ASSOC_CHILDIO); - if (childs != null) { - properties.put(CCConstants.VIRT_PROP_CHILDOBJECTCOUNT, "" + childs.size()); - } - }; - if(aspects.contains(QName.createQName(CCConstants.CCM_ASPECT_COLLECTION_IO_REFERENCE))) { - AuthenticationUtil.runAsSystem(() -> { - try { - fetchCounts.accept( - new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, - (String) service.getProperty(nodeRef, QName.createQName(CCConstants.CCM_PROP_IO_ORIGINAL)) - ) - ); - }catch (Throwable ignored) { - // ignored, original might be deleted - } - return null; - }); - } else { - fetchCounts.accept(nodeRef); - } - List comments = this.getChildrenByAssociationNodeIds(nodeRef.getStoreRef(),nodeRef.getId(), CCConstants.CCM_ASSOC_COMMENT); - if (comments != null) { - properties.put(CCConstants.VIRT_PROP_COMMENTCOUNT,comments.size()); - } - - // add permalink - String version = (String) properties.get(CCConstants.LOM_PROP_LIFECYCLE_VERSION); - if (version == null) - version = (String) properties.get(CCConstants.CM_PROP_VERSIONABLELABEL); + Consumer fetchCounts = (ref) -> { + List usages = this.getChildrenByAssociationNodeIds(ref.getStoreRef(), ref.getId(), CCConstants.CCM_ASSOC_USAGEASPECT_USAGES); + if (usages != null) { + properties.put(CCConstants.VIRT_PROP_USAGECOUNT, "" + usages.size()); + } + List childs = this.getChildrenByAssociationNodeIds(ref.getStoreRef(), ref.getId(), CCConstants.CCM_ASSOC_CHILDIO); + if (childs != null) { + properties.put(CCConstants.VIRT_PROP_CHILDOBJECTCOUNT, "" + childs.size()); + } + }; + if (aspects.contains(QName.createQName(CCConstants.CCM_ASPECT_COLLECTION_IO_REFERENCE))) { + AuthenticationUtil.runAsSystem(() -> { + try { + fetchCounts.accept( + new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, + (String) service.getProperty(nodeRef, QName.createQName(CCConstants.CCM_PROP_IO_ORIGINAL)) + ) + ); + } catch (Throwable ignored) { + // ignored, original might be deleted + } + return null; + }); + } else { + fetchCounts.accept(nodeRef); + } + List comments = this.getChildrenByAssociationNodeIds(nodeRef.getStoreRef(), nodeRef.getId(), CCConstants.CCM_ASSOC_COMMENT); + if (comments != null) { + properties.put(CCConstants.VIRT_PROP_COMMENTCOUNT, comments.size()); + } - //String permaLink = URLTool.getBaseUrl() + "/node/" + nodeRef.getId(); - String permaLink = URLTool.getNgComponentsUrl()+"render/" + nodeRef.getId(); - permaLink = (version != null) ? permaLink + "/" + version : permaLink; - properties.put(CCConstants.VIRT_PROP_PERMALINK, permaLink); - } + // add permalink + String version = (String) properties.get(CCConstants.LOM_PROP_LIFECYCLE_VERSION); + if (version == null) + version = (String) properties.get(CCConstants.CM_PROP_VERSIONABLELABEL); - if (nodeType.equals(CCConstants.CCM_TYPE_MAP)) { - String iconUrl = URLTool.getBrowserURL(nodeRef, CCConstants.CCM_PROP_MAP_ICON); - if (iconUrl != null) { - properties.put(CCConstants.CCM_PROP_MAP_ICON, iconUrl); - } - } + //String permaLink = URLTool.getBaseUrl() + "/node/" + nodeRef.getId(); + String permaLink = URLTool.getNgComponentsUrl() + "render/" + nodeRef.getId(); + permaLink = (version != null) ? permaLink + "/" + version : permaLink; + properties.put(CCConstants.VIRT_PROP_PERMALINK, permaLink); + } - // we can cache primary parent here, instead of parentid which differs - // from the content - if (nodeType.equals(CCConstants.CCM_TYPE_IO) || nodeType.equals(CCConstants.CCM_TYPE_MAP) || nodeType.equals(CCConstants.CM_TYPE_FOLDER) || nodeType.equals(CCConstants.CCM_TYPE_TOOL_INSTANCE)) { - ChildAssociationRef parentNodeRef = nodeService.getPrimaryParent(nodeRef); - properties.put(CCConstants.VIRT_PROP_PRIMARYPARENT_NODEID, parentNodeRef.getParentRef().getId()); - } + if (nodeType.equals(CCConstants.CCM_TYPE_MAP)) { + String iconUrl = URLTool.getBrowserURL(nodeRef, CCConstants.CCM_PROP_MAP_ICON); + if (iconUrl != null) { + properties.put(CCConstants.CCM_PROP_MAP_ICON, iconUrl); + } + } - // NodeType - properties.put(CCConstants.NODETYPE, nodeService.getType(nodeRef).toString()); - properties.put(CCConstants.NODEID, nodeRef.getId()); - - // Repository Id is in API Mode always the home repository - properties.put(CCConstants.REPOSITORY_ID, repId); - properties.put(CCConstants.REPOSITORY_CAPTION, appInfo.getAppCaption()); - - buildUpProperties(properties); - HashMap propertiesFinal = properties; - // cache - if (nodeRef.getStoreRef().equals(storeRef)) { - Date mdate = (Date) propMap.get(QName.createQName(CCConstants.CM_PROP_C_MODIFIED)); - if (mdate != null) { - propertiesFinal.put(CCConstants.CC_CACHE_MILLISECONDS_KEY, new Long(mdate.getTime()).toString()); - for(PropertiesGetInterceptor i : PropertiesInterceptorFactory.getPropertiesGetInterceptors()) { - propertiesFinal = new HashMap<>(i.beforeCacheProperties(PropertiesInterceptorFactory.getPropertiesContext(nodeRef, propertiesFinal, - aspects.stream().map(QName::toString).collect(Collectors.toList()), null, null))); - } - repCache.put(nodeRef.getId(), propertiesFinal); - } - } - return propertiesFinal; - } + // we can cache primary parent here, instead of parentid which differs + // from the content + if (nodeType.equals(CCConstants.CCM_TYPE_IO) || nodeType.equals(CCConstants.CCM_TYPE_MAP) || nodeType.equals(CCConstants.CM_TYPE_FOLDER) || nodeType.equals(CCConstants.CCM_TYPE_TOOL_INSTANCE)) { + ChildAssociationRef parentNodeRef = nodeService.getPrimaryParent(nodeRef); + properties.put(CCConstants.VIRT_PROP_PRIMARYPARENT_NODEID, parentNodeRef.getParentRef().getId()); + } - public String getAlfrescoMimetype(NodeRef nodeRef) { - return AuthenticationUtil.runAsSystem(() -> { - ContentReader contentReader = contentService.getReader(nodeRef, QName.createQName(CCConstants.CM_PROP_CONTENT)); - if (contentReader != null) { - return contentReader.getMimetype(); - } - return null; - }); - } + // NodeType + properties.put(CCConstants.NODETYPE, nodeService.getType(nodeRef).toString()); + properties.put(CCConstants.NODEID, nodeRef.getId()); + + // Repository Id is in API Mode always the home repository + properties.put(CCConstants.REPOSITORY_ID, repId); + properties.put(CCConstants.REPOSITORY_CAPTION, appInfo.getAppCaption()); + + buildUpProperties(properties); + Map propertiesFinal = properties; + // cache + if (nodeRef.getStoreRef().equals(storeRef)) { + Date mdate = (Date) propMap.get(QName.createQName(CCConstants.CM_PROP_C_MODIFIED)); + if (mdate != null) { + propertiesFinal.put(CCConstants.CC_CACHE_MILLISECONDS_KEY, new Long(mdate.getTime()).toString()); + for (PropertiesGetInterceptor i : PropertiesInterceptorFactory.getPropertiesGetInterceptors()) { + propertiesFinal = new HashMap<>(i.beforeCacheProperties(PropertiesInterceptorFactory.getPropertiesContext(nodeRef, propertiesFinal, + aspects.stream().map(QName::toString).collect(Collectors.toList()), null, null))); + } + repCache.put(nodeRef.getId(), propertiesFinal); + } + } + return propertiesFinal; + } - public String getProperty(StoreRef store, String nodeId, String property) { - return this.getProperty(store.getProtocol(), store.getIdentifier(), nodeId, property); - } + public String getAlfrescoMimetype(NodeRef nodeRef) { + return AuthenticationUtil.runAsSystem(() -> { + ContentReader contentReader = contentService.getReader(nodeRef, QName.createQName(CCConstants.CM_PROP_CONTENT)); + if (contentReader != null) { + return contentReader.getMimetype(); + } + return null; + }); + } - /** - * @TODO Same handling with List and MLText properties like in getProperties - * ->getValue - */ - public String getProperty(String storeProtocol, String storeIdentifier, String nodeId, String property) { - Serializable val = nodeService.getProperty(new NodeRef(new StoreRef(storeProtocol, storeIdentifier), nodeId), QName.createQName(property)); - if (val != null) { - - String result = null; - if (val instanceof List && ((List) val).size() > 0) { - - for (Object value : (List) val) { - if (result != null) - result += CCConstants.MULTIVALUE_SEPARATOR; - if (value != null) { - if (result != null) - result += value.toString(); //getMultiLangCleaned(value.toString()); - else - result = value.toString(); //getMultiLangCleaned(value.toString()); - } - } + public String getProperty(StoreRef store, String nodeId, String property) { + return this.getProperty(store.getProtocol(), store.getIdentifier(), nodeId, property); + } - }else if(val instanceof NodeRef){ - result = ((NodeRef)val).toString(); - }else { - result = val.toString(); //getMultiLangCleaned(val.toString()); - } + /** + * @TODO Same handling with List and MLText properties like in getProperties + * ->getValue + */ + public String getProperty(String storeProtocol, String storeIdentifier, String nodeId, String property) { + Serializable val = nodeService.getProperty(new NodeRef(new StoreRef(storeProtocol, storeIdentifier), nodeId), QName.createQName(property)); + if (val != null) { + + String result = null; + if (val instanceof List && ((List) val).size() > 0) { + + for (Object value : (List) val) { + if (result != null) + result += CCConstants.MULTIVALUE_SEPARATOR; + if (value != null) { + if (result != null) + result += value.toString(); //getMultiLangCleaned(value.toString()); + else + result = value.toString(); //getMultiLangCleaned(value.toString()); + } + } - return result; + } else if (val instanceof NodeRef) { + result = ((NodeRef) val).toString(); + } else { + result = val.toString(); //getMultiLangCleaned(val.toString()); + } - } else { - return null; - } - } + return result; - private String getMultiLangCleaned(String value) { + } else { + return null; + } + } - String result = new String(value); + private String getMultiLangCleaned(String value) { - // edu-sharing properties multilang = true {de_DE=Realschule} - if (result != null && result.matches("\\{[a-z][a-z]_[A-Z][A-Z]=.*\\}")) { - String[] splitted = result.split("="); - result = splitted[1].replace("}", ""); - } + String result = new String(value); - if (result != null && result.matches("\\{default=.*\\}")) { - String[] splitted = result.split("="); - result = splitted[1].replace("}", ""); - } + // edu-sharing properties multilang = true {de_DE=Realschule} + if (result != null && result.matches("\\{[a-z][a-z]_[A-Z][A-Z]=.*\\}")) { + String[] splitted = result.split("="); + result = splitted[1].replace("}", ""); + } - return result; - } + if (result != null && result.matches("\\{default=.*\\}")) { + String[] splitted = result.split("="); + result = splitted[1].replace("}", ""); + } - /** - * returns the simple alfresco properties without special handling - * - * @param nodeId - * @return - */ - public HashMap getPropertiesSimple(StoreRef givenStoreRef, String nodeId) { + return result; + } - NodeRef nodeRef = new NodeRef(givenStoreRef, nodeId); - HashMap properties = new HashMap(); - Map propMap = nodeService.getProperties(nodeRef); + /** + * returns the simple alfresco properties without special handling + * + * @param nodeId + * @return + */ + public Map getPropertiesSimple(StoreRef givenStoreRef, String nodeId) { - String nodeType = nodeService.getType(nodeRef).toString(); - - // Properties - for (QName qname : propMap.keySet()) { + NodeRef nodeRef = new NodeRef(givenStoreRef, nodeId); + Map properties = new HashMap<>(); + Map propMap = nodeService.getProperties(nodeRef); - String propName = qname.toString(); - - // Properties - Serializable object = propMap.get(qname); + String nodeType = nodeService.getType(nodeRef).toString(); - if (object instanceof String || object instanceof Date || object instanceof Number || object instanceof List || object instanceof MLText) { + // Properties + for (QName qname : propMap.keySet()) { - String metadataSetId = (String) propMap.get(QName.createQName(CCConstants.CM_PROP_METADATASET_EDU_METADATASET)); + String propName = qname.toString(); - String value = formatData(nodeType, propName, object, metadataSetId); - properties.put(propName, value); - } - } + // Properties + Serializable object = propMap.get(qname); - properties.put(CCConstants.NODETYPE, nodeType); - properties.put(CCConstants.NODEID, nodeRef.getId()); + if (object instanceof String || object instanceof Date || object instanceof Number || object instanceof List || object instanceof MLText) { - buildUpProperties(properties); + String metadataSetId = (String) propMap.get(QName.createQName(CCConstants.CM_PROP_METADATASET_EDU_METADATASET)); - return properties; - } + String value = formatData(nodeType, propName, object, metadataSetId); + properties.put(propName, value); + } + } - /** - * returns the simple alfresco Properties without special handling - * - * @param nodeId - * @return - */ - public HashMap getPropertiesSimple(String nodeId) { - return getPropertiesSimple(storeRef, nodeId); - } + properties.put(CCConstants.NODETYPE, nodeType); + properties.put(CCConstants.NODEID, nodeRef.getId()); - public String getRootNode(StoreRef store) { - return nodeService.getRootNode(store).getId(); - } - - public void removeNode(String storeProtocol, String storeId, String nodeId) { - this.removeNode(new StoreRef(storeProtocol, storeId),nodeId); - } - - public void removeNode(StoreRef store, String nodeId) { - nodeService.deleteNode(new NodeRef(store, nodeId)); - } + buildUpProperties(properties); - public String getRootNodeId() { + return properties; + } - String result = null; - try { - result = null; + /** + * returns the simple alfresco Properties without special handling + * + * @param nodeId + * @return + */ + public Map getPropertiesSimple(String nodeId) { + return getPropertiesSimple(storeRef, nodeId); + } - // access from API Client always is the HomeRepository - ApplicationInfo appInfo = ApplicationInfoList.getHomeRepository(); + public String getRootNode(StoreRef store) { + return nodeService.getRootNode(store).getId(); + } - String adminUser = appInfo.getUsername(); - String tmpUser = authenticationInfo.get(CCConstants.AUTH_USERNAME); - if (!adminUser.equals(tmpUser)) { - result = getHomeFolderID(tmpUser); - }else if ("admin".equals(tmpUser)) { - result = getCompanyHomeNodeId(); - } + public void removeNode(String storeProtocol, String storeId, String nodeId) { + this.removeNode(new StoreRef(storeProtocol, storeId), nodeId); + } - } catch (Exception e) { - return null; - } + public void removeNode(StoreRef store, String nodeId) { + nodeService.deleteNode(new NodeRef(store, nodeId)); + } - return result; - } + public String getRootNodeId() { - public String getRepositoryRoot() throws Exception { - return nodeService.getRootNode(storeRef).getId(); - } + String result = null; + try { + result = null; - public List getChildAssociationByType(String storeProtocol,String storeId,String nodeId, String type){ - Set set = new HashSet(); - set.add(QName.createQName(type)); - return nodeService.getChildAssocs(new NodeRef(new StoreRef(storeProtocol,storeId),nodeId), set); - } - - public HashMap> getChildrenByType(String nodeId, String type) { - return this.getChildrenByType(storeRef, nodeId, type); - } + // access from API Client always is the HomeRepository + ApplicationInfo appInfo = ApplicationInfoList.getHomeRepository(); - public HashMap> getChildrenByType(StoreRef store, String nodeId, String type) { - - HashMap> result = new HashMap>(); - List childAssocList = nodeService.getChildAssocs(new NodeRef(store, nodeId)); - - // nodeService.getc - for (ChildAssociationRef child : childAssocList) { + String adminUser = appInfo.getUsername(); + String tmpUser = authenticationInfo.get(CCConstants.AUTH_USERNAME); + if (!adminUser.equals(tmpUser)) { + result = getHomeFolderID(tmpUser); + } else if ("admin".equals(tmpUser)) { + result = getCompanyHomeNodeId(); + } - String childType = nodeService.getType(child.getChildRef()).toString(); - if (childType.equals(type)) { + } catch (Exception e) { + return null; + } - HashMap resultProps = getPropertiesWithoutChildren(child.getChildRef()); - String childNodeId = child.getChildRef().getId(); - result.put(childNodeId, resultProps); + return result; + } - } - } - return result; - } - public List getChildrenByAssociationNodeIds(StoreRef store, String nodeId, String association) { - - List childAssocList = nodeService.getChildAssocs(new NodeRef(store, nodeId),QName.createQName(association), - RegexQNamePattern.MATCH_ALL); - List result=new ArrayList<>(); - for (ChildAssociationRef child : childAssocList) { - result.add(child.getChildRef()); - } - return result; - } + public String getRepositoryRoot() throws Exception { + return nodeService.getRootNode(storeRef).getId(); + } - public HashMap> getChildrenByAssociation(String nodeId, String association) { - return this.getChildrenByAssociation(storeRef, nodeId, association); - } + public List getChildAssociationByType(String storeProtocol, String storeId, String nodeId, String type) { + Set set = new HashSet(); + set.add(QName.createQName(type)); + return nodeService.getChildAssocs(new NodeRef(new StoreRef(storeProtocol, storeId), nodeId), set); + } - public HashMap> getChildrenByAssociation(String store, String nodeId, String association) { + public Map> getChildrenByType(String nodeId, String type) { + return this.getChildrenByType(storeRef, nodeId, type); + } - StoreRef storeRef = null; - if (store == null) { - storeRef = this.storeRef; - } else { - storeRef = new StoreRef(store); - } + public Map> getChildrenByType(StoreRef store, String nodeId, String type) { - return this.getChildrenByAssociation(storeRef, nodeId, association); - } + Map> result = new HashMap<>(); + List childAssocList = nodeService.getChildAssocs(new NodeRef(store, nodeId)); - public HashMap> getChildrenByAssociation(StoreRef store, String nodeId, String association) { - HashMap> result = new HashMap>(); - List childAssocList = nodeService.getChildAssocs(new NodeRef(store, nodeId), QName.createQName(association), - RegexQNamePattern.MATCH_ALL); - for (ChildAssociationRef child : childAssocList) { - HashMap resultProps = getPropertiesWithoutChildren(child.getChildRef()); - String childNodeId = child.getChildRef().getId(); - result.put(childNodeId, resultProps); - } - return result; - } + // nodeService.getc + for (ChildAssociationRef child : childAssocList) { - private HashMap getPropertiesWithoutChildren(NodeRef nodeRef) { - - Map childPropMap = nodeService.getProperties(nodeRef); - HashMap resultProps = new HashMap(); + String childType = nodeService.getType(child.getChildRef()).toString(); + if (childType.equals(type)) { - String nodeType = nodeService.getType(nodeRef).toString(); + Map resultProps = getPropertiesWithoutChildren(child.getChildRef()); + String childNodeId = child.getChildRef().getId(); + result.put(childNodeId, resultProps); - for (QName qname : childPropMap.keySet()) { + } + } + return result; + } - Serializable object = childPropMap.get(qname); + public List getChildrenByAssociationNodeIds(StoreRef store, String nodeId, String association) { - String metadataSetId = (String) childPropMap.get(QName.createQName(CCConstants.CM_PROP_METADATASET_EDU_METADATASET)); + List childAssocList = nodeService.getChildAssocs(new NodeRef(store, nodeId), QName.createQName(association), + RegexQNamePattern.MATCH_ALL); + List result = new ArrayList<>(); + for (ChildAssociationRef child : childAssocList) { + result.add(child.getChildRef()); + } + return result; + } - String value = formatData(nodeType, qname.toString(), object, metadataSetId); - resultProps.put(qname.toString(), value); + public Map> getChildrenByAssociation(String nodeId, String association) { + return this.getChildrenByAssociation(storeRef, nodeId, association); + } - // VCard - String type = nodeService.getType(nodeRef).toString(); - HashMap vcard = VCardConverter.getVCardHashMap(type, qname.toString(), value); - if (vcard != null && vcard.size() > 0) resultProps.putAll(vcard); + public Map> getChildrenByAssociation(String store, String nodeId, String association) { - } + StoreRef storeRef = null; + if (store == null) { + storeRef = this.storeRef; + } else { + storeRef = new StoreRef(store); + } - resultProps.put(CCConstants.REPOSITORY_ID, repId); - resultProps.put(CCConstants.REPOSITORY_CAPTION, appInfo.getAppCaption()); + return this.getChildrenByAssociation(storeRef, nodeId, association); + } - buildUpProperties(resultProps); + public Map> getChildrenByAssociation(StoreRef store, String nodeId, String association) { + Map> result = new HashMap<>(); + List childAssocList = nodeService.getChildAssocs(new NodeRef(store, nodeId), QName.createQName(association), + RegexQNamePattern.MATCH_ALL); + for (ChildAssociationRef child : childAssocList) { + Map resultProps = getPropertiesWithoutChildren(child.getChildRef()); + String childNodeId = child.getChildRef().getId(); + result.put(childNodeId, resultProps); + } + return result; + } - return resultProps; - } + private Map getPropertiesWithoutChildren(NodeRef nodeRef) { - public HashMap getChild(String parentId, String type, String property, String value) { - return this.getChild(storeRef, parentId, type, property, value); - } + Map childPropMap = nodeService.getProperties(nodeRef); + Map resultProps = new HashMap<>(); - /** - * this method returns the first child that matches the prop value pair it - * - * @param store - * @param parentId - * @param type - * @param property - * @param value - * @return - */ - public HashMap getChild(StoreRef store, String parentId, String type, String property, String value) { - HashMap> children = this.getChildrenByType(store, parentId, type); - for (String childNodeId : children.keySet()) { - HashMap childProps = children.get(childNodeId); - String propValue = (String) childProps.get(property); - if (propValue != null && propValue.equals(value)) - return childProps; - } - return null; - } + String nodeType = nodeService.getType(nodeRef).toString(); - /** - * @param store - * @param parentId - * @param type - * @param props - * @return all nodes that got the same properties like props - */ - public HashMap> getChilden(StoreRef store, String parentId, String type, HashMap props) { - HashMap> result = new HashMap>(); - HashMap> children = this.getChildrenByType(store, parentId, type); - for (String childNodeId : children.keySet()) { - HashMap childProps = children.get(childNodeId); - boolean allPropsMatched = true; - for (Object key : props.keySet()) { - Object searchedPropVal = props.get(key); - Object foundPropVal = childProps.get(key); - if (searchedPropVal != null) { - if (!searchedPropVal.equals(foundPropVal)) { - allPropsMatched = false; - } - } else if (foundPropVal != null) { - allPropsMatched = false; - } - } - if (allPropsMatched) { - result.put(childNodeId, childProps); - } - } - return result; - } + for (QName qname : childPropMap.keySet()) { - /** - * @param store - * @param parentId - * @param type - * @param props - * @return - */ - public HashMap getChildRecursive(StoreRef store, String parentId, String type, HashMap props) throws Throwable { - - NodeRef parentNodeRef = new NodeRef(store, parentId); - List childAssocList = nodeService.getChildAssocs(parentNodeRef); - for (ChildAssociationRef child : childAssocList) { - boolean propertiesMatched = true; - String childType = nodeService.getType(child.getChildRef()).toString(); - if (type != null) { - if (type.equals(childType)) { - - // test with the cached getPops method - // HashMap childProps = - // getPropertiesWithoutChildren(child.getChildRef()); - HashMap childProps = getProperties(child.getChildRef()); - - if (childProps.size() == 0) - propertiesMatched = false; - - for (Object key : props.keySet()) { - if (!childProps.containsKey(key)) { - propertiesMatched = false; - break; - } - Object childPropVal = childProps.get(key); - Object searchPropVal = props.get(key); - if (!searchPropVal.equals(childPropVal)) { - propertiesMatched = false; - break; - } - } - if (propertiesMatched) { - return childProps; - } - } - } + Serializable object = childPropMap.get(qname); - if (childType.equals(CCConstants.CCM_TYPE_MAP) || childType.equals(CCConstants.CM_TYPE_FOLDER)) { - HashMap recursiveResult = getChildRecursive(store, child.getChildRef().getId(), type, props); - if (recursiveResult != null) - return recursiveResult; - } + String metadataSetId = (String) childPropMap.get(QName.createQName(CCConstants.CM_PROP_METADATASET_EDU_METADATASET)); - } - return null; - } + String value = formatData(nodeType, qname.toString(), object, metadataSetId); + resultProps.put(qname.toString(), value); - public HashMap getChildRecursive(String parentId, String type, HashMap props) throws Throwable { - return this.getChildRecursive(storeRef, parentId, type, props); - } + // VCard + String type = nodeService.getType(nodeRef).toString(); + Map vcard = VCardConverter.getVCardMap(type, qname.toString(), value); + if (vcard != null && vcard.size() > 0) resultProps.putAll(vcard); - /** - * uses the getPropertiesCached so no user information is in the result - * - * @param store - * @param parentId - * @param type - * @param result - * @param cached - * @return - * @throws Throwable - */ - public HashMap> getChildrenRecursive(StoreRef store, String parentId, String type, - HashMap> result, boolean cached) throws Throwable { - - if (result == null) - result = new HashMap>(); - NodeRef parentNodeRef = new NodeRef(store, parentId); - List childAssocList = nodeService.getChildAssocs(parentNodeRef); - for (ChildAssociationRef child : childAssocList) { - - /** - * Alfresco 4.0.e archiving on: - check if it's not the archive - * store (when a object was deleted and it was linked somewhere the - * link still exists and points to archive store) - */ - if (child.getChildRef().getStoreRef().equals(StoreRef.STORE_REF_ARCHIVE_SPACESSTORE)) - continue; - - String childType = nodeService.getType(child.getChildRef()).toString(); - if (type != null) { - if (type.equals(childType)) { - HashMap childProps = null; - if (cached) { - // don't return user specific info in props like URLs - // with ticket and so - childProps = getPropertiesCached(child.getChildRef(), true, true, false); - } else { - childProps = getPropertiesCached(child.getChildRef(), false, true, false); - } - result.put(child.getChildRef().getId(), childProps); - } - } + } - if (childType.equals(CCConstants.CCM_TYPE_MAP) || childType.equals(CCConstants.CM_TYPE_FOLDER)) { + resultProps.put(CCConstants.REPOSITORY_ID, repId); + resultProps.put(CCConstants.REPOSITORY_CAPTION, appInfo.getAppCaption()); - HashMap folderprops = getProperties(child.getChildRef()); - String folderName = (String) folderprops.get(CCConstants.CM_NAME); - String folderTitle = (String) folderprops.get(CCConstants.CM_PROP_C_TITLE); - String lomTitle = (String) folderprops.get(CCConstants.LOM_PROP_GENERAL_TITLE); - logger.info("getChildren of Folder:" + folderName + " folderTitle:" + folderTitle + " lomTitle:" + lomTitle); - getChildrenRecursive(store, child.getChildRef().getId(), type, result, cached); - } - } - - if (result.size() > 0) - return result; - else - return null; - } + buildUpProperties(resultProps); - public HashMap> getChildrenRecursive(String parentId, String type) throws Throwable { - return getChildrenRecursive(storeRef, parentId, type, null, true); - } + return resultProps; + } - /** - * @param parentId - * @param type - * @param props - * @return all nodes that got the same properties like props - */ - public HashMap> getChilden(String parentId, String type, HashMap props) { - return getChilden(storeRef, parentId, type, props); - } + public Map getChild(String parentId, String type, String property, String value) { + return this.getChild(storeRef, parentId, type, property, value); + } - public String createNode(String parentID, String nodeTypeString, HashMap _props) { - return this.createNode(storeRef, parentID, nodeTypeString, _props); - } + /** + * this method returns the first child that matches the prop value pair it + * + * @param store + * @param parentId + * @param type + * @param property + * @param value + * @return + */ + public Map getChild(StoreRef store, String parentId, String type, String property, String value) { + Map> children = this.getChildrenByType(store, parentId, type); + for (String childNodeId : children.keySet()) { + Map childProps = children.get(childNodeId); + String propValue = (String) childProps.get(property); + if (propValue != null && propValue.equals(value)) + return childProps; + } + return null; + } - /** - * @param store - * @param parentID - * @param nodeType - * @param properties - * @return - */ - public String createNode(StoreRef store, String parentID, String nodeType, HashMap properties) { + /** + * @param store + * @param parentId + * @param type + * @param props + * @return all nodes that got the same properties like props + */ + public Map> getChilden(StoreRef store, String parentId, String type, Map props) { + Map> result = new HashMap<>(); + Map> children = this.getChildrenByType(store, parentId, type); + for (String childNodeId : children.keySet()) { + Map childProps = children.get(childNodeId); + boolean allPropsMatched = true; + for (Object key : props.keySet()) { + Object searchedPropVal = props.get(key); + Object foundPropVal = childProps.get(key); + if (searchedPropVal != null) { + if (!searchedPropVal.equals(foundPropVal)) { + allPropsMatched = false; + } + } else if (foundPropVal != null) { + allPropsMatched = false; + } + } + if (allPropsMatched) { + result.put(childNodeId, childProps); + } + } + return result; + } - return this.createNode(store, parentID, nodeType, CCConstants.CM_ASSOC_FOLDER_CONTAINS, properties); - } + /** + * @param store + * @param parentId + * @param type + * @param props + * @return + */ + public Map getChildRecursive(StoreRef store, String parentId, String type, Map props) throws Throwable { + + NodeRef parentNodeRef = new NodeRef(store, parentId); + List childAssocList = nodeService.getChildAssocs(parentNodeRef); + for (ChildAssociationRef child : childAssocList) { + boolean propertiesMatched = true; + String childType = nodeService.getType(child.getChildRef()).toString(); + if (type != null) { + if (type.equals(childType)) { + + // test with the cached getPops method + // Map childProps = + // getPropertiesWithoutChildren(child.getChildRef()); + Map childProps = getProperties(child.getChildRef()); + + if (childProps.size() == 0) + propertiesMatched = false; + + for (Object key : props.keySet()) { + if (!childProps.containsKey(key)) { + propertiesMatched = false; + break; + } + Object childPropVal = childProps.get(key); + Object searchPropVal = props.get(key); + if (!searchPropVal.equals(childPropVal)) { + propertiesMatched = false; + break; + } + } + if (propertiesMatched) { + return childProps; + } + } + } - @Override - public String createNode(String parentID, String nodeTypeString, String childAssociation, HashMap _props) { - return this.createNode(storeRef, parentID, nodeTypeString, childAssociation, _props); - } + if (childType.equals(CCConstants.CCM_TYPE_MAP) || childType.equals(CCConstants.CM_TYPE_FOLDER)) { + Map recursiveResult = getChildRecursive(store, child.getChildRef().getId(), type, props); + if (recursiveResult != null) + return recursiveResult; + } - public String createNode(StoreRef store, String parentID, String nodeTypeString, String childAssociation, HashMap _props) { + } + return null; + } - String name = (String)_props.get(CCConstants.CM_NAME); - _props.put(CCConstants.CM_NAME,CharMatcher.javaIsoControl().removeFrom(name)); - Map properties = transformPropMap(_props); + public Map getChildRecursive(String parentId, String type, Map props) throws Throwable { + return this.getChildRecursive(storeRef, parentId, type, props); + } - NodeRef parentNodeRef = new NodeRef(store, parentID); - QName nodeType = QName.createQName(nodeTypeString); + /** + * uses the getPropertiesCached so no user information is in the result + * + * @param store + * @param parentId + * @param type + * @param result + * @param cached + * @return + * @throws Throwable + */ + public Map> getChildrenRecursive(StoreRef store, String parentId, String type, + Map> result, boolean cached) throws Throwable { + + if (result == null) + result = new HashMap<>(); + NodeRef parentNodeRef = new NodeRef(store, parentId); + List childAssocList = nodeService.getChildAssocs(parentNodeRef); + for (ChildAssociationRef child : childAssocList) { + + /** + * Alfresco 4.0.e archiving on: - check if it's not the archive + * store (when a object was deleted and it was linked somewhere the + * link still exists and points to archive store) + */ + if (child.getChildRef().getStoreRef().equals(StoreRef.STORE_REF_ARCHIVE_SPACESSTORE)) + continue; + + String childType = nodeService.getType(child.getChildRef()).toString(); + if (type != null) { + if (type.equals(childType)) { + Map childProps; + if (cached) { + // don't return user specific info in props like URLs + // with ticket and so + childProps = getPropertiesCached(child.getChildRef(), true, true, false); + } else { + childProps = getPropertiesCached(child.getChildRef(), false, true, false); + } + result.put(child.getChildRef().getId(), childProps); + } + } - String assocName = (String) _props.get(CCConstants.CM_NAME); - if (assocName == null) { - assocName = "defaultAssociationName"; - } else { + if (childType.equals(CCConstants.CCM_TYPE_MAP) || childType.equals(CCConstants.CM_TYPE_FOLDER)) { - // assco name must have be smaller than a maxlength - // https://issues.alfresco.com/jira/browse/MNT-2417 - assocName = QName.createValidLocalName(assocName); - } - assocName = "{" + CCConstants.NAMESPACE_CCM + "}" + assocName; + Map folderprops = getProperties(child.getChildRef()); + String folderName = (String) folderprops.get(CCConstants.CM_NAME); + String folderTitle = (String) folderprops.get(CCConstants.CM_PROP_C_TITLE); + String lomTitle = (String) folderprops.get(CCConstants.LOM_PROP_GENERAL_TITLE); + log.info("getChildren of Folder:" + folderName + " folderTitle:" + folderTitle + " lomTitle:" + lomTitle); + getChildrenRecursive(store, child.getChildRef().getId(), type, result, cached); + } + } - ChildAssociationRef childRef = nodeService.createNode(parentNodeRef, QName.createQName(childAssociation), QName.createQName(assocName), nodeType, - properties); - return childRef.getChildRef().getId(); - } + if (result.size() > 0) + return result; + else + return null; + } - public void addAspect(String nodeId, String aspect) { - nodeService.addAspect(new NodeRef(storeRef, nodeId), QName.createQName(aspect), null); - } + public Map> getChildrenRecursive(String parentId, String type) throws Throwable { + return getChildrenRecursive(storeRef, parentId, type, null, true); + } - public void updateNode(String nodeId, HashMap _props) { - this.updateNode(storeRef, nodeId, _props); - } + /** + * @param parentId + * @param type + * @param props + * @return all nodes that got the same properties like props + */ + public Map> getChilden(String parentId, String type, Map props) { + return getChilden(storeRef, parentId, type, props); + } - public void updateNode(StoreRef store, String nodeId, HashMap _props) { + public String createNode(String parentID, String nodeTypeString, Map _props) { + return this.createNode(storeRef, parentID, nodeTypeString, _props); + } - try { - String name = (String)_props.get(CCConstants.CM_NAME); - _props.put(CCConstants.CM_NAME,CharMatcher.javaIsoControl().removeFrom(name)); - Map props = transformPropMap(_props); - NodeRef nodeRef = new NodeRef(store, nodeId); + /** + * @param store + * @param parentID + * @param nodeType + * @param properties + * @return + */ + public String createNode(StoreRef store, String parentID, String nodeType, Map properties) { - // don't do this cause it's slow: - /* - * for (Map.Entry entry : props.entrySet()) { - * nodeService.setProperty(nodeRef, entry.getKey(), - * entry.getValue()); } - */ - - // prevent overwriting of properties that don't come with param _props - Set changedProps = props.keySet(); - Map currentProps = nodeService.getProperties(nodeRef); - for (Map.Entry entry : currentProps.entrySet()) { - if (!changedProps.contains(entry.getKey())) { - props.put(entry.getKey(), entry.getValue()); - } - } + return this.createNode(store, parentID, nodeType, CCConstants.CM_ASSOC_FOLDER_CONTAINS, properties); + } - nodeService.setProperties(nodeRef, props); + @Override + public String createNode(String parentID, String nodeTypeString, String childAssociation, Map _props) { + return this.createNode(storeRef, parentID, nodeTypeString, childAssociation, _props); + } - } catch (Exception e) { - // this occurs sometimes in workspace - // it seems it is an alfresco bug: - // https://issues.alfresco.com/jira/browse/ETHREEOH-2461 - logger.error("Thats maybe an alfreco bug: https://issues.alfresco.com/jira/browse/ETHREEOH-2461", e); - } + public String createNode(StoreRef store, String parentID, String nodeTypeString, String childAssociation, Map _props) { - } + String name = (String) _props.get(CCConstants.CM_NAME); + _props.put(CCConstants.CM_NAME, CharMatcher.javaIsoControl().removeFrom(name)); + Map properties = transformPropMap(_props); - public void createAssociation(String fromID, String toID, String association) { - this.createAssociation(storeRef, fromID, toID, association); - } + NodeRef parentNodeRef = new NodeRef(store, parentID); + QName nodeType = QName.createQName(nodeTypeString); - public void createAssociation(StoreRef store, String fromID, String toID, String association) { - nodeService.createAssociation(new NodeRef(store, fromID), new NodeRef(store, toID), QName.createQName(association)); - } + String assocName = (String) _props.get(CCConstants.CM_NAME); + if (assocName == null) { + assocName = "defaultAssociationName"; + } else { - public void createChildAssociation(String from, String to, String assocType, String assocName) { - nodeService.addChild(new NodeRef(storeRef, from), new NodeRef(storeRef, to), QName.createQName(assocType), QName.createQName(assocName)); - } + // assco name must have be smaller than a maxlength + // https://issues.alfresco.com/jira/browse/MNT-2417 + assocName = QName.createValidLocalName(assocName); + } + assocName = "{" + CCConstants.NAMESPACE_CCM + "}" + assocName; - public void writeContent(String nodeID, byte[] content, String mimetype, String encoding, String property) throws Exception { - this.writeContent(storeRef, nodeID, content, mimetype, encoding, property); - } + ChildAssociationRef childRef = nodeService.createNode(parentNodeRef, QName.createQName(childAssociation), QName.createQName(assocName), nodeType, + properties); + return childRef.getChildRef().getId(); + } - /** - * thats the bad version cause there are OutOfMemory Problems when uploading - * large files - * - * so its better to use the method with InputStream or file as content - * - * @param store - * @param nodeID - * @param content - * @param mimetype - * @param _encoding - * @param property - * @throws Exception - */ - public void writeContent(final StoreRef store, final String nodeID, final byte[] content, final String mimetype, String _encoding, final String property) - throws Exception { - ByteArrayInputStream is = new ByteArrayInputStream(content); - this.writeContent(store, nodeID, is, mimetype, _encoding, property); - } + public void addAspect(String nodeId, String aspect) { + nodeService.addAspect(new NodeRef(storeRef, nodeId), QName.createQName(aspect), null); + } - /** - * @param store - * @param nodeID - * @param content - * @param mimetype - * @param _encoding - * @param property - * @throws Exception - */ - public void writeContent(final StoreRef store, final String nodeID, final File content, final String mimetype, String _encoding, final String property) - throws Exception { - FileInputStream fis = new FileInputStream(content); - this.writeContent(store, nodeID, fis, mimetype, _encoding, property); - } - - /** - * Runs a transaction - * @param callback the callback to run - */ - public Object doInTransaction(RetryingTransactionCallback callback){ - TransactionService transactionService = serviceRegistry.getTransactionService(); - return transactionService.getRetryingTransactionHelper().doInTransaction(callback, false); - } + public void updateNode(String nodeId, Map _props) { + this.updateNode(storeRef, nodeId, _props); + } - /** - * @param store - * @param nodeID - * @param content - * @param mimetype - * @param _encoding - * @param property - * @throws Exception - */ - public void writeContent(final StoreRef store, final String nodeID, final InputStream content, final String mimetype, String _encoding, - final String property) throws Exception { - - final String encoding = (_encoding == null) ? "UTF-8" : _encoding; - logger.debug("called nodeID:" + nodeID + " store:" + store + " mimetype:" + mimetype + " property:" + property); - - RetryingTransactionCallback callback = new RetryingTransactionCallback() { - @Override - public Object execute() throws Throwable { - - NodeRef nodeRef = new NodeRef(store, nodeID); - final ContentWriter contentWriter = contentService.getWriter(nodeRef, QName.createQName(property), true); - contentWriter.addListener(new ContentStreamListener() { - @Override - public void contentStreamClosed() throws ContentIOException { - logger.debug("Content Stream was closed"); - logger.debug(" size:" + contentWriter.getContentData().getSize()+ - ", URL:" + contentWriter.getContentData().getContentUrl()+ - ", MimeType:" + contentWriter.getContentData().getMimetype()+"" + - ", ContentData ToString:" + contentWriter.getContentData().toString()); - } - }); - - String finalMimeType = mimetype; - if(finalMimeType == null || finalMimeType.trim().equals("")) { - finalMimeType = MCAlfrescoAPIClient.this.guessMimetype(MCAlfrescoAPIClient.this.getProperty(storeRef, nodeID, CCConstants.CM_NAME)); - } - - contentWriter.setMimetype(finalMimeType); - contentWriter.setEncoding(encoding); + public void updateNode(StoreRef store, String nodeId, Map _props) { + + try { + String name = (String) _props.get(CCConstants.CM_NAME); + _props.put(CCConstants.CM_NAME, CharMatcher.javaIsoControl().removeFrom(name)); + Map props = transformPropMap(_props); + NodeRef nodeRef = new NodeRef(store, nodeId); + + // don't do this cause it's slow: + /* + * for (Map.Entry entry : props.entrySet()) { + * nodeService.setProperty(nodeRef, entry.getKey(), + * entry.getValue()); } + */ + + // prevent overwriting of properties that don't come with param _props + Set changedProps = props.keySet(); + Map currentProps = nodeService.getProperties(nodeRef); + for (Map.Entry entry : currentProps.entrySet()) { + if (!changedProps.contains(entry.getKey())) { + props.put(entry.getKey(), entry.getValue()); + } + } - InputStream is = content; - contentWriter.putContent(is); + nodeService.setProperties(nodeRef, props); - return null; - } - }; - TransactionService transactionService = serviceRegistry.getTransactionService(); - transactionService.getRetryingTransactionHelper().doInTransaction(callback, false); - } + } catch (Exception e) { + // this occurs sometimes in workspace + // it seems it is an alfresco bug: + // https://issues.alfresco.com/jira/browse/ETHREEOH-2461 + log.error("Thats maybe an alfreco bug: https://issues.alfresco.com/jira/browse/ETHREEOH-2461", e); + } - public void setUserDefinedPreview(String nodeId, byte[] content, String fileName) { - - String tmpDir = System.getProperty("java.io.tmpdir"); - String filePath = tmpDir + File.pathSeparator + "edu-sharing" + File.pathSeparator + "udpreview" + File.pathSeparator + System.currentTimeMillis() - + fileName; - try { - FileOutputStream fos = new FileOutputStream(filePath); - fos.write(content); - fos.close(); + } - this.setUserDefinedPreview(nodeId, new File(filePath), fileName); + public void createAssociation(String fromID, String toID, String association) { + this.createAssociation(storeRef, fromID, toID, association); + } - new File(filePath).delete(); + public void createAssociation(StoreRef store, String fromID, String toID, String association) { + nodeService.createAssociation(new NodeRef(store, fromID), new NodeRef(store, toID), QName.createQName(association)); + } - } catch (IOException e) { - logger.error(e.getMessage(), e); - } - } + public void createChildAssociation(String from, String to, String assocType, String assocName) { + nodeService.addChild(new NodeRef(storeRef, from), new NodeRef(storeRef, to), QName.createQName(assocType), QName.createQName(assocName)); + } - /** - * when userdefined preview is removed - * NodeCustomizationPolicies.onContentUpdate would be excecuted, cause it's - * not looking on which of the contentproperties is updated so we need to - * disable the policy behavior here. - * - * to disable/enable the policy behavior there must be an transaction active - * - * @param fileName - * @param file - * @param nodeId - */ - public void setUserDefinedPreview(String nodeId, File file, String fileName) { - - BehaviourFilter behaviourFilter = (BehaviourFilter) applicationContext.getBean("policyBehaviourFilter"); - TransactionService ts = serviceRegistry.getTransactionService(); - UserTransaction ut = ts.getNonPropagatingUserTransaction(); - try { - ut.begin(); - - NodeRef ioNodeRef = new NodeRef(MCAlfrescoAPIClient.storeRef, nodeId); - try { - - behaviourFilter.disableBehaviour(ioNodeRef); - ContentReader reader = new FileContentReader(file); - - if (fileName != null) { - // BUG when IE: filename is the whole filepath - int slash = Math.max(fileName.lastIndexOf('/'), fileName.lastIndexOf('\\')); - // check for Unix AND Win separator - if (slash > -1) fileName = fileName.substring(slash + 1); - } + public void writeContent(String nodeID, byte[] content, String mimetype, String encoding, String property) throws Exception { + this.writeContent(storeRef, nodeID, content, mimetype, encoding, property); + } - if (fileName != null) { - String mimeType = serviceRegistry.getMimetypeService().guessMimetype(fileName); - if (mimeType == null) { - mimeType = MimeTypes.guessMimetype(fileName); - } - reader.setMimetype(mimeType); - } + /** + * thats the bad version cause there are OutOfMemory Problems when uploading + * large files + * + * so its better to use the method with InputStream or file as content + * + * @param store + * @param nodeID + * @param content + * @param mimetype + * @param _encoding + * @param property + * @throws Exception + */ + public void writeContent(final StoreRef store, final String nodeID, final byte[] content, final String mimetype, String _encoding, final String property) + throws Exception { + ByteArrayInputStream is = new ByteArrayInputStream(content); + this.writeContent(store, nodeID, is, mimetype, _encoding, property); + } - ContentWriter writer = contentService.getWriter(ioNodeRef, QName.createQName(CCConstants.CCM_PROP_IO_USERDEFINED_PREVIEW), true); - writer.setMimetype("image/png"); + /** + * @param store + * @param nodeID + * @param content + * @param mimetype + * @param _encoding + * @param property + * @throws Exception + */ + public void writeContent(final StoreRef store, final String nodeID, final File content, final String mimetype, String _encoding, final String property) + throws Exception { + FileInputStream fis = new FileInputStream(content); + this.writeContent(store, nodeID, fis, mimetype, _encoding, property); + } - ThumbnailRegistry thumbnailRegistry = (ThumbnailRegistry) applicationContext.getBean("thumbnailRegistry"); - ThumbnailDefinition thumbDef = thumbnailRegistry.getThumbnailDefinition("imgpreview"); + /** + * Runs a transaction + * @param callback the callback to run + */ + public Object doInTransaction(RetryingTransactionCallback callback) { + TransactionService transactionService = serviceRegistry.getTransactionService(); + return transactionService.getRetryingTransactionHelper().doInTransaction(callback, false); + } + /** + * @param store + * @param nodeID + * @param content + * @param mimetype + * @param _encoding + * @param property + * @throws Exception + */ + public void writeContent(final StoreRef store, final String nodeID, final InputStream content, final String mimetype, String _encoding, + final String property) throws Exception { + + final String encoding = (_encoding == null) ? "UTF-8" : _encoding; + log.debug("called nodeID:" + nodeID + " store:" + store + " mimetype:" + mimetype + " property:" + property); + + RetryingTransactionCallback callback = new RetryingTransactionCallback() { + @Override + public Object execute() throws Throwable { + + NodeRef nodeRef = new NodeRef(store, nodeID); + final ContentWriter contentWriter = contentService.getWriter(nodeRef, QName.createQName(property), true); + contentWriter.addListener(new ContentStreamListener() { + @Override + public void contentStreamClosed() throws ContentIOException { + log.debug("Content Stream was closed"); + log.debug(" size:" + contentWriter.getContentData().getSize() + + ", URL:" + contentWriter.getContentData().getContentUrl() + + ", MimeType:" + contentWriter.getContentData().getMimetype() + "" + + ", ContentData ToString:" + contentWriter.getContentData().toString()); + } + }); + String finalMimeType = mimetype; + if (finalMimeType == null || finalMimeType.trim().equals("")) { + finalMimeType = MCAlfrescoAPIClient.this.guessMimetype(MCAlfrescoAPIClient.this.getProperty(storeRef, nodeID, CCConstants.CM_NAME)); + } - /** - * @TODO fix alf 7.0 - * if (contentService.isTransformable(reader, writer, thumbDef.getTransformationOptions())) { - contentService.transform(reader, writer, thumbDef.getTransformationOptions()); - } else { - logger.error(reader.getMimetype() + " is not transformable to image/png"); - }**/ - - } finally { - behaviourFilter.enableBehaviour(ioNodeRef); - } + contentWriter.setMimetype(finalMimeType); + contentWriter.setEncoding(encoding); - ut.commit(); - } catch (Exception e) { - logger.error(e.getMessage(), e); - } - return; - } + InputStream is = content; + contentWriter.putContent(is); - /** - * when user defined preview is removed - * NodeCustomizationPolicies.onContentUpdate would be excecuted, cause it's - * not looking on which of the contentproperties is updated so we need to - * disable the policy behavior here. - * - * to disable/enable the policy behavior there must be an transaction active - * - * @param nodeId - */ - public void removeUserDefinedPreview(String nodeId) { - - BehaviourFilter behaviourFilter = (BehaviourFilter) applicationContext.getBean("policyBehaviourFilter"); - TransactionService ts = serviceRegistry.getTransactionService(); - UserTransaction ut = ts.getNonPropagatingUserTransaction(); - try { - ut.begin(); - - NodeRef ioNodeRef = new NodeRef(MCAlfrescoAPIClient.storeRef, nodeId); - try { - behaviourFilter.disableBehaviour(ioNodeRef); - nodeService.setProperty(new NodeRef(storeRef, nodeId), QName.createQName(CCConstants.CCM_PROP_IO_USERDEFINED_PREVIEW), null); - } finally { - behaviourFilter.enableBehaviour(ioNodeRef); - } + return null; + } + }; + TransactionService transactionService = serviceRegistry.getTransactionService(); + transactionService.getRetryingTransactionHelper().doInTransaction(callback, false); + } - ut.commit(); - } catch (Exception e) { - logger.error(e.getMessage(), e); - } - } - - public void removeGlobalAspectFromGroup(String groupNodeId) throws Exception { - - UserTransaction userTransaction = serviceRegistry.getTransactionService().getNonPropagatingUserTransaction(); - - userTransaction.begin(); - try{ - - NodeRef nodeRef = new NodeRef(storeRef,groupNodeId ); - nodeService.removeAspect(nodeRef,QName.createQName( CCConstants.CCM_ASPECT_SCOPE)); - String authorityName = (String) nodeService.getProperty(nodeRef, ContentModel.PROP_AUTHORITY_NAME); - Set userNames = authorityService.getContainedAuthorities(AuthorityType.USER,authorityName,false); - - //remove all shadow users from group - for(String username : userNames){ - NodeRef personNodeRef = personService.getPerson(username); - Map personProps = nodeService.getProperties(personNodeRef); - String repoId = (String)personProps.get(QName.createQName(CCConstants.PROP_USER_REPOSITORYID)); - if(repoId != null && !repoId.trim().equals("") && !appInfo.getAppId().equals(repoId)){ - authorityService.removeAuthority(authorityName, username); - } - } - - userTransaction.commit(); - - } catch (Throwable e) { - userTransaction.rollback(); - } + public void setUserDefinedPreview(String nodeId, byte[] content, String fileName) { - } - - public static Map transformQNameKeyToString(Map props) { - Map result = new HashMap(); - for (Map.Entry entry : props.entrySet()) { - result.put(entry.getKey().toString(), entry.getValue()); - } - return result; - } + String tmpDir = System.getProperty("java.io.tmpdir"); + String filePath = tmpDir + File.pathSeparator + "edu-sharing" + File.pathSeparator + "udpreview" + File.pathSeparator + System.currentTimeMillis() + + fileName; + try { + FileOutputStream fos = new FileOutputStream(filePath); + fos.write(content); + fos.close(); - /** - * transform to Alfresco HashMap - * - * @param map - * @return - */ - Map transformPropMap(HashMap map) { - Map result = new HashMap(); - for (Object key : map.keySet()) { - - try { - Object value = map.get(key); - if (value instanceof HashMap) { - value = getMLText((HashMap) value); - } else if (value instanceof List) { - List transformedList = new ArrayList(); - for (Object valCol : (ArrayList) value) { - if (valCol instanceof HashMap) { - transformedList.add(getMLText((HashMap) valCol)); - } else { - transformedList.add(valCol); - } - } - value = transformedList; - } - result.put(QName.createQName((String) key), (Serializable) value); - } catch (ClassCastException e) { - logger.error("this prop has a wrong value:" + key + " val:" + map.get(key)); - logger.error(e.getMessage(), e); - } - } - return result; - } + this.setUserDefinedPreview(nodeId, new File(filePath), fileName); - private MLText getMLText(HashMap i18nMap) { - MLText mlText = new MLText(); - for (Object obj : i18nMap.keySet()) { - String locale = (String) obj; - mlText.addValue(new Locale(locale), (String) i18nMap.get(obj)); - } - return mlText; - } + new File(filePath).delete(); - public Map transformPropMapToStringKeys(HashMap map) { - Map result = new HashMap(); - for (Object key : map.keySet()) { - result.put((String) key, (Serializable) map.get(key)); - } - return result; - } + } catch (IOException e) { + log.error(e.getMessage(), e); + } + } - @Override - public String getHomeFolderID(String username) throws Exception { - - if (NodeServiceInterceptor.getEduSharingScope() == null || - NodeServiceInterceptor.getEduSharingScope().trim().equals("")) { - NodeRef person = serviceRegistry.getPersonService().getPerson(username,false); - if (person != null) { - NodeRef homfolder = (NodeRef) nodeService.getProperty(person, QName.createQName(CCConstants.CM_PROP_PERSON_HOME_FOLDER)); - return (homfolder != null) ? homfolder.getId() : null; - } else { - return null; - } - - } else { - - NodeRef userHome = ScopeUserHomeServiceFactory.getScopeUserHomeService().getUserHome( - username, - NodeServiceInterceptor.getEduSharingScope(), - true); - String userHomeNodeId = (userHome != null) ? userHome.getId() : null; - return userHomeNodeId; - } - } + /** + * when userdefined preview is removed + * NodeCustomizationPolicies.onContentUpdate would be excecuted, cause it's + * not looking on which of the contentproperties is updated so we need to + * disable the policy behavior here. + * + * to disable/enable the policy behavior there must be an transaction active + * + * @param fileName + * @param file + * @param nodeId + */ + public void setUserDefinedPreview(String nodeId, File file, String fileName) { + + BehaviourFilter behaviourFilter = (BehaviourFilter) applicationContext.getBean("policyBehaviourFilter"); + TransactionService ts = serviceRegistry.getTransactionService(); + UserTransaction ut = ts.getNonPropagatingUserTransaction(); + try { + ut.begin(); + + NodeRef ioNodeRef = new NodeRef(MCAlfrescoAPIClient.storeRef, nodeId); + try { + + behaviourFilter.disableBehaviour(ioNodeRef); + ContentReader reader = new FileContentReader(file); + + if (fileName != null) { + // BUG when IE: filename is the whole filepath + int slash = Math.max(fileName.lastIndexOf('/'), fileName.lastIndexOf('\\')); + // check for Unix AND Win separator + if (slash > -1) fileName = fileName.substring(slash + 1); + } - public synchronized void createVersion(String nodeId) throws Exception { + if (fileName != null) { + String mimeType = serviceRegistry.getMimetypeService().guessMimetype(fileName); + if (mimeType == null) { + mimeType = MimeTypes.guessMimetype(fileName); + } + reader.setMimetype(mimeType); + } - VersionService versionService = serviceRegistry.getVersionService(); - NodeRef nodeRef = new NodeRef(storeRef, nodeId); - Map transFormedProps = transformQNameKeyToString(nodeService.getProperties(nodeRef)); - if (versionService.getVersionHistory(nodeRef) == null) { + ContentWriter writer = contentService.getWriter(ioNodeRef, QName.createQName(CCConstants.CCM_PROP_IO_USERDEFINED_PREVIEW), true); + writer.setMimetype("image/png"); - // see https://issues.alfresco.com/jira/browse/ALF-12815 - // alfresco-4.0.d fix version should start with 1.0 not with 0.1 - transFormedProps.put(VersionModel.PROP_VERSION_TYPE, VersionType.MAJOR); - } - versionService.createVersion(nodeRef, transFormedProps); + ThumbnailRegistry thumbnailRegistry = (ThumbnailRegistry) applicationContext.getBean("thumbnailRegistry"); + ThumbnailDefinition thumbDef = thumbnailRegistry.getThumbnailDefinition("imgpreview"); - } + /** + * @TODO fix alf 7.0 + * if (contentService.isTransformable(reader, writer, thumbDef.getTransformationOptions())) { + contentService.transform(reader, writer, thumbDef.getTransformationOptions()); + } else { + logger.error(reader.getMimetype() + " is not transformable to image/png"); + }**/ - public String getPath(String nodeID) { - return nodeService.getPath(new NodeRef(storeRef, nodeID)).toPrefixString(namespaceService); - } + } finally { + behaviourFilter.enableBehaviour(ioNodeRef); + } - public List getAssociationNodeIds(String nodeID, String association) { - NodeRef nodeRef = new NodeRef(storeRef, nodeID); - List result = new ArrayList(); - for(NodeRef assocNodeRef : getAssociationNodeIds(nodeRef, association)){ - result.add(assocNodeRef.getId()); - } - return result; - } - - /** - * returns target Assocs NodeIds - * - * @param nodeRef - * @param association - * @return - */ - public List getAssociationNodeIds(NodeRef nodeRef, String association) { - - List result = new ArrayList(); - - - QName assocQName = QName.createQName(association); - - List targetAssoc = nodeService.getTargetAssocs(nodeRef, assocQName); - for (AssociationRef assocRef : targetAssoc) - result.add(assocRef.getTargetRef()); - return result; - } - - public HashMap getAssocNode(String nodeid, String association) throws Throwable { - - HashMap result = new HashMap(); - for(Map.Entry entry : getAssocNode(new NodeRef(storeRef,nodeid), association).entrySet()){ - result.put(entry.getKey().getId(), entry.getValue()); - } - - return result; - } + ut.commit(); + } catch (Exception e) { + log.error(e.getMessage(), e); + } + return; + } - public HashMap getAssocNode(NodeRef nodeRef, String association) throws Throwable { - HashMap result = new HashMap(); - List nodeIds = this.getAssociationNodeIds(nodeRef, association); - for (NodeRef nodeId : nodeIds) { - result.put(nodeId, getProperties(nodeId)); - } - return result; - } + /** + * when user defined preview is removed + * NodeCustomizationPolicies.onContentUpdate would be excecuted, cause it's + * not looking on which of the contentproperties is updated so we need to + * disable the policy behavior here. + * + * to disable/enable the policy behavior there must be an transaction active + * + * @param nodeId + */ + public void removeUserDefinedPreview(String nodeId) { + + BehaviourFilter behaviourFilter = (BehaviourFilter) applicationContext.getBean("policyBehaviourFilter"); + TransactionService ts = serviceRegistry.getTransactionService(); + UserTransaction ut = ts.getNonPropagatingUserTransaction(); + try { + ut.begin(); + + NodeRef ioNodeRef = new NodeRef(MCAlfrescoAPIClient.storeRef, nodeId); + try { + behaviourFilter.disableBehaviour(ioNodeRef); + nodeService.setProperty(new NodeRef(storeRef, nodeId), QName.createQName(CCConstants.CCM_PROP_IO_USERDEFINED_PREVIEW), null); + } finally { + behaviourFilter.enableBehaviour(ioNodeRef); + } - public void removeAspect(String nodeId, String aspect) { - nodeService.removeAspect(new NodeRef(storeRef, nodeId), QName.createQName(aspect)); - } + ut.commit(); + } catch (Exception e) { + log.error(e.getMessage(), e); + } + } - public void removeAssociation(String fromID, String toID, String association) throws Exception { - nodeService.removeAssociation(new NodeRef(storeRef, fromID), new NodeRef(storeRef, toID), QName.createQName(association)); - } - - /** - * Throws NoSuchPersonException when user not exists - */ - public HashMap getUserInfo(String userName) throws Exception { - - return serviceRegistry.getTransactionService().getRetryingTransactionHelper().doInTransaction( - - new RetryingTransactionCallback>() - { - public HashMap execute() throws Throwable - { - NodeRef personRef = serviceRegistry.getPersonService().getPerson(userName, false); - if (personRef == null) { - return null; - } - - Map tmpProps = nodeService.getProperties(personRef); - HashMap result = new HashMap(); - for (Map.Entry entry : tmpProps.entrySet()) { - - Object value = entry.getValue(); - - result.put( - entry.getKey().toString(), - (value instanceof NodeRef) - ? ((NodeRef) value).getId() - : (value != null) - ? value.toString() - : null); - - } - - return result; + public void removeGlobalAspectFromGroup(String groupNodeId) throws Exception { + UserTransaction userTransaction = serviceRegistry.getTransactionService().getNonPropagatingUserTransaction(); + + userTransaction.begin(); + try { + + NodeRef nodeRef = new NodeRef(storeRef, groupNodeId); + nodeService.removeAspect(nodeRef, QName.createQName(CCConstants.CCM_ASPECT_SCOPE)); + String authorityName = (String) nodeService.getProperty(nodeRef, ContentModel.PROP_AUTHORITY_NAME); + Set userNames = authorityService.getContainedAuthorities(AuthorityType.USER, authorityName, false); + + //remove all shadow users from group + for (String username : userNames) { + NodeRef personNodeRef = personService.getPerson(username); + Map personProps = nodeService.getProperties(personNodeRef); + String repoId = (String) personProps.get(QName.createQName(CCConstants.PROP_USER_REPOSITORYID)); + if (repoId != null && !repoId.trim().equals("") && !appInfo.getAppId().equals(repoId)) { + authorityService.removeAuthority(authorityName, username); + } + } + + userTransaction.commit(); + + } catch (Throwable e) { + userTransaction.rollback(); + } + + } + + public static Map transformQNameKeyToString(Map props) { + Map result = new HashMap<>(); + for (Map.Entry entry : props.entrySet()) { + result.put(entry.getKey().toString(), entry.getValue()); + } + return result; + } + + /** + * transform to Alfresco Map + * + * @param map + * @return + */ + Map transformPropMap(Map map) { + Map result = new HashMap<>(); + for (Object key : map.keySet()) { + + try { + Object value = map.get(key); + if (value instanceof HashMap) { + value = getMLText((Map) value); + } else if (value instanceof List) { + List transformedList = new ArrayList<>(); + for (Object valCol : (ArrayList) value) { + if (valCol instanceof HashMap) { + transformedList.add(getMLText((Map) valCol)); + } else { + transformedList.add(valCol); + } } - }, true); - } - - public String getGroupDisplayName(String groupName) throws Exception { - - AuthorityService authorityService = serviceRegistry.getAuthorityService(); - - return serviceRegistry.getTransactionService().getRetryingTransactionHelper().doInTransaction( - - new RetryingTransactionCallback() - { - public String execute() throws Throwable - { - try { - String key = (groupName.startsWith(PermissionService.GROUP_PREFIX) ? "" : PermissionService.GROUP_PREFIX) + groupName; - - return authorityService.authorityExists(key) - ? authorityService.getAuthorityDisplayName(key) - : null; - } catch(Throwable e) { - logger.error(e.getMessage(), e); - return null; - } + value = transformedList; + } + result.put(QName.createQName((String) key), (Serializable) value); + } catch (ClassCastException e) { + log.error("this prop has a wrong value:" + key + " val:" + map.get(key)); + log.error(e.getMessage(), e); + } + } + return result; + } + + private MLText getMLText(Map i18nMap) { + MLText mlText = new MLText(); + for (String locale : i18nMap.keySet()) { + mlText.addValue(new Locale(locale), (String) i18nMap.get(locale)); + } + return mlText; + } + + public Map transformPropMapToStringKeys(Map map) { + Map result = new HashMap<>(); + for (Object key : map.keySet()) { + result.put((String) key, map.get(key)); + } + return result; + } + + @Override + public String getHomeFolderID(String username) throws Exception { + + if (NodeServiceInterceptor.getEduSharingScope() == null || + NodeServiceInterceptor.getEduSharingScope().trim().equals("")) { + NodeRef person = serviceRegistry.getPersonService().getPerson(username, false); + if (person != null) { + NodeRef homfolder = (NodeRef) nodeService.getProperty(person, QName.createQName(CCConstants.CM_PROP_PERSON_HOME_FOLDER)); + return (homfolder != null) ? homfolder.getId() : null; + } else { + return null; + } + + } else { + + NodeRef userHome = ScopeUserHomeServiceFactory.getScopeUserHomeService().getUserHome( + username, + NodeServiceInterceptor.getEduSharingScope(), + true); + String userHomeNodeId = (userHome != null) ? userHome.getId() : null; + return userHomeNodeId; + } + } + + public synchronized void createVersion(String nodeId) throws Exception { + + VersionService versionService = serviceRegistry.getVersionService(); + NodeRef nodeRef = new NodeRef(storeRef, nodeId); + Map transFormedProps = transformQNameKeyToString(nodeService.getProperties(nodeRef)); + if (versionService.getVersionHistory(nodeRef) == null) { + + // see https://issues.alfresco.com/jira/browse/ALF-12815 + // alfresco-4.0.d fix version should start with 1.0 not with 0.1 + transFormedProps.put(VersionModel.PROP_VERSION_TYPE, VersionType.MAJOR); + } + versionService.createVersion(nodeRef, transFormedProps); + + + } + + public String getPath(String nodeID) { + return nodeService.getPath(new NodeRef(storeRef, nodeID)).toPrefixString(namespaceService); + } + + public List getAssociationNodeIds(String nodeID, String association) { + NodeRef nodeRef = new NodeRef(storeRef, nodeID); + List result = new ArrayList<>(); + for (NodeRef assocNodeRef : getAssociationNodeIds(nodeRef, association)) { + result.add(assocNodeRef.getId()); + } + return result; + } + + /** + * returns target Assocs NodeIds + * + * @param nodeRef + * @param association + * @return + */ + public List getAssociationNodeIds(NodeRef nodeRef, String association) { + + List result = new ArrayList<>(); + + + QName assocQName = QName.createQName(association); + + List targetAssoc = nodeService.getTargetAssocs(nodeRef, assocQName); + for (AssociationRef assocRef : targetAssoc) + result.add(assocRef.getTargetRef()); + return result; + } + + public Map> getAssocNode(String nodeid, String association) throws Throwable { + + Map> result = new HashMap<>(); + for (Map.Entry> entry : getAssocNode(new NodeRef(storeRef, nodeid), association).entrySet()) { + result.put(entry.getKey().getId(), entry.getValue()); + } + + return result; + } + + public Map> getAssocNode(NodeRef nodeRef, String association) throws Throwable { + Map> result = new HashMap<>(); + List nodeIds = this.getAssociationNodeIds(nodeRef, association); + for (NodeRef nodeId : nodeIds) { + result.put(nodeId, getProperties(nodeId)); + } + return result; + } + + public void removeAspect(String nodeId, String aspect) { + nodeService.removeAspect(new NodeRef(storeRef, nodeId), QName.createQName(aspect)); + } + + public void removeAssociation(String fromID, String toID, String association) throws Exception { + nodeService.removeAssociation(new NodeRef(storeRef, fromID), new NodeRef(storeRef, toID), QName.createQName(association)); + } + + /** + * Throws NoSuchPersonException when user not exists + */ + public Map getUserInfo(String userName) throws Exception { + + return serviceRegistry.getTransactionService().getRetryingTransactionHelper().doInTransaction( + + () -> { + NodeRef personRef = serviceRegistry.getPersonService().getPerson(userName, false); + if (personRef == null) { + return null; } - }, true); - - } - public String getGroupNodeId(String groupName) throws Exception { - - AuthorityService authorityService = serviceRegistry.getAuthorityService(); + Map tmpProps = nodeService.getProperties(personRef); + Map result = new HashMap<>(); + for (Map.Entry entry : tmpProps.entrySet()) { + + Object value = entry.getValue(); + + result.put( + entry.getKey().toString(), + (value instanceof NodeRef) + ? ((NodeRef) value).getId() + : (value != null) + ? value.toString() + : null); - return serviceRegistry.getTransactionService().getRetryingTransactionHelper().doInTransaction( - - new RetryingTransactionCallback() - { - public String execute() throws Throwable - { - String key = groupName.startsWith(PermissionService.GROUP_PREFIX) ? groupName : PermissionService.GROUP_PREFIX + groupName; - - return authorityService.authorityExists(key) - ? authorityService.getAuthorityNodeRef(key).getId() - : null; } - }, true); - - } - public String getEduGroupFolder(String groupName) throws Exception { - - return serviceRegistry.getTransactionService().getRetryingTransactionHelper().doInTransaction( - - new RetryingTransactionCallback() - { - public String execute() throws Throwable - { - String key = groupName.startsWith(PermissionService.GROUP_PREFIX) ? groupName : PermissionService.GROUP_PREFIX + groupName; - - NodeRef nodeRef = serviceRegistry.getAuthorityService().getAuthorityNodeRef(key); - - if (nodeRef == null) { - return null; - } - - - NodeRef folderRef = (NodeRef) serviceRegistry.getNodeService().getProperty(nodeRef, QName.createQName(CCConstants.CCM_PROP_EDUGROUP_EDU_HOMEDIR)); - - return folderRef != null - ? folderRef.getId() - : null; + return result; + + }, true); + } + + public String getGroupDisplayName(String groupName) throws Exception { + + AuthorityService authorityService = serviceRegistry.getAuthorityService(); + + return serviceRegistry.getTransactionService().getRetryingTransactionHelper().doInTransaction( + + () -> { + try { + String key = (groupName.startsWith(PermissionService.GROUP_PREFIX) ? "" : PermissionService.GROUP_PREFIX) + groupName; + + return authorityService.authorityExists(key) + ? authorityService.getAuthorityDisplayName(key) + : null; + } catch (Throwable e) { + log.error(e.getMessage(), e); + return null; } - }, true); - - } - - public void createOrUpdateGroup(String groupName, String displayName) throws Exception { - createOrUpdateGroup(groupName, displayName,null,false); - } + }, true); - public String createOrUpdateGroup(String groupName, String displayName,String parentGroup,boolean preventDuplicate) throws Exception { - - if (parentGroup!=null) { - if(getGroupNodeId(parentGroup)==null){ - throw new IllegalArgumentException("parent group "+parentGroup+" does not exists"); - } - } - - return serviceRegistry.getTransactionService().getRetryingTransactionHelper().doInTransaction( - - new RetryingTransactionCallback() - { - public String execute() throws Throwable - { - return eduAuthorityService.createOrUpdateGroup(groupName, displayName, parentGroup, preventDuplicate); + } + + public String getGroupNodeId(String groupName) throws Exception { + + AuthorityService authorityService = serviceRegistry.getAuthorityService(); + + return serviceRegistry.getTransactionService().getRetryingTransactionHelper().doInTransaction( + + new RetryingTransactionCallback() { + public String execute() throws Throwable { + String key = groupName.startsWith(PermissionService.GROUP_PREFIX) ? groupName : PermissionService.GROUP_PREFIX + groupName; + + return authorityService.authorityExists(key) + ? authorityService.getAuthorityNodeRef(key).getId() + : null; } - }, false); + }, true); - } - - public String[] getUserNames() throws Exception { - - PersonService personService = serviceRegistry.getPersonService(); - - return serviceRegistry.getTransactionService().getRetryingTransactionHelper().doInTransaction( - - new RetryingTransactionCallback() - { - public String[] execute() throws Throwable - { - PagingResults peopleReq = - personService.getPeople( - null, - null, - null, - new PagingRequest(Integer.MAX_VALUE, null)); - - List userNames = new ArrayList(); - for (PersonInfo personInfo : peopleReq.getPage()) - { - userNames.add(personInfo.getUserName()); - } - - return userNames.toArray(new String[0]); + } + + public String getEduGroupFolder(String groupName) throws Exception { + + return serviceRegistry.getTransactionService().getRetryingTransactionHelper().doInTransaction( + + () -> { + String key = groupName.startsWith(PermissionService.GROUP_PREFIX) ? groupName : PermissionService.GROUP_PREFIX + groupName; + + NodeRef nodeRef = serviceRegistry.getAuthorityService().getAuthorityNodeRef(key); + + if (nodeRef == null) { + return null; } - }, true); - } - public String[] searchUserNames(String pattern) throws Exception { - - PersonService personService = serviceRegistry.getPersonService(); - - return serviceRegistry.getTransactionService().getRetryingTransactionHelper().doInTransaction( - - new RetryingTransactionCallback() { - public String[] execute() throws Throwable { - List filters = new ArrayList(); - filters.add(ContentModel.PROP_FIRSTNAME); - filters.add(ContentModel.PROP_LASTNAME); - filters.add(ContentModel.PROP_EMAIL); - - PagingResults peopleReq = - personService.getPeople( - pattern, - filters, - null, - new PagingRequest(Integer.MAX_VALUE, null)); - - List userNames = new ArrayList(); - for (PersonInfo personInfo : peopleReq.getPage()) { - userNames.add(personInfo.getUserName()); - } - - return userNames.toArray(new String[0]); + + NodeRef folderRef = (NodeRef) serviceRegistry.getNodeService().getProperty(nodeRef, QName.createQName(CCConstants.CCM_PROP_EDUGROUP_EDU_HOMEDIR)); + + return folderRef != null + ? folderRef.getId() + : null; + }, true); + + } + + public void createOrUpdateGroup(String groupName, String displayName) throws Exception { + createOrUpdateGroup(groupName, displayName, null, false); + } + + public String createOrUpdateGroup(String groupName, String displayName, String parentGroup, boolean preventDuplicate) throws Exception { + + if (parentGroup != null) { + if (getGroupNodeId(parentGroup) == null) { + throw new IllegalArgumentException("parent group " + parentGroup + " does not exists"); + } + } + + return serviceRegistry.getTransactionService().getRetryingTransactionHelper().doInTransaction( + + () -> eduAuthorityService.createOrUpdateGroup(groupName, displayName, parentGroup, preventDuplicate), false); + + } + + public String[] getUserNames() throws Exception { + + PersonService personService = serviceRegistry.getPersonService(); + + return serviceRegistry.getTransactionService().getRetryingTransactionHelper().doInTransaction( + + () -> { + PagingResults peopleReq = + personService.getPeople( + null, + null, + null, + new PagingRequest(Integer.MAX_VALUE, null)); + + List userNames = new ArrayList<>(); + for (PersonInfo personInfo : peopleReq.getPage()) { + userNames.add(personInfo.getUserName()); } - }, true); - - } - public String[] getGroupNames() { - - AuthorityService authorityService = serviceRegistry.getAuthorityService(); - - return serviceRegistry.getTransactionService().getRetryingTransactionHelper().doInTransaction( - - new RetryingTransactionCallback() - { - public String[] execute() throws Throwable - { - PagingResults groupReq = - authorityService.getAuthorities( - AuthorityType.GROUP, - AuthorityService.ZONE_APP_DEFAULT, - null, - false, - false, - new PagingRequest(Integer.MAX_VALUE, null)); - - List groupNames = new ArrayList(); - for (String groupName : groupReq.getPage()) { - if (groupName.startsWith(PermissionService.GROUP_PREFIX)) { - groupName = groupName.substring(PermissionService.GROUP_PREFIX.length()); - } - groupNames.add(groupName); - } - - return groupNames.toArray(new String[0]); + return userNames.toArray(new String[0]); + }, true); + } + + public String[] searchUserNames(String pattern) throws Exception { + + PersonService personService = serviceRegistry.getPersonService(); + + return serviceRegistry.getTransactionService().getRetryingTransactionHelper().doInTransaction( + + () -> { + List filters = new ArrayList<>(); + filters.add(ContentModel.PROP_FIRSTNAME); + filters.add(ContentModel.PROP_LASTNAME); + filters.add(ContentModel.PROP_EMAIL); + + PagingResults peopleReq = + personService.getPeople( + pattern, + filters, + null, + new PagingRequest(Integer.MAX_VALUE, null)); + + List userNames = new ArrayList<>(); + for (PersonInfo personInfo : peopleReq.getPage()) { + userNames.add(personInfo.getUserName()); } - }, true); - - } - public String[] searchGroupNames(String pattern) throws Exception { - - AuthorityService authorityService = serviceRegistry.getAuthorityService(); - - return serviceRegistry.getTransactionService().getRetryingTransactionHelper().doInTransaction( - - new RetryingTransactionCallback() - { - public String[] execute() throws Throwable - { - PagingResults groupReq = - authorityService.getAuthoritiesInfo( - AuthorityType.GROUP, - null, - pattern, - null, - true, - new PagingRequest(Integer.MAX_VALUE, null)); - - List groupNames = new ArrayList(); - for (AuthorityInfo groupInfo : groupReq.getPage()) { - groupNames.add(groupInfo.getAuthorityName()); + return userNames.toArray(new String[0]); + }, true); + + } + + public String[] getGroupNames() { + + AuthorityService authorityService = serviceRegistry.getAuthorityService(); + + return serviceRegistry.getTransactionService().getRetryingTransactionHelper().doInTransaction( + + () -> { + PagingResults groupReq = + authorityService.getAuthorities( + AuthorityType.GROUP, + AuthorityService.ZONE_APP_DEFAULT, + null, + false, + false, + new PagingRequest(Integer.MAX_VALUE, null)); + + List groupNames = new ArrayList<>(); + for (String groupName : groupReq.getPage()) { + if (groupName.startsWith(PermissionService.GROUP_PREFIX)) { + groupName = groupName.substring(PermissionService.GROUP_PREFIX.length()); } - - return groupNames.toArray(new String[0]); + groupNames.add(groupName); } - }, true); - - } - - public void updateUser(HashMap userInfo) throws Exception { - - if(userInfo == null) { - throw new PropertyRequiredException(CCConstants.CM_PROP_PERSON_USERNAME); - } - - String userName = (String)userInfo.get(CCConstants.CM_PROP_PERSON_USERNAME); - String currentUser = AuthenticationUtil.getRunAsUser(); - if (!currentUser.equals(userName) && !isAdmin()) { - throw new AccessDeniedException("admin role required."); - } - - PersonService personService = serviceRegistry.getPersonService(); - - serviceRegistry.getTransactionService().getRetryingTransactionHelper().doInTransaction( - (RetryingTransactionCallback) () -> { - Throwable runAs = AuthenticationUtil.runAs( - () -> { - try{ - addUserExtensionAspect(userName); - personService.setPersonProperties(userName, transformPropMap(userInfo)); - } catch (Throwable e) { - logger.error(e.getMessage(), e); - return e; - } - return null; - }, - ApplicationInfoList.getHomeRepository().getUsername()); - - if (runAs != null) { - throw runAs; - } - return null; - }, - false); - userCache.refresh(userName); - } - - private void addUserExtensionAspect(String userName) { - PersonService personService = serviceRegistry.getPersonService(); - if(!nodeService.hasAspect(personService.getPerson(userName),QName.createQName(CCConstants.CCM_ASPECT_USER_EXTENSION))) - nodeService.addAspect(personService.getPerson(userName),QName.createQName(CCConstants.CCM_ASPECT_USER_EXTENSION),null); - } - - public void createOrUpdateUser(HashMap userInfo) throws Exception { - - String currentUser = AuthenticationUtil.getRunAsUser(); - - if(userInfo == null){ - throw new PropertyRequiredException(CCConstants.CM_PROP_PERSON_USERNAME); - } - - String userName = userInfo.get(CCConstants.CM_PROP_PERSON_USERNAME); - String firstName = userInfo.get(CCConstants.CM_PROP_PERSON_FIRSTNAME); - String lastName = userInfo.get(CCConstants.CM_PROP_PERSON_LASTNAME); - String email = userInfo.get(CCConstants.CM_PROP_PERSON_EMAIL); - - if(userName == null || userName.trim().equals("")){ - throw new PropertyRequiredException(CCConstants.CM_PROP_PERSON_USERNAME); - } - - if(firstName == null || firstName.trim().equals("")){ - throw new PropertyRequiredException(CCConstants.CM_PROP_PERSON_FIRSTNAME); - } - - if(lastName == null || lastName.trim().equals("")){ - throw new PropertyRequiredException(CCConstants.CM_PROP_PERSON_LASTNAME); - } - - if(email == null || email.trim().equals("")){ - throw new PropertyRequiredException(CCConstants.CM_PROP_PERSON_EMAIL); - } - - if (!currentUser.equals(userName) && !isAdmin()) { - throw new AccessDeniedException("admin role required."); - } - - PersonService personService = serviceRegistry.getPersonService(); - - serviceRegistry.getTransactionService().getRetryingTransactionHelper().doInTransaction( - - new RetryingTransactionCallback() - { - public Void execute() throws Throwable - { - Throwable runAs = AuthenticationUtil.runAs( - - new AuthenticationUtil.RunAsWork() { - - @Override - public Throwable doWork() throws Exception { - - try { - - if (personService.personExists(userName)) { - - personService.setPersonProperties(userName, transformPropMap(userInfo)); - - } else { - - personService.createPerson(transformPropMap(userInfo)); - } - addUserExtensionAspect(userName); - - } catch (Throwable e) { - logger.error(e.getMessage(), e); - return e; - } - - return null; - } - }, - ApplicationInfoList.getHomeRepository().getUsername()); - - if (runAs != null) { - throw runAs; - } - - return null; - } - - }, - false); - - } + return groupNames.toArray(new String[0]); + }, true); - public void deleteUser(String userName) { - - PersonService personService = serviceRegistry.getPersonService(); - - serviceRegistry.getTransactionService().getRetryingTransactionHelper().doInTransaction( - - new RetryingTransactionCallback() - { - public Void execute() throws Throwable - { - personService.deletePerson(userName); + } + + public String[] searchGroupNames(String pattern) throws Exception { + + AuthorityService authorityService = serviceRegistry.getAuthorityService(); - return null; + return serviceRegistry.getTransactionService().getRetryingTransactionHelper().doInTransaction( + + () -> { + PagingResults groupReq = + authorityService.getAuthoritiesInfo( + AuthorityType.GROUP, + null, + pattern, + null, + true, + new PagingRequest(Integer.MAX_VALUE, null)); + + List groupNames = new ArrayList<>(); + for (AuthorityInfo groupInfo : groupReq.getPage()) { + groupNames.add(groupInfo.getAuthorityName()); } - }, false); - - } - - public void deleteGroup(String groupName) { - - AuthorityService authorityService = serviceRegistry.getAuthorityService(); - - serviceRegistry.getTransactionService().getRetryingTransactionHelper().doInTransaction( - - new RetryingTransactionCallback() - { - public Void execute() throws Throwable - { - String key = PermissionService.GROUP_PREFIX + groupName; - - authorityService.deleteAuthority(key, true); - return null; + return groupNames.toArray(new String[0]); + }, true); + + } + + public void updateUser(Map userInfo) throws Exception { + + if (userInfo == null) { + throw new PropertyRequiredException(CCConstants.CM_PROP_PERSON_USERNAME); + } + + String userName = (String) userInfo.get(CCConstants.CM_PROP_PERSON_USERNAME); + String currentUser = AuthenticationUtil.getRunAsUser(); + + if (!currentUser.equals(userName) && !isAdmin()) { + throw new AccessDeniedException("admin role required."); + } + + PersonService personService = serviceRegistry.getPersonService(); + + serviceRegistry.getTransactionService().getRetryingTransactionHelper().doInTransaction( + (RetryingTransactionCallback) () -> { + Throwable runAs = AuthenticationUtil.runAs( + () -> { + try { + addUserExtensionAspect(userName); + personService.setPersonProperties(userName, transformPropMap(userInfo)); + } catch (Throwable e) { + log.error(e.getMessage(), e); + return e; + } + return null; + }, + ApplicationInfoList.getHomeRepository().getUsername()); + + if (runAs != null) { + throw runAs; } - }, false); - } + return null; + }, + false); + userCache.refresh(userName); + } - public void removeAllMemberships(String groupName) { - - AuthorityService authorityService = serviceRegistry.getAuthorityService(); - - serviceRegistry.getTransactionService().getRetryingTransactionHelper().doInTransaction( - - new RetryingTransactionCallback() - { - public Void execute() throws Throwable - { - String key = PermissionService.GROUP_PREFIX + groupName; - - for (String containedAuthority : authorityService.getContainedAuthorities(null, key, true)) { - - authorityService.removeAuthority(key, containedAuthority); - } - - return null; + private void addUserExtensionAspect(String userName) { + PersonService personService = serviceRegistry.getPersonService(); + if (!nodeService.hasAspect(personService.getPerson(userName), QName.createQName(CCConstants.CCM_ASPECT_USER_EXTENSION))) + nodeService.addAspect(personService.getPerson(userName), QName.createQName(CCConstants.CCM_ASPECT_USER_EXTENSION), null); + } + + public void createOrUpdateUser(Map userInfo) throws Exception { + + String currentUser = AuthenticationUtil.getRunAsUser(); + + if (userInfo == null) { + throw new PropertyRequiredException(CCConstants.CM_PROP_PERSON_USERNAME); + } + + String userName = userInfo.get(CCConstants.CM_PROP_PERSON_USERNAME); + String firstName = userInfo.get(CCConstants.CM_PROP_PERSON_FIRSTNAME); + String lastName = userInfo.get(CCConstants.CM_PROP_PERSON_LASTNAME); + String email = userInfo.get(CCConstants.CM_PROP_PERSON_EMAIL); + + if (userName == null || userName.trim().equals("")) { + throw new PropertyRequiredException(CCConstants.CM_PROP_PERSON_USERNAME); + } + + if (firstName == null || firstName.trim().equals("")) { + throw new PropertyRequiredException(CCConstants.CM_PROP_PERSON_FIRSTNAME); + } + + if (lastName == null || lastName.trim().equals("")) { + throw new PropertyRequiredException(CCConstants.CM_PROP_PERSON_LASTNAME); + } + + if (email == null || email.trim().equals("")) { + throw new PropertyRequiredException(CCConstants.CM_PROP_PERSON_EMAIL); + } + + if (!currentUser.equals(userName) && !isAdmin()) { + throw new AccessDeniedException("admin role required."); + } + + PersonService personService = serviceRegistry.getPersonService(); + + serviceRegistry.getTransactionService().getRetryingTransactionHelper().doInTransaction( + + (RetryingTransactionCallback) () -> { + Throwable runAs = AuthenticationUtil.runAs( + + () -> { + + try { + + if (personService.personExists(userName)) { + + personService.setPersonProperties(userName, transformPropMap(userInfo)); + + } else { + + personService.createPerson(transformPropMap(userInfo)); + } + addUserExtensionAspect(userName); + + } catch (Throwable e) { + log.error(e.getMessage(), e); + return e; + } + + return null; + }, + ApplicationInfoList.getHomeRepository().getUsername()); + + if (runAs != null) { + throw runAs; } - }, false); + return null; + }, + false); - } + } - public void setUserPassword(String userName, String newPassword){ - - MutableAuthenticationService authenticationService = serviceRegistry.getAuthenticationService(); - - if (authenticationService.isAuthenticationMutable(userName)) { - - authenticationService.setAuthentication(userName, newPassword.toCharArray()); - - } else { - - authenticationService.createAuthentication(userName, newPassword.toCharArray()); - } - } + public void deleteUser(String userName) { - public void updateUserPassword(String userName, String oldPassword, String newPassword){ - - MutableAuthenticationService authenticationService = serviceRegistry.getAuthenticationService(); - - if (authenticationService.isAuthenticationMutable(userName)) { - - authenticationService.updateAuthentication(userName, oldPassword.toCharArray(), newPassword.toCharArray()); - - } - } - - public void removeNode(String nodeID, String fromID) { - removeNode(nodeID,fromID,true); - } - - public void removeNode(String nodeID, String fromID,boolean recycle) { - // NodeService.removeChild will lead to an accessdeniedException when - // the user got no DeleteChildren permission on the folder(fromId) - // this appears i.e. when we have an linked GroupFolder and the group - // gots the Collaborator right on it, - // cause Collaborator brings no DeleteChildren permission with - // so if fromID is the primary parent then we call deleteNode instead of - // removeChild - NodeRef nodeRef = new NodeRef(storeRef, nodeID); - ChildAssociationRef childAssocRef = nodeService.getPrimaryParent(nodeRef); - if(fromID == null){ - fromID = childAssocRef.getParentRef().getId(); - } - if (childAssocRef.getParentRef().getId().equals(fromID)) { + PersonService personService = serviceRegistry.getPersonService(); - if(!recycle){ - // unlock the node (in case it was locked by alfresco, e.g. by webdav) - if(serviceRegistry.getLockService().isLocked(nodeRef)) { - serviceRegistry.getLockService().unlock(nodeRef); - } - nodeService.addAspect(nodeRef, ContentModel.ASPECT_TEMPORARY, null); - } - nodeService.deleteNode(nodeRef); + serviceRegistry.getTransactionService().getRetryingTransactionHelper().doInTransaction( - } else { - nodeService.removeChild(new NodeRef(storeRef, fromID), nodeRef); - } + (RetryingTransactionCallback) () -> { + personService.deletePerson(userName); - } + return null; + }, false); - public void removeNodeAndRelations(String nodeID, String fromID) throws Throwable { - this.removeNodeAndRelations(nodeID, fromID, true); - } - - public void removeNodeAndRelations(String nodeID, String fromID, boolean recycle) throws Throwable { - logger.info("called"); - this.removeRelationsForNode(nodeID, fromID); - this.removeNode(nodeID, fromID,recycle); - logger.info("return"); - } + } - public boolean hasContent(String nodeId, String contentProp) throws Exception { - ContentReader reader = serviceRegistry.getContentService().getReader(new NodeRef(storeRef, nodeId), QName.createQName(contentProp)); - if (reader != null && reader.getSize() > 0) { - return true; - } else { - return false; - } - } + public void deleteGroup(String groupName) { - public void executeAction(String nodeId, String actionName, String actionId, HashMap parameters, boolean async) { - - ActionService actionService = serviceRegistry.getActionService(); - Action action = actionService.createAction(actionName); - action.setTrackStatus(true); + AuthorityService authorityService = serviceRegistry.getAuthorityService(); - NodeRef nodeRef = new NodeRef(storeRef, nodeId); + serviceRegistry.getTransactionService().getRetryingTransactionHelper().doInTransaction( - if (async) { - ActionObserver.getInstance().addAction(nodeRef, action); - } - if (parameters != null) { - for (Object key : parameters.keySet()) { - action.setParameterValue((String) key, (Serializable) parameters.get(key)); - } - } - actionService.executeAction(action, nodeRef, true, async); + (RetryingTransactionCallback) () -> { + String key = PermissionService.GROUP_PREFIX + groupName; - } + authorityService.deleteAuthority(key, true); - public String getGroupFolderId() throws Throwable { - return getGroupFolderId(this.authenticationInfo.get(CCConstants.AUTH_USERNAME)); - } + return null; + }, false); + } - public String getGroupFolderId(String userName) { - try { - String homeFolder=getHomeFolderID(userName); - if(homeFolder==null){ - logger.info("User "+userName+" has no home folder, will return no group folder for person"); - return null; - } - NodeRef child = NodeServiceFactory.getLocalService().getChild(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, homeFolder, CCConstants.CCM_TYPE_MAP, CCConstants.CCM_PROP_MAP_TYPE, CCConstants.CCM_VALUE_MAP_TYPE_EDUGROUP); - return child.getId(); - }catch(Exception e){ - logger.info("Exception while fetching user "+userName+": "+e.getMessage()+", will return no group folder for person"); - return null; - } - } + public void removeAllMemberships(String groupName) { - public HashMap getGroupFolders() throws Throwable { - String folderId = getGroupFolderId(); - if (folderId == null) { - logger.info("No GroupFolders ... returning empty map."); - return new HashMap(); - } - final HashMap map = getChildren(folderId); - logger.debug("No GroupFolders ... returning map with size(" + map.size() + ")."); - return map; - } + AuthorityService authorityService = serviceRegistry.getAuthorityService(); - public ArrayList getEduGroups() throws Throwable { - - ArrayList result = new ArrayList(); - HashMap> edugroups = search("@ccm\\:edu_homedir:\"workspace://*\""); - for(Map.Entry> entry : edugroups.entrySet()){ - String nodeRef = (String)entry.getValue().get(CCConstants.CCM_PROP_AUTHORITYCONTAINER_EDUHOMEDIR); - //when a group folder relation is removed the noderef can be null cause of async solr refresh - try{ - if(nodeRef != null){ - String nodeId = nodeRef.replace("workspace://SpacesStore/", ""); - HashMap folderProps = getProperties(nodeId); - EduGroup eduGroup = new EduGroup(); - eduGroup.setFolderId((String)folderProps.get(CCConstants.SYS_PROP_NODE_UID)); - eduGroup.setFolderName((String)folderProps.get(CCConstants.CM_NAME)); - eduGroup.setGroupId((String)entry.getValue().get(CCConstants.SYS_PROP_NODE_UID)); - eduGroup.setGroupname((String)entry.getValue().get(CCConstants.CM_PROP_AUTHORITY_AUTHORITYNAME)); - eduGroup.setGroupDisplayName((String)entry.getValue().get(CCConstants.CM_PROP_AUTHORITY_AUTHORITYDISPLAYNAME)); - eduGroup.setFolderPath(getPath((String)folderProps.get(CCConstants.SYS_PROP_NODE_UID))); - result.add(eduGroup); - } - }catch(AccessDeniedException e){} - } - return result; - } + serviceRegistry.getTransactionService().getRetryingTransactionHelper().doInTransaction( - public String getFavoritesFolder() throws Throwable { + (RetryingTransactionCallback) () -> { + String key = PermissionService.GROUP_PREFIX + groupName; - String userName = this.authenticationInfo.get(CCConstants.AUTH_USERNAME); + for (String containedAuthority : authorityService.getContainedAuthorities(null, key, true)) { - String homefolderID = getHomeFolderID(userName); - HashMap> children = getChildren(homefolderID, CCConstants.CCM_TYPE_MAP); + authorityService.removeAuthority(key, containedAuthority); + } - String basketsFolderID = null; + return null; + }, false); - for (String key : children.keySet()) { - HashMap props = children.get(key); + } - if (CCConstants.CCM_VALUE_MAP_TYPE_FAVORITE.equals(props.get(CCConstants.CCM_PROP_MAP_TYPE))) { - basketsFolderID = key; - break; - } - } + public void setUserPassword(String userName, String newPassword) { - if (basketsFolderID == null) { + MutableAuthenticationService authenticationService = serviceRegistry.getAuthenticationService(); - logger.info("creating Favorites Folder for:" + userName); + if (authenticationService.isAuthenticationMutable(userName)) { - HashMap properties = new HashMap(); + authenticationService.setAuthentication(userName, newPassword.toCharArray()); - // get an alfresco installation locale corresponding name - String userFavoritesFolderName = I18nServer.getTranslationDefaultResourcebundle(CCConstants.I18n_USERFOLDER_FAVORITES); + } else { - String folderName = new DuplicateFinder().getUniqueValue(getChildren(homefolderID), CCConstants.CM_NAME, userFavoritesFolderName); + authenticationService.createAuthentication(userName, newPassword.toCharArray()); + } + } - properties.put(CCConstants.CM_NAME, folderName); - properties.put(CCConstants.CCM_PROP_MAP_TYPE, CCConstants.CCM_VALUE_MAP_TYPE_FAVORITE); + public void updateUserPassword(String userName, String oldPassword, String newPassword) { - basketsFolderID = createNode(homefolderID, CCConstants.CCM_TYPE_MAP, CCConstants.CM_ASSOC_FOLDER_CONTAINS, properties); - } + MutableAuthenticationService authenticationService = serviceRegistry.getAuthenticationService(); - return basketsFolderID; - } + if (authenticationService.isAuthenticationMutable(userName)) { - public HashMap getBaskets() throws Throwable { - String favoritesFolderID = getFavoritesFolder(); - HashMap favoritesfolderChilds = getChildren(favoritesFolderID); - Object[] keyarr = favoritesfolderChilds.keySet().toArray(); - HashMap basketHashMap = new HashMap(); - for (Object key : keyarr) { - HashMap properties = (HashMap) favoritesfolderChilds.get(key); - if (properties.get(CCConstants.NODETYPE).equals(CCConstants.CM_TYPE_FOLDER) - || properties.get(CCConstants.NODETYPE).equals(CCConstants.CCM_TYPE_MAP)) { - HashMap basketContent = getChildren((String) key); - properties.put(CCConstants.CCM_ASSOC_BASKETCONTENT, basketContent); - basketHashMap.put(key, properties); - } - } - return basketHashMap; - } + authenticationService.updateAuthentication(userName, oldPassword.toCharArray(), newPassword.toCharArray()); - public HashMap hasAllPermissions(String nodeId, String[] permissions) { - return hasAllPermissions(storeRef.getProtocol(), storeRef.getIdentifier(), nodeId, permissions); - } - - public HashMap hasAllPermissions(String storeProtocol, String storeId, String nodeId, String[] permissions) { - ApplicationInfo appInfo = ApplicationInfoList.getHomeRepository(); - boolean guest= GuestCagePolicy.getGuestUsers().contains(AuthenticationUtil.getFullyAuthenticatedUser()); - PermissionService permissionService = serviceRegistry.getPermissionService(); - HashMap result = new HashMap(); - NodeRef nodeRef = new NodeRef(new StoreRef(storeProtocol,storeId), nodeId); - if (permissions != null && permissions.length > 0) { - for (String permission : permissions) { - AccessStatus accessStatus = permissionService.hasPermission(nodeRef, permission); - // Guest only has read permissions, no modify permissions - if(guest && !Arrays.asList(org.edu_sharing.service.permission.PermissionService.GUEST_PERMISSIONS).contains(permission)){ - accessStatus=AccessStatus.DENIED; - } - if (accessStatus.equals(AccessStatus.ALLOWED)) { - result.put(permission, new Boolean(true)); - } else { - result.put(permission, new Boolean(false)); - } - } - } - return result; - } + } + } - /** - * with this method you got the opportunity to test if an authority has a - * set of permissions it's using the AuthenticationUtil.runAs Method of the - * Alfresco Foundation API - */ - public HashMap hasAllPermissions(String nodeId, String authority, String[] permissions) throws Exception { - - /** - * Strange behavior in alfresco: GROUP_EVERYONE is not a real group. - * When calling PermissionService.hasPermissions alfresco checks if the authority exists - * so alfresco-5.0.d raises an exception at AuthorityDAOImpl.listAuthorities(AuthorityDAOImpl.java:1086) - * - * but this check is not done with users (without "GROUP_" prefix) - * - * - * so the workaround is to change the authority to a user that does not exist. - * if GROUP_EVERYONE got's a permission on the node, the not existent user would have the permission, else not - * - * so we change the authority name to EVERYONE - * @TODO policy that prevents "EVERYONE" to become a real alfresco user - */ - if(authority.equals(PermissionService.ALL_AUTHORITIES)){ - authority = "EVERYONE"; - } - - OwnableService ownableService = serviceRegistry.getOwnableService(); - PermissionService permissionService = serviceRegistry.getPermissionService(); - if (authority.equals(PermissionService.OWNER_AUTHORITY)) { - authority = ownableService.getOwner(new NodeRef(storeRef, nodeId)); - logger.info(PermissionService.OWNER_AUTHORITY + " mapping on userId:" + ownableService); - } + public void removeNode(String nodeID, String fromID) { + removeNode(nodeID, fromID, true); + } - return AuthenticationUtil.runAs(new HasPermissionsWork(permissionService, authority, permissions, nodeId), authority); - } + public void removeNode(String nodeID, String fromID, boolean recycle) { + // NodeService.removeChild will lead to an accessdeniedException when + // the user got no DeleteChildren permission on the folder(fromId) + // this appears i.e. when we have an linked GroupFolder and the group + // gots the Collaborator right on it, + // cause Collaborator brings no DeleteChildren permission with + // so if fromID is the primary parent then we call deleteNode instead of + // removeChild + NodeRef nodeRef = new NodeRef(storeRef, nodeID); + ChildAssociationRef childAssocRef = nodeService.getPrimaryParent(nodeRef); + if (fromID == null) { + fromID = childAssocRef.getParentRef().getId(); + } + if (childAssocRef.getParentRef().getId().equals(fromID)) { - public boolean hasPermissions(String nodeId, String authority, String[] permissions) throws Exception { - HashMap hasAllPermResult = this.hasAllPermissions(nodeId, authority, permissions); - for (String permission : permissions) { - Boolean tmpBool = hasAllPermResult.get(permission); - if (tmpBool == null || tmpBool.booleanValue() == false) { - return false; - } - } - return true; - } + if (!recycle) { + // unlock the node (in case it was locked by alfresco, e.g. by webdav) + if (serviceRegistry.getLockService().isLocked(nodeRef)) { + serviceRegistry.getLockService().unlock(nodeRef); + } + nodeService.addAspect(nodeRef, ContentModel.ASPECT_TEMPORARY, null); + } + nodeService.deleteNode(nodeRef); - public boolean hasPermissions(String nodeId, String[] permissions) { - boolean result = true; - HashMap hasAllPerm = hasAllPermissions(nodeId, permissions); - for (Map.Entry entry : hasAllPerm.entrySet()) { - if (entry.getValue() == false) { - result = false; - } - } - return result; - } - - public User getOwner(String storeId,String storeProtocol,String nodeId){ - NodeRef nodeRef = new NodeRef(new StoreRef(storeProtocol,storeId), nodeId); - String owner = this.serviceRegistry.getOwnableService().getOwner(nodeRef); - if(owner == null){ - return null; - } - return userCache.getUser(owner); - } + } else { + nodeService.removeChild(new NodeRef(storeRef, fromID), nodeRef); + } - /** - * @return the resolveRemoteObjects - */ - public boolean isResolveRemoteObjects() { - return resolveRemoteObjects; - } + } - /** - * @param resolveRemoteObjects - * the resolveRemoteObjects to set - */ - public void setResolveRemoteObjects(boolean resolveRemoteObjects) { - this.resolveRemoteObjects = resolveRemoteObjects; - } + public void removeNodeAndRelations(String nodeID, String fromID) throws Throwable { + this.removeNodeAndRelations(nodeID, fromID, true); + } - public void setProperty(String nodeId, String property, Serializable value) { - this.nodeService.setProperty(new NodeRef(storeRef, nodeId), QName.createQName(property), value); - } - - public void setProperty(String nodeId, String property, ArrayList value) { - - if(CCConstants.CCM_PROP_EDUSCOPE_NAME.equals(property)){ - - boolean isSystemUser = false; - - String user = (String)AuthenticationUtil.getFullyAuthenticatedUser(); - if("admin".equals(user)) { - isSystemUser = true; - } - - if(AuthenticationUtil.isRunAsUserTheSystemUser()){ - isSystemUser = true; - } - - if(!isSystemUser){ - throw new RuntimeException("it's not allowed to change the scope"); - } - } - - this.nodeService.setProperty(new NodeRef(storeRef, nodeId), QName.createQName(property), value); - } + public void removeNodeAndRelations(String nodeID, String fromID, boolean recycle) throws Throwable { + log.info("called"); + this.removeRelationsForNode(nodeID, fromID); + this.removeNode(nodeID, fromID, recycle); + log.info("return"); + } + + public boolean hasContent(String nodeId, String contentProp) throws Exception { + ContentReader reader = serviceRegistry.getContentService().getReader(new NodeRef(storeRef, nodeId), QName.createQName(contentProp)); + if (reader != null && reader.getSize() > 0) { + return true; + } else { + return false; + } + } + + public void executeAction(String nodeId, String actionName, String actionId, Map parameters, boolean async) { + + ActionService actionService = serviceRegistry.getActionService(); + Action action = actionService.createAction(actionName); + action.setTrackStatus(true); + + NodeRef nodeRef = new NodeRef(storeRef, nodeId); + + if (async) { + ActionObserver.getInstance().addAction(nodeRef, action); + } + if (parameters != null) { + for (Object key : parameters.keySet()) { + action.setParameterValue((String) key, (Serializable) parameters.get(key)); + } + } + actionService.executeAction(action, nodeRef, true, async); + + } + + public String getGroupFolderId() throws Throwable { + return getGroupFolderId(this.authenticationInfo.get(CCConstants.AUTH_USERNAME)); + } + + public String getGroupFolderId(String userName) { + try { + String homeFolder = getHomeFolderID(userName); + if (homeFolder == null) { + log.info("User " + userName + " has no home folder, will return no group folder for person"); + return null; + } + NodeRef child = NodeServiceFactory.getLocalService().getChild(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, homeFolder, CCConstants.CCM_TYPE_MAP, CCConstants.CCM_PROP_MAP_TYPE, CCConstants.CCM_VALUE_MAP_TYPE_EDUGROUP); + return child.getId(); + } catch (Exception e) { + log.info("Exception while fetching user " + userName + ": " + e.getMessage() + ", will return no group folder for person"); + return null; + } + } + + public Map> getGroupFolders() throws Throwable { + String folderId = getGroupFolderId(); + if (folderId == null) { + log.info("No GroupFolders ... returning empty map."); + return new HashMap<>(); + } + final Map> map = getChildren(folderId); + log.debug("No GroupFolders ... returning map with size(" + map.size() + ")."); + return map; + } + + public ArrayList getEduGroups() throws Throwable { + + ArrayList result = new ArrayList<>(); + Map> edugroups = search("@ccm\\:edu_homedir:\"workspace://*\""); + for (Map.Entry> entry : edugroups.entrySet()) { + String nodeRef = (String) entry.getValue().get(CCConstants.CCM_PROP_AUTHORITYCONTAINER_EDUHOMEDIR); + //when a group folder relation is removed the noderef can be null cause of async solr refresh + try { + if (nodeRef != null) { + String nodeId = nodeRef.replace("workspace://SpacesStore/", ""); + Map folderProps = getProperties(nodeId); + EduGroup eduGroup = new EduGroup(); + eduGroup.setFolderId((String) folderProps.get(CCConstants.SYS_PROP_NODE_UID)); + eduGroup.setFolderName((String) folderProps.get(CCConstants.CM_NAME)); + eduGroup.setGroupId((String) entry.getValue().get(CCConstants.SYS_PROP_NODE_UID)); + eduGroup.setGroupname((String) entry.getValue().get(CCConstants.CM_PROP_AUTHORITY_AUTHORITYNAME)); + eduGroup.setGroupDisplayName((String) entry.getValue().get(CCConstants.CM_PROP_AUTHORITY_AUTHORITYDISPLAYNAME)); + eduGroup.setFolderPath(getPath((String) folderProps.get(CCConstants.SYS_PROP_NODE_UID))); + result.add(eduGroup); + } + } catch (AccessDeniedException e) { + } + } + return result; + } + + public String getFavoritesFolder() throws Throwable { + + String userName = this.authenticationInfo.get(CCConstants.AUTH_USERNAME); + + String homefolderID = getHomeFolderID(userName); + Map> children = getChildren(homefolderID, CCConstants.CCM_TYPE_MAP); + + String basketsFolderID = null; + + for (String key : children.keySet()) { + + Map props = children.get(key); + + if (CCConstants.CCM_VALUE_MAP_TYPE_FAVORITE.equals(props.get(CCConstants.CCM_PROP_MAP_TYPE))) { + basketsFolderID = key; + break; + } + } + + if (basketsFolderID == null) { + + log.info("creating Favorites Folder for:" + userName); + + Map properties = new HashMap<>(); + + // get an alfresco installation locale corresponding name + String userFavoritesFolderName = I18nServer.getTranslationDefaultResourcebundle(CCConstants.I18n_USERFOLDER_FAVORITES); + + String folderName = new DuplicateFinder().getUniqueValue(getChildren(homefolderID), CCConstants.CM_NAME, userFavoritesFolderName); + + properties.put(CCConstants.CM_NAME, folderName); + properties.put(CCConstants.CCM_PROP_MAP_TYPE, CCConstants.CCM_VALUE_MAP_TYPE_FAVORITE); + + basketsFolderID = createNode(homefolderID, CCConstants.CCM_TYPE_MAP, CCConstants.CM_ASSOC_FOLDER_CONTAINS, properties); + } + + return basketsFolderID; + } + + public Map> getBaskets() throws Throwable { + String favoritesFolderID = getFavoritesFolder(); + Map> favoritesfolderChilds = getChildren(favoritesFolderID); + String[] keyarr = favoritesfolderChilds.keySet().toArray(new String[0]); + Map> basketHashMap = new HashMap<>(); + for (String key : keyarr) { + Map properties = favoritesfolderChilds.get(key); + if (properties.get(CCConstants.NODETYPE).equals(CCConstants.CM_TYPE_FOLDER) + || properties.get(CCConstants.NODETYPE).equals(CCConstants.CCM_TYPE_MAP)) { + Map> basketContent = getChildren((String) key); + properties.put(CCConstants.CCM_ASSOC_BASKETCONTENT, basketContent); + basketHashMap.put(key, properties); + } + } + return basketHashMap; + } + + public Map hasAllPermissions(String nodeId, String[] permissions) { + return hasAllPermissions(storeRef.getProtocol(), storeRef.getIdentifier(), nodeId, permissions); + } + + public Map hasAllPermissions(String storeProtocol, String storeId, String nodeId, String[] permissions) { + ApplicationInfo appInfo = ApplicationInfoList.getHomeRepository(); + boolean guest = GuestCagePolicy.getGuestUsers().contains(AuthenticationUtil.getFullyAuthenticatedUser()); + PermissionService permissionService = serviceRegistry.getPermissionService(); + Map result = new HashMap<>(); + NodeRef nodeRef = new NodeRef(new StoreRef(storeProtocol, storeId), nodeId); + if (permissions != null && permissions.length > 0) { + for (String permission : permissions) { + AccessStatus accessStatus = permissionService.hasPermission(nodeRef, permission); + // Guest only has read permissions, no modify permissions + if (guest && !Arrays.asList(org.edu_sharing.service.permission.PermissionService.GUEST_PERMISSIONS).contains(permission)) { + accessStatus = AccessStatus.DENIED; + } + if (accessStatus.equals(AccessStatus.ALLOWED)) { + result.put(permission, new Boolean(true)); + } else { + result.put(permission, new Boolean(false)); + } + } + } + return result; + } + + /** + * with this method you got the opportunity to test if an authority has a + * set of permissions it's using the AuthenticationUtil.runAs Method of the + * Alfresco Foundation API + */ + public Map hasAllPermissions(String nodeId, String authority, String[] permissions) throws Exception { + + /** + * Strange behavior in alfresco: GROUP_EVERYONE is not a real group. + * When calling PermissionService.hasPermissions alfresco checks if the authority exists + * so alfresco-5.0.d raises an exception at AuthorityDAOImpl.listAuthorities(AuthorityDAOImpl.java:1086) + * + * but this check is not done with users (without "GROUP_" prefix) + * + * + * so the workaround is to change the authority to a user that does not exist. + * if GROUP_EVERYONE got's a permission on the node, the not existent user would have the permission, else not + * + * so we change the authority name to EVERYONE + * @TODO policy that prevents "EVERYONE" to become a real alfresco user + */ + if (authority.equals(PermissionService.ALL_AUTHORITIES)) { + authority = "EVERYONE"; + } + + OwnableService ownableService = serviceRegistry.getOwnableService(); + PermissionService permissionService = serviceRegistry.getPermissionService(); + if (authority.equals(PermissionService.OWNER_AUTHORITY)) { + authority = ownableService.getOwner(new NodeRef(storeRef, nodeId)); + log.info(PermissionService.OWNER_AUTHORITY + " mapping on userId:" + ownableService); + } + + return AuthenticationUtil.runAs(new HasPermissionsWork(permissionService, authority, permissions, nodeId), authority); + } + + public boolean hasPermissions(String nodeId, String authority, String[] permissions) throws Exception { + Map hasAllPermResult = this.hasAllPermissions(nodeId, authority, permissions); + for (String permission : permissions) { + Boolean tmpBool = hasAllPermResult.get(permission); + if (tmpBool == null || tmpBool.booleanValue() == false) { + return false; + } + } + return true; + } + + public boolean hasPermissions(String nodeId, String[] permissions) { + boolean result = true; + Map hasAllPerm = hasAllPermissions(nodeId, permissions); + for (Map.Entry entry : hasAllPerm.entrySet()) { + if (entry.getValue() == false) { + result = false; + } + } + return result; + } + + public User getOwner(String storeId, String storeProtocol, String nodeId) { + NodeRef nodeRef = new NodeRef(new StoreRef(storeProtocol, storeId), nodeId); + String owner = this.serviceRegistry.getOwnableService().getOwner(nodeRef); + if (owner == null) { + return null; + } + return userCache.getUser(owner); + } + + /** + * @return the resolveRemoteObjects + */ + public boolean isResolveRemoteObjects() { + return resolveRemoteObjects; + } + + /** + * @param resolveRemoteObjects + * the resolveRemoteObjects to set + */ + public void setResolveRemoteObjects(boolean resolveRemoteObjects) { + this.resolveRemoteObjects = resolveRemoteObjects; + } + + public void setProperty(String nodeId, String property, Serializable value) { + this.nodeService.setProperty(new NodeRef(storeRef, nodeId), QName.createQName(property), value); + } + + public void setProperty(String nodeId, String property, ArrayList value) { + + if (CCConstants.CCM_PROP_EDUSCOPE_NAME.equals(property)) { + + boolean isSystemUser = false; + + String user = (String) AuthenticationUtil.getFullyAuthenticatedUser(); + if ("admin".equals(user)) { + isSystemUser = true; + } + + if (AuthenticationUtil.isRunAsUserTheSystemUser()) { + isSystemUser = true; + } + + if (!isSystemUser) { + throw new RuntimeException("it's not allowed to change the scope"); + } + } + + this.nodeService.setProperty(new NodeRef(storeRef, nodeId), QName.createQName(property), value); + } + + @Override + public MCBaseClient getInstance(Map authenticationInfo) { + return new MCAlfrescoAPIClient(authenticationInfo); + } + + @Override + public MCBaseClient getInstance(String repositoryFile, Map authenticationInfo) { + return new MCAlfrescoAPIClient(repositoryFile, authenticationInfo); + } + + public String newBasket(String _basketName) throws Throwable { + String basketsFolderID = this.getFavoritesFolder(); + Map properties = new HashMap<>(); + properties.put(CCConstants.CM_PROP_C_TITLE, _basketName); + properties.put(CCConstants.CM_NAME, _basketName); + return this.createNode(basketsFolderID, CCConstants.CCM_TYPE_MAP, properties); + } + + /** + * was a basket not created within a favorite folder and just created thru + * createChildAssociation so the favorite folder is not the primary parent + * and the basket will just get removed from the favorite folder + * + * @param basketID + * @return + * @throws org.apache.axis.AxisFault + * @throws RemoteException + */ + public boolean removeBasket(String basketID) throws Throwable { + String fromID = getFavoritesFolder(); + /** + * just to remove node is not enough, because the children get deleted in cascade + */ + removeNodeAndRelations(basketID, fromID); + return true; + } + + public boolean createChildAssociation(String folderId, String nodeId) { + nodeService.addChild(new NodeRef(storeRef, folderId), new NodeRef(storeRef, nodeId), ContentModel.ASSOC_CONTAINS, ContentModel.ASSOC_CONTAINS); + return true; + } + + @Override + public void createShare(String nodeId, String[] emails, long expiryDate) throws Exception { + ShareService shareService = new ShareServiceImpl(PermissionServiceFactory.getPermissionService(appInfo.getAppId())); + String locale = (String) Context.getCurrentInstance().getRequest().getSession().getAttribute(CCConstants.AUTH_LOCALE); + shareService.createShare(nodeId, emails, expiryDate, null, locale); + } + + public Share[] getShares(String nodeId) { + ShareService shareService = new ShareServiceImpl(PermissionServiceFactory.getPermissionService(appInfo.getAppId())); + return shareService.getShares(nodeId); + } + + public boolean removeChildAssociation(String folderId, String nodeId) { + nodeService.removeChild(new NodeRef(storeRef, folderId), new NodeRef(storeRef, nodeId)); + return true; + } + + public Map> getParents(String nodeID, boolean primary) throws Throwable { + // nodeService.getP + Map> result = new HashMap<>(); + NodeRef nodeRef = new NodeRef(storeRef, nodeID); + if (primary) { + ChildAssociationRef cAR = nodeService.getPrimaryParent(nodeRef); + + log.info("cAR:" + cAR); + log.info("cAR getChildRef:" + cAR.getChildRef().getId()); + log.info("cAR getParentRef:" + cAR.getParentRef().getId()); + + result.put(cAR.getParentRef().getId(), this.getProperties(cAR.getParentRef())); + } else { + List parents = nodeService.getParentAssocs(nodeRef); + try { + for (ChildAssociationRef parent : parents) { + String parentNodeId = parent.getParentRef().getId(); + Map parentProps = getProperties(parent.getParentRef()); + result.put(parentNodeId, parentProps); + } + } catch (AccessDeniedException e) { + log.info("access denied error while getting parents for:" + nodeID + " will continue with the next one"); + } + } + return result; + } + + public ChildAssociationRef getParent(NodeRef nodeRef) { + return nodeService.getPrimaryParent(nodeRef); + } + + public ACL getPermissions(String nodeId) throws Exception { + + return serviceRegistry.getTransactionService().getRetryingTransactionHelper().doInTransaction( + + () -> { + PermissionService permissionsService = serviceRegistry.getPermissionService(); + + NodeRef nodeRef = new NodeRef(storeRef, nodeId); + Set permSet = permissionsService.getAllSetPermissions(nodeRef); + Iterator iter = permSet.iterator(); + + boolean isInherited = false; + + ACL result = new ACL(); + ArrayList aces = new ArrayList<>(); + + + while (iter.hasNext()) { + AccessPermission ace = iter.next(); + String alfAuthority = ace.getAuthority(); + + String authority = alfAuthority; + + authority = (authority == null) ? authority = ace.getAuthority() : authority; + String permission = ace.getPermission(); + ACE aceResult = new ACE(); + aceResult.setAuthority(authority); + aceResult.setPermission(permission); + + aceResult.setInherited(ace.isInherited()); + + // to be compatible with WS API where positiv access status is called "acepted" + // in GUI we compare with "acepted" + String accessStatus = ace.getAccessStatus().name(); + if (accessStatus.trim().equals("ALLOWED")) { + accessStatus = "acepted"; + } + + aceResult.setAccessStatus(accessStatus); + aceResult.setAuthorityType(AuthorityType.getAuthorityType(alfAuthority).name()); + + if (AuthorityType.getAuthorityType(alfAuthority).equals(AuthorityType.USER) || + AuthorityType.getAuthorityType(alfAuthority).equals(AuthorityType.OWNER)) { + + NodeRef personNodeRef = null; + if (AuthorityType.getAuthorityType(alfAuthority).equals(AuthorityType.OWNER)) { + personNodeRef = personService.getPersonOrNull(serviceRegistry.getOwnableService().getOwner(nodeRef)); + } else { + personNodeRef = personService.getPersonOrNull(alfAuthority); + } + + if (personNodeRef != null) { + Map personProps = nodeService.getProperties(personNodeRef); + User user = new User(); + user.setNodeId(personNodeRef.getId()); + user.setEmail((String) personProps.get(ContentModel.PROP_EMAIL)); + user.setGivenName((String) personProps.get(ContentModel.PROP_FIRSTNAME)); + user.setSurname((String) personProps.get(ContentModel.PROP_LASTNAME)); + user.setEditable( + AuthorityServiceHelper.isAdmin() || + !Objects.equals(AuthenticationUtil.getFullyAuthenticatedUser(), alfAuthority) + ); + + String repository = (String) personProps.get(QName.createQName(CCConstants.PROP_USER_REPOSITORYID)); + if (repository == null || repository.trim().equals("")) + repository = appInfo.getAppId(); + user.setRepositoryId(repository); + user.setUsername((String) personProps.get(ContentModel.PROP_USERNAME)); + aceResult.setUser(user); + } else { + User user = new User(); + user.setUsername(alfAuthority); + aceResult.setUser(user); + } + } + + + if (AuthorityType.getAuthorityType(alfAuthority).equals(AuthorityType.GROUP)) { + NodeRef groupNodeRef = serviceRegistry.getAuthorityService().getAuthorityNodeRef(alfAuthority); + if (groupNodeRef == null) { + log.warn("authority " + alfAuthority + " does not exist." + " will continue"); + continue; + } + + Map groupProps = nodeService.getProperties(groupNodeRef); + Group group = new Group(); + group.setName(alfAuthority); + group.setDisplayName((String) groupProps.get(ContentModel.PROP_AUTHORITY_DISPLAY_NAME)); + group.setNodeId(groupNodeRef.getId()); + group.setRepositoryId(appInfo.getAppId()); + group.setAuthorityType(AuthorityType.getAuthorityType(alfAuthority).name()); + group.setScope((String) nodeService.getProperty(nodeRef, QName.createQName(CCConstants.CCM_PROP_SCOPE_TYPE))); + + NodeRef authorityNodeRef = authorityService.getAuthorityNodeRef(alfAuthority); + if (authorityNodeRef != null) { + String groupType = (String) nodeService.getProperty(authorityNodeRef, QName.createQName(CCConstants.CCM_PROP_GROUPEXTENSION_GROUPTYPE)); + if (groupType != null) { + group.setGroupType(groupType); + + if (CCConstants.ADMINISTRATORS_GROUP_TYPE.equals(groupType) + && permission.equals(PermissionService.COORDINATOR)) { + + if (isSharedNode(nodeId)) { + group.setEditable(false); + } else { + group.setEditable(true); + } + + } + } + } + aceResult.setGroup(group); + } + + log.debug("authority" + authority + " Permission:" + permission + " ACCESSSTATUS:" + aceResult.getAccessStatus() + "isInherited:" + + ace.isInherited() + " getInheritParentPermissions(nodeRef):" + permissionsService.getInheritParentPermissions(nodeRef)); + + aces.add(aceResult); + } + + result.setAces(aces.toArray(new ACE[aces.size()])); + + log.debug("permissionsService.getInheritParentPermissions(nodeRef):" + permissionsService.getInheritParentPermissions(nodeRef)); + isInherited = permissionsService.getInheritParentPermissions(nodeRef); + + result.setInherited(isInherited); + return result; + + }, false); + } + + /** true if this node is in a shared context ("My shared files"), false if it's in users home + * + * @param nodeId + * @return + * @throws Throwable + */ + private boolean isSharedNode(String nodeId) { + try { + + String groupFolderId = getGroupFolderId(AuthenticationUtil.getFullyAuthenticatedUser()); + List sharedFolderIds = new ArrayList<>(); + + if (groupFolderId != null) { + Map> children = getChildren(groupFolderId); + for (Object key : children.keySet()) { + sharedFolderIds.add(key.toString()); + } + } + if (sharedFolderIds.size() == 0) return false; + + NodeRef last = new NodeRef(storeRef, nodeId); + while (true) { + if (last == null) break; + if (sharedFolderIds.contains(last.getId())) return true; + last = getParent(last).getParentRef(); + } + + } catch (Throwable t) { + log.warn(t.getMessage()); + } + return false; + } + + /** + * returns admin authority if context is an edugroup + * @param nodeRef + * @return + */ + String getAdminAuthority(NodeRef nodeRef) { + String authorityAdministrator = null; + if (isSharedNode(nodeRef.getId())) { + Set allSetPermissions = serviceRegistry.getPermissionService().getAllSetPermissions(nodeRef); + for (AccessPermission ap : allSetPermissions) { + NodeRef authorityNodeRef = authorityService.getAuthorityNodeRef(ap.getAuthority()); + if (authorityNodeRef != null) { + String groupType = (String) nodeService.getProperty(authorityNodeRef, QName.createQName(CCConstants.CCM_PROP_GROUPEXTENSION_GROUPTYPE)); + if (groupType != null && CCConstants.ADMINISTRATORS_GROUP_TYPE.equals(groupType) + && ap.getPermission().equals(PermissionService.COORDINATOR)) { + authorityAdministrator = ap.getAuthority(); + } + } + } + } + return authorityAdministrator; + } + + public void removeRelations(String parentID) throws Exception { + NodeRef parentNodeRef = new NodeRef(storeRef, parentID); + List childAssocList = nodeService.getChildAssocs(parentNodeRef); + for (ChildAssociationRef child : childAssocList) { + String childType = nodeService.getType(child.getChildRef()).toString(); + if (childType.equals(CCConstants.CCM_TYPE_MAPRELATION)) { + this.removeNode(child.getChildRef().getId(), parentID); + } + } + } + + public void removeRelationsForNode(String nodeId, String nodeParentId) throws Throwable { + + Map> childrenRelation = getChildren(nodeParentId, CCConstants.CCM_TYPE_MAPRELATION); + + for (String relationNodeId : childrenRelation.keySet()) { + Map props = childrenRelation.get(relationNodeId); + for (String propKey : props.keySet()) { + + if (propKey.equals(CCConstants.CCM_ASSOC_RELSOURCE) || propKey.equals(CCConstants.CCM_ASSOC_RELTARGET)) { + + String relToNodeId = (String) props.get(propKey); + if (relToNodeId.equals(nodeId)) { + removeNode(relationNodeId, nodeParentId); + } + } + } + } + } + + /** + * + * @param parentID + * @param childID + * @param association (is ignored) + * removes all associations between two nodes + */ + public void removeChild(String parentID, String childID, String association) { + nodeService.removeChild(new NodeRef(storeRef, parentID), new NodeRef(storeRef, childID)); + } + + public String dropToBasketRemoteNode(String basketId, Map params) throws Exception { + String result = createRemoteNode(basketId, params); + return result; + } - @Override - public MCBaseClient getInstance(HashMap authenticationInfo) { - return new MCAlfrescoAPIClient(authenticationInfo); - } + public String createRemoteNode(String parentId, Map params) throws Exception { - @Override - public MCBaseClient getInstance(String repositoryFile, HashMap authenticationInfo) { - return new MCAlfrescoAPIClient(repositoryFile, authenticationInfo); - } + String result = null; + String remoteNodeId = params.get(CCConstants.NODEID); + String remoteRepository = params.get(CCConstants.REPOSITORY_ID); + String remoteRepositoryType = params.get(CCConstants.REPOSITORY_TYPE); - public String newBasket(String _basketName) throws Throwable { - String basketsFolderID = this.getFavoritesFolder(); - HashMap properties = new HashMap(); - properties.put(CCConstants.CM_PROP_C_TITLE, _basketName); - properties.put(CCConstants.CM_NAME, _basketName); - return this.createNode(basketsFolderID, CCConstants.CCM_TYPE_MAP, properties); - } + if (remoteNodeId != null && remoteNodeId.trim().length() > 0 && remoteRepository != null && remoteRepository.trim().length() > 0) { + Map properties = new HashMap<>(); + properties.put(CCConstants.CCM_PROP_REMOTEOBJECT_NODEID, remoteNodeId); + properties.put(CCConstants.CCM_PROP_REMOTEOBJECT_REPOSITORYID, remoteRepository); - /** - * was a basket not created within a favorite folder and just created thru - * createChildAssociation so the favorite folder is not the primary parent - * and the basket will just get removed from the favorite folder - * - * @param basketID - * @return - * @throws org.apache.axis.AxisFault - * @throws RemoteException - */ - public boolean removeBasket(String basketID) throws Throwable { - String fromID = getFavoritesFolder(); - /** - * just to remove node is not enough, because the children get deleted in cascade - */ - removeNodeAndRelations(basketID, fromID); - return true; - } + if (remoteRepositoryType == null || remoteRepositoryType.trim().equals("")) { + ApplicationInfo appInfo = ApplicationInfoList.getRepositoryInfoById(remoteRepository); + remoteRepositoryType = appInfo.getRepositoryType(); + } - public boolean createChildAssociation(String folderId, String nodeId) { - nodeService.addChild(new NodeRef(storeRef, folderId), new NodeRef(storeRef, nodeId), ContentModel.ASSOC_CONTAINS, ContentModel.ASSOC_CONTAINS); - return true; - } + properties.put(CCConstants.CCM_PROP_REMOTEOBJECT_REPOSITORY_TYPE, remoteRepositoryType); - @Override - public void createShare(String nodeId, String[] emails, long expiryDate) throws Exception { - ShareService shareService = new ShareServiceImpl(PermissionServiceFactory.getPermissionService(appInfo.getAppId())); - String locale = (String) Context.getCurrentInstance().getRequest().getSession().getAttribute(CCConstants.AUTH_LOCALE); - shareService.createShare(nodeId, emails, expiryDate, null, locale); - } + result = this.createNode(parentId, CCConstants.CCM_TYPE_REMOTEOBJECT, properties); - public Share[] getShares(String nodeId) { - ShareService shareService = new ShareServiceImpl(PermissionServiceFactory.getPermissionService(appInfo.getAppId())); - return shareService.getShares(nodeId); - } + } else { + log.error("missing remote NodeId or remoteRepository"); + } + return result; + } - public boolean removeChildAssociation(String folderId, String nodeId) { - nodeService.removeChild(new NodeRef(storeRef, folderId), new NodeRef(storeRef, nodeId)); - return true; - } + public void moveNode(String newParentId, String childAssocType, String nodeId) throws Exception { + String originalName = + (String) nodeService.getProperty( + new NodeRef(storeRef, nodeId), + QName.createQName(CCConstants.CM_NAME)); + + nodeService.setProperty(new NodeRef(storeRef, nodeId), QName.createQName(CCConstants.CM_NAME), UUID.randomUUID().toString()); + nodeService.setProperty(new NodeRef(storeRef, nodeId), QName.createQName(CCConstants.CM_NAME), UUID.randomUUID().toString()); + try { + nodeService.moveNode( + new NodeRef(storeRef, nodeId), + new NodeRef(storeRef, newParentId), + QName.createQName(childAssocType), + QName.createQName(CCConstants.NAMESPACE_CCM, nodeId)); + } catch (Exception e) { + nodeService.setProperty(new NodeRef(storeRef, nodeId), QName.createQName(CCConstants.CM_NAME), originalName); + throw e; + } + String name = originalName; + int i = 1; + int maxRetries = 10; + while (nodeService.getChildByName(new NodeRef(storeRef, newParentId), ContentModel.ASSOC_CONTAINS, name) != null && i <= maxRetries) { + name = NodeServiceHelper.renameNode(originalName, i++); + } - public HashMap getParents(String nodeID, boolean primary) throws Throwable { - // nodeService.getP - HashMap result = new HashMap(); - NodeRef nodeRef = new NodeRef(storeRef, nodeID); - if (primary) { - ChildAssociationRef cAR = nodeService.getPrimaryParent(nodeRef); - - logger.info("cAR:" + cAR); - logger.info("cAR getChildRef:" + cAR.getChildRef().getId()); - logger.info("cAR getParentRef:" + cAR.getParentRef().getId()); - - result.put(cAR.getParentRef().getId(), this.getProperties(cAR.getParentRef())); - } else { - List parents = nodeService.getParentAssocs(nodeRef); - try { - for (ChildAssociationRef parent : parents) { - String parentNodeId = parent.getParentRef().getId(); - HashMap parentProps = getProperties(parent.getParentRef()); - result.put(parentNodeId, parentProps); - } - } catch (AccessDeniedException e) { - logger.info("access denied error while getting parents for:" + nodeID + " will continue with the next one"); - } - } - return result; - } - - public ChildAssociationRef getParent(NodeRef nodeRef){ - return nodeService.getPrimaryParent(nodeRef); - } + boolean canApplyName = i <= maxRetries; + if (canApplyName) { + nodeService.setProperty(new NodeRef(storeRef, nodeId), QName.createQName(CCConstants.CM_NAME), name); + } - public ACL getPermissions(String nodeId) throws Exception { + // remove from cache so that the new primary parent will be refreshed + Cache repCache = new RepositoryCache(); + repCache.remove(nodeId); + } - return serviceRegistry.getTransactionService().getRetryingTransactionHelper().doInTransaction( - - new RetryingTransactionCallback() - { - public ACL execute() throws Throwable - { - PermissionService permissionsService = serviceRegistry.getPermissionService(); - - NodeRef nodeRef = new NodeRef(storeRef, nodeId); - Set permSet = permissionsService.getAllSetPermissions(nodeRef); - Iterator iter = permSet.iterator(); - - boolean isInherited = false; - - ACL result = new ACL(); - ArrayList aces = new ArrayList(); - - - while (iter.hasNext()) { - AccessPermission ace = iter.next(); - String alfAuthority = ace.getAuthority(); - - String authority = alfAuthority; - - authority = (authority == null) ? authority = ace.getAuthority() : authority; - String permission = ace.getPermission(); - ACE aceResult = new ACE(); - aceResult.setAuthority(authority); - aceResult.setPermission(permission); - - aceResult.setInherited(ace.isInherited()); - - // to be compatible with WS API where positiv access status is called "acepted" - // in GUI we compare with "acepted" - String accessStatus = ace.getAccessStatus().name(); - if (accessStatus.trim().equals("ALLOWED")) { - accessStatus = "acepted"; - } - - aceResult.setAccessStatus(accessStatus); - aceResult.setAuthorityType(AuthorityType.getAuthorityType(alfAuthority).name()); - - if (AuthorityType.getAuthorityType(alfAuthority).equals(AuthorityType.USER) || - AuthorityType.getAuthorityType(alfAuthority).equals(AuthorityType.OWNER)) { - - NodeRef personNodeRef = null; - if(AuthorityType.getAuthorityType(alfAuthority).equals(AuthorityType.OWNER)){ - personNodeRef = personService.getPersonOrNull(serviceRegistry.getOwnableService().getOwner(nodeRef)); - }else{ - personNodeRef = personService.getPersonOrNull(alfAuthority); - } - - if(personNodeRef != null) { - Map personProps = nodeService.getProperties(personNodeRef); - User user = new User(); - user.setNodeId(personNodeRef.getId()); - user.setEmail((String) personProps.get(ContentModel.PROP_EMAIL)); - user.setGivenName((String) personProps.get(ContentModel.PROP_FIRSTNAME)); - user.setSurname((String) personProps.get(ContentModel.PROP_LASTNAME)); - user.setEditable( - AuthorityServiceHelper.isAdmin() || - !Objects.equals(AuthenticationUtil.getFullyAuthenticatedUser(), alfAuthority) - ); - - String repository = (String) personProps.get(QName.createQName(CCConstants.PROP_USER_REPOSITORYID)); - if (repository == null || repository.trim().equals("")) repository = appInfo.getAppId(); - user.setRepositoryId(repository); - user.setUsername((String) personProps.get(ContentModel.PROP_USERNAME)); - aceResult.setUser(user); - }else{ - User user = new User(); - user.setUsername(alfAuthority); - aceResult.setUser(user); - } - } - - - if (AuthorityType.getAuthorityType(alfAuthority).equals(AuthorityType.GROUP)) { - NodeRef groupNodeRef = serviceRegistry.getAuthorityService().getAuthorityNodeRef(alfAuthority); - if(groupNodeRef == null) { - logger.warn("authority " + alfAuthority + " does not exist." + " will continue"); - continue; - } - - Map groupProps = nodeService.getProperties(groupNodeRef); - Group group = new Group(); - group.setName(alfAuthority); - group.setDisplayName((String) groupProps.get(ContentModel.PROP_AUTHORITY_DISPLAY_NAME)); - group.setNodeId(groupNodeRef.getId()); - group.setRepositoryId(appInfo.getAppId()); - group.setAuthorityType(AuthorityType.getAuthorityType(alfAuthority).name()); - group.setScope((String)nodeService.getProperty(nodeRef, QName.createQName(CCConstants.CCM_PROP_SCOPE_TYPE))); - - NodeRef authorityNodeRef = authorityService.getAuthorityNodeRef(alfAuthority); - if(authorityNodeRef != null) { - String groupType = (String)nodeService.getProperty(authorityNodeRef, QName.createQName(CCConstants.CCM_PROP_GROUPEXTENSION_GROUPTYPE)); - if(groupType != null) { - group.setGroupType(groupType); - - if(CCConstants.ADMINISTRATORS_GROUP_TYPE.equals(groupType) - && permission.equals(PermissionService.COORDINATOR)) { - - if(isSharedNode(nodeId)) { - group.setEditable(false); - }else{ - group.setEditable(true); - } - - } - } - } - aceResult.setGroup(group); - } - - logger.debug("authority" + authority + " Permission:" + permission + " ACCESSSTATUS:" + aceResult.getAccessStatus() + "isInherited:" - + ace.isInherited() + " getInheritParentPermissions(nodeRef):" + permissionsService.getInheritParentPermissions(nodeRef)); - - aces.add(aceResult); - } - - result.setAces(aces.toArray(new ACE[aces.size()])); - - logger.debug("permissionsService.getInheritParentPermissions(nodeRef):" + permissionsService.getInheritParentPermissions(nodeRef)); - isInherited = permissionsService.getInheritParentPermissions(nodeRef); - - result.setInherited(isInherited); - return result; - - } - }, false); - } - - /** true if this node is in a shared context ("My shared files"), false if it's in users home - * - * @param nodeId - * @return - * @throws Throwable - */ - private boolean isSharedNode(String nodeId) { - try { - - String groupFolderId = getGroupFolderId(AuthenticationUtil.getFullyAuthenticatedUser()); - List sharedFolderIds=new ArrayList<>(); - - if (groupFolderId != null) { - HashMap> children = getChildren(groupFolderId); - for (Object key : children.keySet()) { - sharedFolderIds.add(key.toString()); - } - } - if(sharedFolderIds.size()==0) return false; - - NodeRef last=new NodeRef(storeRef,nodeId); - while(true) { - if(last==null) break; - if(sharedFolderIds.contains(last.getId())) return true; - last=getParent(last).getParentRef(); - } - - } catch(Throwable t){ - logger.warn(t.getMessage()); - } - return false; - } - /** - * returns admin authority if context is an edugroup - * @param nodeRef - * @return - */ - String getAdminAuthority(NodeRef nodeRef) { - String authorityAdministrator = null; - if(isSharedNode(nodeRef.getId())){ - Set allSetPermissions = serviceRegistry.getPermissionService().getAllSetPermissions(nodeRef); - for(AccessPermission ap : allSetPermissions) { - NodeRef authorityNodeRef = authorityService.getAuthorityNodeRef(ap.getAuthority()); - if(authorityNodeRef != null) { - String groupType = (String)nodeService.getProperty(authorityNodeRef, QName.createQName(CCConstants.CCM_PROP_GROUPEXTENSION_GROUPTYPE)); - if(groupType != null && CCConstants.ADMINISTRATORS_GROUP_TYPE.equals(groupType) - && ap.getPermission().equals(PermissionService.COORDINATOR)) { - authorityAdministrator = ap.getAuthority(); - } - } - } - } - return authorityAdministrator; - } - - public void removeRelations(String parentID) throws Exception { - NodeRef parentNodeRef = new NodeRef(storeRef, parentID); - List childAssocList = nodeService.getChildAssocs(parentNodeRef); - for (ChildAssociationRef child : childAssocList) { - String childType = nodeService.getType(child.getChildRef()).toString(); - if (childType.equals(CCConstants.CCM_TYPE_MAPRELATION)) { - this.removeNode(child.getChildRef().getId(), parentID); - } - } - } + /** + * @param nodeId : the id of the node to copy + * @param toNodeId : the id of the target folder + * @param copyChildren + */ + public String copyNode(String nodeId, String toNodeId, boolean copyChildren) throws Exception { + NodeRef nodeRef = new NodeRef(MCAlfrescoAPIClient.storeRef, nodeId); - public void removeRelationsForNode(String nodeId, String nodeParentId) throws Throwable { - - HashMap> childrenRelation = getChildren(nodeParentId, CCConstants.CCM_TYPE_MAPRELATION); + CopyService copyService = serviceRegistry.getCopyService(); - for (String relationNodeId : childrenRelation.keySet()) { - HashMap props = childrenRelation.get(relationNodeId); - for (String propKey : props.keySet()) { + String name = (String) nodeService.getProperty(nodeRef, ContentModel.PROP_NAME); + NodeRef copyNodeRef = copyService.copyAndRename(nodeRef, new NodeRef(MCAlfrescoAPIClient.storeRef, toNodeId), QName.createQName(CCConstants.CM_ASSOC_FOLDER_CONTAINS), + QName.createQName(name), copyChildren); - if (propKey.equals(CCConstants.CCM_ASSOC_RELSOURCE) || propKey.equals(CCConstants.CCM_ASSOC_RELTARGET)) { + return copyNodeRef.getId(); + } - String relToNodeId = (String) props.get(propKey); - if (relToNodeId.equals(nodeId)) { - removeNode(relationNodeId, nodeParentId); - } - } - } - } - } - /** - * - * @param parentID - * @param childID - * @param association (is ignored) - * removes all associations between two nodes - */ - public void removeChild(String parentID, String childID, String association) { - nodeService.removeChild(new NodeRef(storeRef, parentID), new NodeRef(storeRef, childID)); - } + public String copyNode(String nodeId, String toNodeId, String assocType, String assocName, boolean copyChildren) throws Exception { + NodeRef nodeRef = new NodeRef(MCAlfrescoAPIClient.storeRef, nodeId); - public String dropToBasketRemoteNode(String basketId, HashMap params) throws Exception { - String result = createRemoteNode(basketId, params); - return result; - } + CopyService copyService = serviceRegistry.getCopyService(); - public String createRemoteNode(String parentId, HashMap params) throws Exception { - - String result = null; - String remoteNodeId = params.get(CCConstants.NODEID); - String remoteRepository = params.get(CCConstants.REPOSITORY_ID); - String remoteRepositoryType = params.get(CCConstants.REPOSITORY_TYPE); - - if (remoteNodeId != null && remoteNodeId.trim().length() > 0 && remoteRepository != null && remoteRepository.trim().length() > 0) { - HashMap properties = new HashMap(); - properties.put(CCConstants.CCM_PROP_REMOTEOBJECT_NODEID, remoteNodeId); - properties.put(CCConstants.CCM_PROP_REMOTEOBJECT_REPOSITORYID, remoteRepository); - - if (remoteRepositoryType == null || remoteRepositoryType.trim().equals("")) { - ApplicationInfo appInfo = ApplicationInfoList.getRepositoryInfoById(remoteRepository); - remoteRepositoryType = appInfo.getRepositoryType(); - } + NodeRef copyNodeRef = copyService.copy(nodeRef, new NodeRef(MCAlfrescoAPIClient.storeRef, toNodeId), QName.createQName(assocType), + QName.createQName(assocName), copyChildren); - properties.put(CCConstants.CCM_PROP_REMOTEOBJECT_REPOSITORY_TYPE, remoteRepositoryType); + return copyNodeRef.getId(); + } - result = this.createNode(parentId, CCConstants.CCM_TYPE_REMOTEOBJECT, properties); + /** + * walk through all parents until you find a folder that is used as + * edugrouphomedir of a edugroup return the Group + * + * @param nodeId + * @return + * @throws CCException + */ + public Group getEduGroupContextOfNode(String nodeId) { + + NodeRef result = null; + + NodeRef nodeRef = new NodeRef(storeRef, nodeId); + QName nodeType = null; + QName mapType = QName.createQName(CCConstants.CCM_TYPE_MAP); + + Collection eduGroupNodeRefs = new VirtualEduGroupFolderTool(serviceRegistry, nodeService).getEduGroupNodeRefs(); + + // nodeRefEduGroupFolder , noderefEduGroup + Map eduGroupEduGroupFolderMap = new HashMap<>(); + for (NodeRef eduGroupNodeRef : eduGroupNodeRefs) { + eduGroupEduGroupFolderMap.put((NodeRef) nodeService.getProperty(eduGroupNodeRef, QName.createQName(CCConstants.CCM_PROP_EDUGROUP_EDU_HOMEDIR)), + eduGroupNodeRef); + } - } else { - logger.error("missing remote NodeId or remoteRepository"); - } - return result; - } + Group group = null; + try { + do { + ChildAssociationRef parentAssocRef = nodeService.getPrimaryParent(nodeRef); + nodeRef = (parentAssocRef == null) ? null : parentAssocRef.getParentRef(); + if (nodeRef != null) { + nodeType = nodeService.getType(nodeRef); + } - public void moveNode(String newParentId, String childAssocType, String nodeId) throws Exception { - String originalName = - (String) nodeService.getProperty( - new NodeRef(storeRef, nodeId), - QName.createQName(CCConstants.CM_NAME)); - - nodeService.setProperty(new NodeRef(storeRef, nodeId), QName.createQName(CCConstants.CM_NAME), UUID.randomUUID().toString()); - nodeService.setProperty(new NodeRef(storeRef, nodeId), QName.createQName(CCConstants.CM_NAME), UUID.randomUUID().toString()); - try { - nodeService.moveNode( - new NodeRef(storeRef, nodeId), - new NodeRef(storeRef, newParentId), - QName.createQName(childAssocType), - QName.createQName(CCConstants.NAMESPACE_CCM, nodeId)); - } catch(Exception e) { - nodeService.setProperty(new NodeRef(storeRef, nodeId), QName.createQName(CCConstants.CM_NAME), originalName); - throw e; - } - String name = originalName; - int i = 1; - int maxRetries = 10; - while (nodeService.getChildByName(new NodeRef(storeRef, newParentId), ContentModel.ASSOC_CONTAINS, name) != null && i <= maxRetries) { - name = NodeServiceHelper.renameNode(originalName, i++); - } + NodeRef groupNodeRef = eduGroupEduGroupFolderMap.get(nodeRef); + if ((groupNodeRef != null)) { + result = groupNodeRef; - boolean canApplyName = i <= maxRetries; - if (canApplyName) { - nodeService.setProperty(new NodeRef(storeRef, nodeId), QName.createQName(CCConstants.CM_NAME), name); - } + } - // remove from cache so that the new primary parent will be refreshed - Cache repCache = new RepositoryCache(); - repCache.remove(nodeId); - } + } while (nodeRef != null && mapType.equals(nodeType) && result == null); + + if (result != null) { + group = new Group(); + String authorityName = (String) nodeService.getProperty(result, ContentModel.PROP_AUTHORITY_NAME); + group.setName(authorityName); + group.setDisplayName((String) nodeService.getProperty(result, ContentModel.PROP_AUTHORITY_DISPLAY_NAME)); + group.setRepositoryId(appInfo.getAppId()); + group.setNodeId(result.getId()); + group.setAuthorityType(AuthorityType.getAuthorityType(group.getName()).name()); + group.setScope((String) nodeService.getProperty(nodeRef, QName.createQName(CCConstants.CCM_PROP_SCOPE_TYPE))); + NodeRef authorityNodeRef = authorityService.getAuthorityNodeRef(authorityName); + if (authorityNodeRef != null) { + String groupType = (String) nodeService.getProperty(authorityNodeRef, QName.createQName(CCConstants.CCM_PROP_GROUPEXTENSION_GROUPTYPE)); + if (groupType != null) { + group.setGroupType(groupType); + } + } + } + } catch (org.alfresco.repo.security.permissions.AccessDeniedException e) { + // maybe while doing nodeService.getPrimaryParent(nodeRef); and + // landing in an folder where i have no read permissions + log.debug(e.getMessage()); + } + return group; + } - /** - * @param nodeId : the id of the node to copy - * @param toNodeId : the id of the target folder - * @param copyChildren - */ - public String copyNode(String nodeId, String toNodeId, boolean copyChildren) throws Exception { - NodeRef nodeRef = new NodeRef(MCAlfrescoAPIClient.storeRef, nodeId); + public Map checkAndCreateShadowUser(String username, String email, String repId) throws Exception { + throw new Exception("checkAndCreateShadowUser is not implemented!"); + } - CopyService copyService = serviceRegistry.getCopyService(); + public Map> getVersionHistory(String nodeId) throws Throwable { + VersionService versionService = serviceRegistry.getVersionService(); + VersionHistory versionHistory = versionService.getVersionHistory(new NodeRef(storeRef, nodeId)); + Map> result = null; + if (versionHistory != null && versionHistory.getAllVersions() != null && versionHistory.getAllVersions().size() > 0) { + result = new HashMap<>(); + Collection versions = versionHistory.getAllVersions(); - String name = (String) nodeService.getProperty(nodeRef, ContentModel.PROP_NAME); - NodeRef copyNodeRef = copyService.copyAndRename(nodeRef, new NodeRef(MCAlfrescoAPIClient.storeRef, toNodeId), QName.createQName(CCConstants.CM_ASSOC_FOLDER_CONTAINS), - QName.createQName(name), copyChildren); - - return copyNodeRef.getId(); - } - - public String copyNode(String nodeId, String toNodeId, String assocType, String assocName, boolean copyChildren) throws Exception { - NodeRef nodeRef = new NodeRef(MCAlfrescoAPIClient.storeRef, nodeId); + for (Version version : versions) { - CopyService copyService = serviceRegistry.getCopyService(); + Map props = getPropertiesSimple(version.getFrozenStateNodeRef().getStoreRef(), version.getFrozenStateNodeRef().getId()); - NodeRef copyNodeRef = copyService.copy(nodeRef, new NodeRef(MCAlfrescoAPIClient.storeRef, toNodeId),QName.createQName(assocType), - QName.createQName(assocName), copyChildren); - - return copyNodeRef.getId(); - } - - /** - * walk through all parents until you find a folder that is used as - * edugrouphomedir of a edugroup return the Group - * - * @param nodeId - * @return - * @throws CCException - */ - public Group getEduGroupContextOfNode(String nodeId) { - - NodeRef result = null; - - NodeRef nodeRef = new NodeRef(storeRef, nodeId); - QName nodeType = null; - QName mapType = QName.createQName(CCConstants.CCM_TYPE_MAP); - - Collection eduGroupNodeRefs = new VirtualEduGroupFolderTool(serviceRegistry, nodeService).getEduGroupNodeRefs(); - - // nodeRefEduGroupFolder , noderefEduGroup - Map eduGroupEduGroupFolderMap = new HashMap(); - for (NodeRef eduGroupNodeRef : eduGroupNodeRefs) { - eduGroupEduGroupFolderMap.put((NodeRef) nodeService.getProperty(eduGroupNodeRef, QName.createQName(CCConstants.CCM_PROP_EDUGROUP_EDU_HOMEDIR)), - eduGroupNodeRef); - } + log.debug(" version prop UID:" + props.get(CCConstants.SYS_PROP_NODE_UID)); + log.debug(" version NodeID:" + props.get(CCConstants.NODEID)); - Group group = null; - try { - do { - ChildAssociationRef parentAssocRef = nodeService.getPrimaryParent(nodeRef); - nodeRef = (parentAssocRef == null) ? null : parentAssocRef.getParentRef(); - if (nodeRef != null) { - nodeType = nodeService.getType(nodeRef); - } + props.put(CCConstants.ALFRESCO_MIMETYPE, getAlfrescoMimetype(version.getFrozenStateNodeRef())); + // contenturl + String contentUrl = URLTool.getNgRenderNodeUrl(nodeId, version.getVersionLabel()); + contentUrl = URLTool.addOAuthAccessToken(contentUrl); - NodeRef groupNodeRef = eduGroupEduGroupFolderMap.get(nodeRef); - if ((groupNodeRef != null)) { - result = groupNodeRef; + props.put(CCConstants.CONTENTURL, contentUrl); + if (props.get(CCConstants.ALFRESCO_MIMETYPE) != null && contentUrl != null) { + props.put(CCConstants.DOWNLOADURL, URLTool.getDownloadServletUrl(nodeId, version.getVersionLabel(), true)); + } - } + // thumbnail take the current thumbnail cause subobjects + // (thumbnail will be removed by versioning) + setPreviewUrlWithoutTicket(storeRef, nodeId, props); + String thumbnailUrl = (String) props.get(CCConstants.CM_ASSOC_THUMBNAILS); + if (thumbnailUrl != null && !thumbnailUrl.trim().equals("")) { + // prevent Browser Caching + thumbnailUrl = UrlTool.setParam(thumbnailUrl, "dontcache", new Long(System.currentTimeMillis()).toString()); + props.put(CCConstants.CM_ASSOC_THUMBNAILS, thumbnailUrl); + } - } while (nodeRef != null && mapType.equals(nodeType) && result == null); - - if (result != null) { - group = new Group(); - String authorityName = (String) nodeService.getProperty(result, ContentModel.PROP_AUTHORITY_NAME); - group.setName(authorityName); - group.setDisplayName((String) nodeService.getProperty(result, ContentModel.PROP_AUTHORITY_DISPLAY_NAME)); - group.setRepositoryId(appInfo.getAppId()); - group.setNodeId(result.getId()); - group.setAuthorityType(AuthorityType.getAuthorityType(group.getName()).name()); - group.setScope((String)nodeService.getProperty(nodeRef, QName.createQName(CCConstants.CCM_PROP_SCOPE_TYPE))); - NodeRef authorityNodeRef = authorityService.getAuthorityNodeRef(authorityName); - if(authorityNodeRef != null) { - String groupType = (String)nodeService.getProperty(authorityNodeRef, QName.createQName(CCConstants.CCM_PROP_GROUPEXTENSION_GROUPTYPE)); - if(groupType != null) { - group.setGroupType(groupType); - } - } - } - } catch (org.alfresco.repo.security.permissions.AccessDeniedException e) { - // maybe while doing nodeService.getPrimaryParent(nodeRef); and - // landing in an folder where i have no read permissions - logger.debug(e.getMessage()); - } - - return group; - } + // version store NodeId + props.put(CCConstants.VERSION_STORE_NODEID, version.getFrozenStateNodeRef().getId()); - public HashMap checkAndCreateShadowUser(String username, String email, String repId) throws Exception { - throw new Exception("checkAndCreateShadowUser is not implemented!"); - } + // versionLabel + props.put(CCConstants.CM_PROP_VERSIONABLELABEL, version.getVersionLabel()); - public HashMap> getVersionHistory(String nodeId) throws Throwable { - VersionService versionService = serviceRegistry.getVersionService(); - VersionHistory versionHistory = versionService.getVersionHistory(new NodeRef(storeRef, nodeId)); - HashMap> result = null; - if (versionHistory != null && versionHistory.getAllVersions() != null && versionHistory.getAllVersions().size() > 0) { - result = new HashMap>(); - Collection versions = versionHistory.getAllVersions(); - - for (Version version : versions) { - - HashMap props = getPropertiesSimple(version.getFrozenStateNodeRef().getStoreRef(), version.getFrozenStateNodeRef().getId()); - - logger.debug(" version prop UID:" + props.get(CCConstants.SYS_PROP_NODE_UID)); - logger.debug(" version NodeID:" + props.get(CCConstants.NODEID)); - - props.put(CCConstants.ALFRESCO_MIMETYPE, getAlfrescoMimetype(version.getFrozenStateNodeRef())); - // contenturl - String contentUrl = URLTool.getNgRenderNodeUrl(nodeId,version.getVersionLabel()); - contentUrl = URLTool.addOAuthAccessToken(contentUrl); - - props.put(CCConstants.CONTENTURL, contentUrl); - if (props.get(CCConstants.ALFRESCO_MIMETYPE) != null && contentUrl != null) { - props.put(CCConstants.DOWNLOADURL, URLTool.getDownloadServletUrl(nodeId,version.getVersionLabel(), true)); - } + /* add permalink */ + String v = version.getVersionLabel(); + String permaLink = URLTool.getBaseUrl() + "/node/" + nodeId; + permaLink = (v != null) ? permaLink + "/" + v : permaLink; + props.put(CCConstants.VIRT_PROP_PERMALINK, permaLink); - // thumbnail take the current thumbnail cause subobjects - // (thumbnail will be removed by versioning) - setPreviewUrlWithoutTicket(storeRef, nodeId, props); - String thumbnailUrl = (String) props.get(CCConstants.CM_ASSOC_THUMBNAILS); - if (thumbnailUrl != null && !thumbnailUrl.trim().equals("")) { - // prevent Browser Caching - thumbnailUrl = UrlTool.setParam(thumbnailUrl, "dontcache", new Long(System.currentTimeMillis()).toString()); - props.put(CCConstants.CM_ASSOC_THUMBNAILS, thumbnailUrl); - } + result.put(version.getFrozenStateNodeRef().getId(), props); + } + } + return result; + } - // version store NodeId - props.put(CCConstants.VERSION_STORE_NODEID, version.getFrozenStateNodeRef().getId()); + public void revertVersion(String nodeId, String verLbl) throws Exception { + VersionService versionService = serviceRegistry.getVersionService(); + VersionHistory versionHistory = versionService.getVersionHistory(new NodeRef(storeRef, nodeId)); + if (versionHistory != null && versionHistory.getAllVersions() != null && versionHistory.getAllVersions().size() > 0) { + NodeRef ioNodeRef = new NodeRef(storeRef, nodeId); + BehaviourFilter behaviourFilter = (BehaviourFilter) applicationContext.getBean("policyBehaviourFilter"); - // versionLabel - props.put(CCConstants.CM_PROP_VERSIONABLELABEL, version.getVersionLabel()); + UserTransaction userTransaction = serviceRegistry.getTransactionService().getNonPropagatingUserTransaction(); - /* add permalink */ - String v = version.getVersionLabel(); - String permaLink = URLTool.getBaseUrl() + "/node/" + nodeId; - permaLink = (v != null) ? permaLink + "/" + v : permaLink; - props.put(CCConstants.VIRT_PROP_PERMALINK, permaLink); + try { - result.put(version.getFrozenStateNodeRef().getId(), props); - } - } - return result; - } + userTransaction.begin(); - public void revertVersion(String nodeId, String verLbl) throws Exception { - VersionService versionService = serviceRegistry.getVersionService(); - VersionHistory versionHistory = versionService.getVersionHistory(new NodeRef(storeRef, nodeId)); - if (versionHistory != null && versionHistory.getAllVersions() != null && versionHistory.getAllVersions().size() > 0) { - NodeRef ioNodeRef = new NodeRef(storeRef, nodeId); - BehaviourFilter behaviourFilter = (BehaviourFilter) applicationContext.getBean("policyBehaviourFilter"); + try { - UserTransaction userTransaction = serviceRegistry.getTransactionService().getNonPropagatingUserTransaction(); + behaviourFilter.disableBehaviour(ioNodeRef, QName.createQName(CCConstants.CCM_TYPE_IO)); + Version version = versionHistory.getVersion(verLbl); + versionService.revert(ioNodeRef, version, true); - try { - - userTransaction.begin(); - - try { + } finally { + behaviourFilter.enableBehaviour(ioNodeRef, QName.createQName(CCConstants.CCM_TYPE_IO)); + } - behaviourFilter.disableBehaviour(ioNodeRef, QName.createQName(CCConstants.CCM_TYPE_IO)); - Version version = versionHistory.getVersion(verLbl); - versionService.revert(ioNodeRef, version, true); + userTransaction.commit(); - } finally { - behaviourFilter.enableBehaviour(ioNodeRef, QName.createQName(CCConstants.CCM_TYPE_IO)); - } - - userTransaction.commit(); - - } catch (Throwable e) { - - logger.error(e.getMessage()+" rolling back",e); - userTransaction.rollback(); - throw new Exception("revert version failed cause of" + e.getMessage()); } + } catch (Throwable e) { - } - } + log.error(e.getMessage() + " rolling back", e); + userTransaction.rollback(); + throw new Exception("revert version failed cause of" + e.getMessage()); + } - public boolean isAdmin(String username) throws Exception { - try { - Set testUsetAuthorities = serviceRegistry.getAuthorityService().getAuthoritiesForUser(username); - for (String testAuth : testUsetAuthorities) { + } + } - if (testAuth.equals("GROUP_ALFRESCO_ADMINISTRATORS")) { - return true; - } - } - } catch (org.alfresco.repo.security.permissions.AccessDeniedException e) { - logger.debug(username + " is no admin!!!"); - } - return false; - } + public boolean isAdmin(String username) throws Exception { + try { + Set testUsetAuthorities = serviceRegistry.getAuthorityService().getAuthoritiesForUser(username); + for (String testAuth : testUsetAuthorities) { - /** - * take the current runAs alfresco user and check if it is an admin normally - * runas = the fully authenticated user only when - * AuthenticationUtil.RunAsWork it differs - * - * @return - * @throws Exception - */ - public boolean isAdmin() throws Exception { - - String username = AuthenticationUtil.getRunAsUser(); - return isAdmin(username); - } + if (testAuth.equals("GROUP_ALFRESCO_ADMINISTRATORS")) { + return true; + } + } + } catch (org.alfresco.repo.security.permissions.AccessDeniedException e) { + log.debug(username + " is no admin!!!"); + } + return false; + } - public String getAlfrescoContentUrl(String nodeId) throws Exception { - return URLTool.getBrowserURL(new NodeRef(storeRef, nodeId)); - } + /** + * take the current runAs alfresco user and check if it is an admin normally + * runas = the fully authenticated user only when + * AuthenticationUtil.RunAsWork it differs + * + * @return + * @throws Exception + */ + public boolean isAdmin() throws Exception { + + String username = AuthenticationUtil.getRunAsUser(); + return isAdmin(username); + } - public void setPreviewUrlWithoutTicket(StoreRef storeRef, String nodeId, HashMap properties) { - try { - properties.put(CCConstants.CM_ASSOC_THUMBNAILS, NodeServiceHelper.getPreview(new NodeRef(storeRef,nodeId)).getUrl()); - // @todo 5.1: Check if this is needed in the client + public String getAlfrescoContentUrl(String nodeId) throws Exception { + return URLTool.getBrowserURL(new NodeRef(storeRef, nodeId)); + } + + public void setPreviewUrlWithoutTicket(StoreRef storeRef, String nodeId, Map properties) { + try { + properties.put(CCConstants.CM_ASSOC_THUMBNAILS, NodeServiceHelper.getPreview(new NodeRef(storeRef, nodeId)).getUrl()); + // @todo 5.1: Check if this is needed in the client /* GetPreviewResult prevResult = getPreviewUrl(storeRef, nodeId); @@ -3770,369 +3686,361 @@ public void setPreviewUrlWithoutTicket(StoreRef storeRef, String nodeId, HashMap properties.remove(CCConstants.KEY_PREVIEW_GENERATION_RUNS); } */ - } catch (Exception e) { - logger.error(e.getMessage(), e); - } - } + } catch (Exception e) { + log.error(e.getMessage(), e); + } + } - public String checkSystemFolderAndReturn(String foldername) throws Exception { - String systemFolderRootId = getCompanyHomeNodeId(); - - HashMap systemFolderProps = getChild(systemFolderRootId, CCConstants.CM_TYPE_FOLDER, CCConstants.CM_NAME, foldername); - if (systemFolderProps == null || systemFolderProps.size() == 0) { - HashMap newSystemFolderProps = new HashMap(); - newSystemFolderProps.put(CCConstants.CM_NAME, foldername); - newSystemFolderProps.put(CCConstants.CM_PROP_C_TITLE, foldername); - String newRemoteFolderId = createNode(systemFolderRootId, CCConstants.CM_TYPE_FOLDER, newSystemFolderProps); - return newRemoteFolderId; - } else { - return (String) systemFolderProps.get(CCConstants.SYS_PROP_NODE_UID); - } - } + public String checkSystemFolderAndReturn(String foldername) throws Exception { + String systemFolderRootId = getCompanyHomeNodeId(); + + Map systemFolderProps = getChild(systemFolderRootId, CCConstants.CM_TYPE_FOLDER, CCConstants.CM_NAME, foldername); + if (systemFolderProps == null || systemFolderProps.size() == 0) { + Map newSystemFolderProps = new HashMap<>(); + newSystemFolderProps.put(CCConstants.CM_NAME, foldername); + newSystemFolderProps.put(CCConstants.CM_PROP_C_TITLE, foldername); + String newRemoteFolderId = createNode(systemFolderRootId, CCConstants.CM_TYPE_FOLDER, newSystemFolderProps); + return newRemoteFolderId; + } else { + return (String) systemFolderProps.get(CCConstants.SYS_PROP_NODE_UID); + } + } - public String getCompanyHomeNodeId() { - return repositoryHelper.getCompanyHome().getId(); - } + public String getCompanyHomeNodeId() { + return repositoryHelper.getCompanyHome().getId(); + } - public void endSession(String user, String ticket) { - serviceRegistry.getAuthenticationService().invalidateTicket(ticket); - } + public void endSession(String user, String ticket) { + serviceRegistry.getAuthenticationService().invalidateTicket(ticket); + } - public void endSession() { - serviceRegistry.getAuthenticationService().invalidateTicket(this.authenticationInfo.get(CCConstants.AUTH_TICKET)); - serviceRegistry.getAuthenticationService().clearCurrentSecurityContext(); - } + public void endSession() { + serviceRegistry.getAuthenticationService().invalidateTicket(this.authenticationInfo.get(CCConstants.AUTH_TICKET)); + serviceRegistry.getAuthenticationService().clearCurrentSecurityContext(); + } - @Override - public boolean isSubOf(String type, String parentType) throws Throwable { - boolean isSubOf = serviceRegistry.getDictionaryService().isSubClass(QName.createQName(type), QName.createQName(parentType)); - return isSubOf; - } + @Override + public boolean isSubOf(String type, String parentType) throws Throwable { + boolean isSubOf = serviceRegistry.getDictionaryService().isSubClass(QName.createQName(type), QName.createQName(parentType)); + return isSubOf; + } - public String getType(String nodeId) { - return nodeService.getType(new NodeRef(storeRef, nodeId)).toString(); - } + public String getType(String nodeId) { + return nodeService.getType(new NodeRef(storeRef, nodeId)).toString(); + } - private NodeRef getAuthority(String name) { - SearchParameters sp = new SearchParameters(); - - sp.addStore(storeRef); - sp.setLanguage("lucene"); - sp.setQuery("+TYPE:\"" - + ContentModel.TYPE_AUTHORITY_CONTAINER - + "\"" - + " +@" - + QueryParser.escape("{" + ContentModel.PROP_AUTHORITY_NAME.getNamespaceURI() + "}" - + ISO9075.encode(ContentModel.PROP_AUTHORITY_NAME.getLocalName())) + ":\"" + name + "\""); - ResultSet rs = null; - try { - rs = searchService.query(sp); - if (rs.length() == 0) { - return null; - } else { - for (ResultSetRow row : rs) { - String test = DefaultTypeConverter.INSTANCE.convert(String.class, - nodeService.getProperty(row.getNodeRef(), ContentModel.PROP_AUTHORITY_NAME)); - if (test.equals(name)) { - return row.getNodeRef(); - } - } - } - return null; - } finally { - if (rs != null) { - rs.close(); - } - } - } + private NodeRef getAuthority(String name) { + SearchParameters sp = new SearchParameters(); + + sp.addStore(storeRef); + sp.setLanguage("lucene"); + sp.setQuery("+TYPE:\"" + + ContentModel.TYPE_AUTHORITY_CONTAINER + + "\"" + + " +@" + + QueryParser.escape("{" + ContentModel.PROP_AUTHORITY_NAME.getNamespaceURI() + "}" + + ISO9075.encode(ContentModel.PROP_AUTHORITY_NAME.getLocalName())) + ":\"" + name + "\""); + ResultSet rs = null; + try { + rs = searchService.query(sp); + if (rs.length() == 0) { + return null; + } else { + for (ResultSetRow row : rs) { + String test = DefaultTypeConverter.INSTANCE.convert(String.class, + nodeService.getProperty(row.getNodeRef(), ContentModel.PROP_AUTHORITY_NAME)); + if (test.equals(name)) { + return row.getNodeRef(); + } + } + } + return null; + } finally { + if (rs != null) { + rs.close(); + } + } + } - private String getAuthorityName(String groupNodeId) { - return DefaultTypeConverter.INSTANCE.convert(String.class, - nodeService.getProperty(new NodeRef(storeRef, groupNodeId), ContentModel.PROP_AUTHORITY_NAME)); - } + private String getAuthorityName(String groupNodeId) { + return DefaultTypeConverter.INSTANCE.convert(String.class, + nodeService.getProperty(new NodeRef(storeRef, groupNodeId), ContentModel.PROP_AUTHORITY_NAME)); + } - private void buildUpProperties(HashMap properties) { + private void buildUpProperties(Map properties) { + + // Creators + String creator = (String) properties.get(CCConstants.CM_PROP_C_CREATOR); + if (creator != null) { + User creatorUser = userCache.getUser(creator); + if (creatorUser != null) { + properties.put(CCConstants.NODECREATOR_FIRSTNAME, creatorUser.getGivenName()); + properties.put(CCConstants.NODECREATOR_LASTNAME, creatorUser.getSurname()); + properties.put(CCConstants.NODECREATOR_EMAIL, creatorUser.getEmail()); + } else { + properties.put(CCConstants.NODECREATOR_FIRSTNAME, "unknown"); + properties.put(CCConstants.NODECREATOR_LASTNAME, "unknown"); + properties.put(CCConstants.NODECREATOR_EMAIL, "unknown"); + } + } - // Creators - String creator = (String) properties.get(CCConstants.CM_PROP_C_CREATOR); - if (creator != null) { - User creatorUser = userCache.getUser(creator); - if (creatorUser != null) { - properties.put(CCConstants.NODECREATOR_FIRSTNAME, creatorUser.getGivenName()); - properties.put(CCConstants.NODECREATOR_LASTNAME, creatorUser.getSurname()); - properties.put(CCConstants.NODECREATOR_EMAIL, creatorUser.getEmail()); - } else { - properties.put(CCConstants.NODECREATOR_FIRSTNAME, "unknown"); - properties.put(CCConstants.NODECREATOR_LASTNAME, "unknown"); - properties.put(CCConstants.NODECREATOR_EMAIL, "unknown"); - } - } + // Modfifier + String modifier = (String) properties.get(CCConstants.CM_PROP_C_MODIFIER); + if (modifier != null) { + User modifierUser = userCache.getUser(modifier); + + if (modifierUser != null) { + properties.put(CCConstants.NODEMODIFIER_FIRSTNAME, modifierUser.getGivenName()); + properties.put(CCConstants.NODEMODIFIER_LASTNAME, modifierUser.getSurname()); + properties.put(CCConstants.NODEMODIFIER_EMAIL, modifierUser.getEmail()); + } else { + properties.put(CCConstants.NODEMODIFIER_FIRSTNAME, "unknown"); + properties.put(CCConstants.NODEMODIFIER_LASTNAME, "unknown"); + properties.put(CCConstants.NODEMODIFIER_EMAIL, "unknown"); + } + } - // Modfifier - String modifier = (String) properties.get(CCConstants.CM_PROP_C_MODIFIER); - if (modifier != null) { - User modifierUser = userCache.getUser(modifier); + } - if (modifierUser != null) { - properties.put(CCConstants.NODEMODIFIER_FIRSTNAME, modifierUser.getGivenName()); - properties.put(CCConstants.NODEMODIFIER_LASTNAME, modifierUser.getSurname()); - properties.put(CCConstants.NODEMODIFIER_EMAIL, modifierUser.getEmail()); - } else { - properties.put(CCConstants.NODEMODIFIER_FIRSTNAME, "unknown"); - properties.put(CCConstants.NODEMODIFIER_LASTNAME, "unknown"); - properties.put(CCConstants.NODEMODIFIER_EMAIL, "unknown"); - } - } + public String getDetailsHtmlSnippet(String nodeId) throws Exception { + throw new Exception("notImplementedYet"); + } - } + public void setLocale(String localeStr) { + Locale locale = I18NUtil.parseLocale(localeStr); + I18NUtil.setLocale(locale); + } - public String getDetailsHtmlSnippet(String nodeId) throws Exception { - throw new Exception("notImplementedYet"); - } + @Override + public String getNodeType(String nodeId) { + return this.nodeService.getType(new NodeRef(storeRef, nodeId)).toString(); + } - public void setLocale(String localeStr) { - Locale locale = I18NUtil.parseLocale(localeStr); - I18NUtil.setLocale(locale); - } + public GetPreviewResult getPreviewUrl(StoreRef storeRef, String nodeId) { + return getPreviewUrl(storeRef.getProtocol(), storeRef.getIdentifier(), nodeId); + } - @Override - public String getNodeType(String nodeId) { - return this.nodeService.getType(new NodeRef(storeRef, nodeId)).toString(); - } + public String getUrl() { + ApplicationInfo homeRep = ApplicationInfoList.getHomeRepository(); - public GetPreviewResult getPreviewUrl(StoreRef storeRef, String nodeId) { - return getPreviewUrl(storeRef.getProtocol(), storeRef.getIdentifier(), nodeId); - } - - public String getUrl(){ - ApplicationInfo homeRep = ApplicationInfoList.getHomeRepository(); + String server = homeRep.getDomain(); + server = (server == null) ? homeRep.getHost() : server; + return homeRep.getClientprotocol() + "://" + server + ":" + homeRep.getClientport() + "/" + homeRep.getWebappname(); + } - String server = homeRep.getDomain(); - server = (server == null) ? homeRep.getHost() : server; - return homeRep.getClientprotocol() + "://" + server + ":" + homeRep.getClientport() + "/" + homeRep.getWebappname(); - } - - public GetPreviewResult getPreviewUrl(String storeProtocol, String storeIdentifier, String nodeId){ - return NodeServiceHelper.getPreview(new NodeRef(storeRef, nodeId)); - } + public GetPreviewResult getPreviewUrl(String storeProtocol, String storeIdentifier, String nodeId) { + return NodeServiceHelper.getPreview(new NodeRef(storeRef, nodeId)); + } - @Override - public boolean isOwner(String nodeId, String user) { + @Override + public boolean isOwner(String nodeId, String user) { - String owner = serviceRegistry.getOwnableService().getOwner(new NodeRef(MCAlfrescoAPIClient.storeRef, nodeId)); - if (owner.equals(user)) { - return true; - } else { - return false; - } - } + String owner = serviceRegistry.getOwnableService().getOwner(new NodeRef(MCAlfrescoAPIClient.storeRef, nodeId)); + if (owner.equals(user)) { + return true; + } else { + return false; + } + } - public String[] getMetadataSets() { - try { + public String[] getMetadataSets() { + try { - File mdsDir = new File(MCAlfrescoAPIClient.class.getClassLoader().getResource("org/edu_sharing/metadataset").toURI()); + File mdsDir = new File(MCAlfrescoAPIClient.class.getClassLoader().getResource("org/edu_sharing/metadataset").toURI()); - final FilenameFilter filter = new FilenameFilter() { + final FilenameFilter filter = new FilenameFilter() { - public boolean accept(final File dir, final String name) { + public boolean accept(final File dir, final String name) { - if (name.matches("metadataset_[a-zA-Z]*.xml")) { - return true; - } else { - return false; - } - } - }; - String[] filesFound = mdsDir.list(filter); - - List mdsNames = new ArrayList(); - for (String mdsFile : filesFound) { - String name = mdsFile.replace("metadataset_", ""); - name = mdsFile.replace(".xml", ""); - mdsNames.add(name); - } + if (name.matches("metadataset_[a-zA-Z]*.xml")) { + return true; + } else { + return false; + } + } + }; + String[] filesFound = mdsDir.list(filter); + + List mdsNames = new ArrayList<>(); + for (String mdsFile : filesFound) { + String name = mdsFile.replace("metadataset_", ""); + name = mdsFile.replace(".xml", ""); + mdsNames.add(name); + } - return mdsNames.toArray(new String[mdsNames.size()]); - } catch (URISyntaxException e) { - logger.error(e.getMessage(), e); - } + return mdsNames.toArray(new String[mdsNames.size()]); + } catch (URISyntaxException e) { + log.error(e.getMessage(), e); + } - return null; + return null; - } + } - @Override - public void setOwner(String nodeId, String username) { - serviceRegistry.getOwnableService().setOwner(new NodeRef(storeRef, nodeId), username); - } + @Override + public void setOwner(String nodeId, String username) { + serviceRegistry.getOwnableService().setOwner(new NodeRef(storeRef, nodeId), username); + } - @Override - public String guessMimetype(String filename) { - return serviceRegistry.getMimetypeService().guessMimetype(filename); - } + @Override + public String guessMimetype(String filename) { + return serviceRegistry.getMimetypeService().guessMimetype(filename); + } - public boolean exists(String nodeId) { - return nodeService.exists(new NodeRef(storeRef, nodeId)); - } + public boolean exists(String nodeId) { + return nodeService.exists(new NodeRef(storeRef, nodeId)); + } - /** - * returns hash of content, if node has no content -1 - * - * @param nodeId - * @param property - * @return - */ - public int getContentHash(String nodeId, String property) { - return getContentHash(nodeId, property, storeRef.getProtocol(),storeRef.getIdentifier()); - } - - public int getContentHash(String nodeId, String property, String storeProtocol,String storeIdentifier) { - ContentReader reader = this.contentService.getReader(new NodeRef(new StoreRef(storeProtocol,storeIdentifier), nodeId), QName.createQName(property)); - if (reader == null) { - return -1; - } else { - return reader.getContentData().hashCode(); - } - } + /** + * returns hash of content, if node has no content -1 + * + * @param nodeId + * @param property + * @return + */ + public int getContentHash(String nodeId, String property) { + return getContentHash(nodeId, property, storeRef.getProtocol(), storeRef.getIdentifier()); + } - - public String[] getAspects(String nodeId){ - return getAspects(new NodeRef(storeRef,nodeId)); - } - - public String[] getAspects(String storeProtocol, String storeId, String nodeId){ - return getAspects(new NodeRef(new StoreRef(storeProtocol,storeId),nodeId)); - } - - public String[] getAspects(NodeRef nodeRef){ - Set set = nodeService.getAspects(nodeRef); - ArrayList result = new ArrayList(); - for(QName qname : set){ - result.add(qname.toString()); - } - return result.toArray(new String[result.size()]); - } - - public String findNodeByPath(String path) { - - return serviceRegistry.getTransactionService().getRetryingTransactionHelper().doInTransaction( - - new RetryingTransactionCallback() - { - public String execute() throws Throwable - { - List paths = null; - if (path == null || path.length() == 0) - { - paths = Collections.emptyList(); - - } else { - - paths = new ArrayList(); - - StringTokenizer token = new StringTokenizer(path, "/"); - while (token.hasMoreTokens()) - { - String s = token.nextToken().replaceAll("\\{[^}]*\\}", ""); - - String[] t = s.split(":"); - if (t.length == 2) { - s = t[1]; - } - - paths.add(s); - } - } - - NodeRef companyHome = repositoryHelper.getCompanyHome(); - - if (0 < paths.size() && "company_home".equals(paths.get(0))) { - - paths.remove(0); - } - - return serviceRegistry.getFileFolderService(). - resolveNamePath(companyHome, paths, true).getNodeRef().getId(); - } - }, true); - - } - - public void bindEduGroupFolder(String groupName, String folderId) throws Exception { + public int getContentHash(String nodeId, String property, String storeProtocol, String storeIdentifier) { + ContentReader reader = this.contentService.getReader(new NodeRef(new StoreRef(storeProtocol, storeIdentifier), nodeId), QName.createQName(property)); + if (reader == null) { + return -1; + } else { + return reader.getContentData().hashCode(); + } + } - try{ - serviceRegistry.getTransactionService().getRetryingTransactionHelper().doInTransaction( - - new RetryingTransactionCallback() - { - public Void execute() throws Throwable - { - if (isAdmin()) { - - eduOrganisationService.bindEduGroupFolder(groupName,new NodeRef(storeRef,folderId)); - }else{ - throw new Exception("No Permissions to bind edugroup"); - } - - return null; + + public String[] getAspects(String nodeId) { + return getAspects(new NodeRef(storeRef, nodeId)); + } + + public String[] getAspects(String storeProtocol, String storeId, String nodeId) { + return getAspects(new NodeRef(new StoreRef(storeProtocol, storeId), nodeId)); + } + + public String[] getAspects(NodeRef nodeRef) { + Set set = nodeService.getAspects(nodeRef); + ArrayList result = new ArrayList<>(); + for (QName qname : set) { + result.add(qname.toString()); + } + return result.toArray(new String[result.size()]); + } + + public String findNodeByPath(String path) { + + return serviceRegistry.getTransactionService().getRetryingTransactionHelper().doInTransaction( + + new RetryingTransactionCallback() { + public String execute() throws Throwable { + List paths = null; + if (path == null || path.length() == 0) { + paths = Collections.emptyList(); + + } else { + + paths = new ArrayList<>(); + + StringTokenizer token = new StringTokenizer(path, "/"); + while (token.hasMoreTokens()) { + String s = token.nextToken().replaceAll("\\{[^}]*\\}", ""); + + String[] t = s.split(":"); + if (t.length == 2) { + s = t[1]; + } + + paths.add(s); + } + } + + NodeRef companyHome = repositoryHelper.getCompanyHome(); + + if (0 < paths.size() && "company_home".equals(paths.get(0))) { + + paths.remove(0); + } + + return serviceRegistry.getFileFolderService(). + resolveNamePath(companyHome, paths, true).getNodeRef().getId(); } - }, false); + }, true); - }catch(AlfrescoRuntimeException e){ - throw (Exception)e.getCause(); - } - } - - public void unbindEduGroupFolder(String groupName, String folderId) throws Exception { + } - serviceRegistry.getTransactionService().getRetryingTransactionHelper().doInTransaction( - - new RetryingTransactionCallback() - { - public Void execute() throws Throwable - { - if (isAdmin()) { - - AuthorityService authorityService = serviceRegistry.getAuthorityService(); - NodeRef authorityNodeRef = authorityService.getAuthorityNodeRef(PermissionService.GROUP_PREFIX + groupName); - - if (authorityNodeRef == null) { - return null; - } - - NodeService nodeService = serviceRegistry.getNodeService(); - NodeRef folderNodeRef = new NodeRef(storeRef, folderId); - - if (! nodeService.exists(folderNodeRef)) { - return null; - } - - EduGroupTool.processEduGroupMicroCommand("COMMAND REMOVE " + authorityNodeRef.toString() + " " + folderNodeRef.toString() ); - } - - return null; + public void bindEduGroupFolder(String groupName, String folderId) throws Exception { + + try { + serviceRegistry.getTransactionService().getRetryingTransactionHelper().doInTransaction( + + new RetryingTransactionCallback() { + public Void execute() throws Throwable { + if (isAdmin()) { + + eduOrganisationService.bindEduGroupFolder(groupName, new NodeRef(storeRef, folderId)); + } else { + throw new Exception("No Permissions to bind edugroup"); + } + + return null; + } + }, false); + + } catch (AlfrescoRuntimeException e) { + throw (Exception) e.getCause(); + } + } + + public void unbindEduGroupFolder(String groupName, String folderId) throws Exception { + + serviceRegistry.getTransactionService().getRetryingTransactionHelper().doInTransaction( + + new RetryingTransactionCallback() { + public Void execute() throws Throwable { + if (isAdmin()) { + + AuthorityService authorityService = serviceRegistry.getAuthorityService(); + NodeRef authorityNodeRef = authorityService.getAuthorityNodeRef(PermissionService.GROUP_PREFIX + groupName); + + if (authorityNodeRef == null) { + return null; + } + + NodeService nodeService = serviceRegistry.getNodeService(); + NodeRef folderNodeRef = new NodeRef(storeRef, folderId); + + if (!nodeService.exists(folderNodeRef)) { + return null; + } + + EduGroupTool.processEduGroupMicroCommand("COMMAND REMOVE " + authorityNodeRef.toString() + " " + folderNodeRef.toString()); + } + + return null; } - }, false); + }, false); - } - - public InputStream getContent(String nodeId){ - return getContent(nodeId, CCConstants.CM_PROP_CONTENT); - } - - public InputStream getContent(String nodeId, String contentProp){ - ContentReader reader = serviceRegistry.getContentService().getReader(new NodeRef(storeRef,nodeId), QName.createQName(contentProp)); - if(reader != null) return reader.getContentInputStream(); - else return null; - } - - /** - * https://community.alfresco.com/thread/176342-read-document-content-doc-docx-odt - * @param nodeId - * @param mimetype e.g. MimetypeMap.MIMETYPE_TEXT_PLAIN - * @return - */ - public String getNodeTextContent(String nodeId,String mimetype) { + } + + public InputStream getContent(String nodeId) { + return getContent(nodeId, CCConstants.CM_PROP_CONTENT); + } + + public InputStream getContent(String nodeId, String contentProp) { + ContentReader reader = serviceRegistry.getContentService().getReader(new NodeRef(storeRef, nodeId), QName.createQName(contentProp)); + if (reader != null) return reader.getContentInputStream(); + else return null; + } + + /** + * https://community.alfresco.com/thread/176342-read-document-content-doc-docx-odt + * @param nodeId + * @param mimetype e.g. MimetypeMap.MIMETYPE_TEXT_PLAIN + * @return + */ + public String getNodeTextContent(String nodeId, String mimetype) { /* @TODO fix alf 7.0 ContentReader reader = contentService.getReader(new NodeRef(storeRef,nodeId), QName.createQName(CCConstants.CM_PROP_CONTENT)); @@ -4140,7 +4048,7 @@ public String getNodeTextContent(String nodeId,String mimetype) { { // get the transformer org.alfresco.repo.content.transform.ContentTransformer transformer = contentService.getTransformer(reader.getMimetype(), MimetypeMap.MIMETYPE_TEXT_PLAIN); - + // is this transformer good enough? if (transformer != null) { @@ -4172,31 +4080,26 @@ public String getNodeTextContent(String nodeId,String mimetype) { throw new ContentIOException("No reader found"); */ - return null; - } + return null; + } - public NodeRef findFolderNodeRef(StoreRef storeRef, String folderXPath) - { + public NodeRef findFolderNodeRef(StoreRef storeRef, String folderXPath) { NodeRef storeRootNodeRef = nodeService.getRootNode(storeRef); - + List nodeRefs = searchService.selectNodes(storeRootNodeRef, folderXPath, null, namespaceService, false); - + NodeRef folderNodeRef = null; - if (nodeRefs.size() != 1) - { + if (nodeRefs.size() != 1) { throw new AlfrescoRuntimeException("Cannot find folder location: " + folderXPath); - } - else - { + } else { folderNodeRef = nodeRefs.get(0); } return folderNodeRef; } - - public NodeRef getUserHomesNodeRef(StoreRef storeRef) - { - // get the "User Homes" location - return findFolderNodeRef(storeRef, "/app:company_home/app:user_homes"); - } - + + public NodeRef getUserHomesNodeRef(StoreRef storeRef) { + // get the "User Homes" location + return findFolderNodeRef(storeRef, "/app:company_home/app:user_homes"); + } + } diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/MCAlfrescoClient.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/MCAlfrescoClient.java index a4785c4547..08eba4545d 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/MCAlfrescoClient.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/MCAlfrescoClient.java @@ -29,13 +29,12 @@ import java.io.Serializable; import java.util.ArrayList; -import java.util.HashMap; import java.util.List; +import java.util.Map; import org.edu_sharing.repository.client.rpc.EduGroup; import org.edu_sharing.service.nodeservice.model.GetPreviewResult; import org.edu_sharing.repository.client.rpc.Group; -import org.edu_sharing.repository.client.rpc.Notify; import org.edu_sharing.repository.client.rpc.SearchResult; import org.edu_sharing.repository.client.rpc.Share; import org.edu_sharing.repository.client.rpc.User; @@ -56,29 +55,29 @@ enum ContextSearchMode{ /** * get all favorite folders for the current user * - * @return nested HashMap withe the nodeIds of the favorite folders and the corresponding propetries (as HashMap) + * @return nested Map withe the nodeIds of the favorite folders and the corresponding propetries (as Map) * @throws Throwable */ - public HashMap getBaskets() throws Throwable; + public Map> getBaskets() throws Throwable; /** * search for nodes with a lucene string, filtered by type * * @param luceneString a lucene String * @param type the given type - * @return nested HashMap with nodeId's and nodes + * @return nested Map with nodeId's and nodes * @throws Exception */ - public HashMap> search(String luceneString, String type) throws Exception; + public Map> search(String luceneString, String type) throws Exception; /** * search for nodes with a lucene string * * @param luceneString a lucene String - * @return nested HashMap with nodeId's and propeties + * @return nested Map with nodeId's and propeties * @throws Throwable */ - public HashMap> search(String luceneString) throws Throwable; + public Map> search(String luceneString) throws Throwable; /** * @@ -89,7 +88,7 @@ enum ContextSearchMode{ * @return * @throws Throwable */ - public HashMap> search(String luceneString, ContextSearchMode mode) throws Throwable; + public Map> search(String luceneString, ContextSearchMode mode) throws Throwable; /** * search for nodeId's with a lucene string @@ -106,20 +105,20 @@ enum ContextSearchMode{ * get all children of a given parentId * * @param parentID - * @return nested HashMap with nodeIds and the corresponding properties HashMap> + * @return nested Map with nodeIds and the corresponding properties Map> * @throws Throwable */ - public HashMap> getChildren(String parentID) throws Throwable; + public Map> getChildren(String parentID) throws Throwable; /** * get all children with a given association * * @param nodeId node Id of the parent object * @param association the matching association - * @return nested HashMap with nodeIds and the corresponding properties + * @return nested Map with nodeIds and the corresponding properties * @throws Exception */ - public HashMap> getChildrenByAssociation(String nodeId, String association) throws Exception; + public Map> getChildrenByAssociation(String nodeId, String association) throws Exception; /** * get all children with a given association in a given alfresco store @@ -127,10 +126,10 @@ enum ContextSearchMode{ * @param store the store * @param nodeId node Id of the parent object * @param association the matching association - * @return nested HashMap with nodeIds and the corresponding properties + * @return nested Map with nodeIds and the corresponding properties * @throws Exception */ - public HashMap> getChildrenByAssociation(String store, String nodeId, String association) throws Exception; + public Map> getChildrenByAssociation(String store, String nodeId, String association) throws Exception; /** @@ -186,7 +185,7 @@ enum ContextSearchMode{ * @return * @throws Throwable */ - public HashMap getGroupFolders() throws Throwable; + public Map> getGroupFolders() throws Throwable; /** * get all parents of a given nodeId @@ -196,7 +195,7 @@ enum ContextSearchMode{ * @return * @throws Throwable */ - public HashMap getParents(String nodeID, boolean primary) throws Throwable; + public Map> getParents(String nodeID, boolean primary) throws Throwable; @@ -233,7 +232,7 @@ enum ContextSearchMode{ * * @throws Exception */ - public HashMap hasAllPermissions(String nodeId, String authority, String[] permissions) throws Exception; + public Map hasAllPermissions(String nodeId, String authority, String[] permissions) throws Exception; /** * @@ -244,7 +243,7 @@ enum ContextSearchMode{ * @return Map with the permissions and the value true/false weather the permission is set or not * @throws Exception */ - public HashMap hasAllPermissions(String nodeId, String[] permissions) throws Exception; + public Map hasAllPermissions(String nodeId, String[] permissions) throws Exception; /** @@ -272,17 +271,17 @@ enum ContextSearchMode{ * @return * @throws Exception */ - public String dropToBasketRemoteNode(String basketId, HashMap params) throws Exception; + public String dropToBasketRemoteNode(String basketId, Map params) throws Exception; /** * get all associated nodes * * @param nodeID the nodeId of the source node * @param association the association type - * @return nested HashMap with nodeIds and properties + * @return nested Map with nodeIds and properties * @throws Throwable */ - public HashMap getAssocNode(String nodeID, String association) throws Throwable; + public Map> getAssocNode(String nodeID, String association) throws Throwable; /** * remove relations for the current folder @@ -339,18 +338,18 @@ enum ContextSearchMode{ * @return the person properties * @throws Exception */ - public HashMap checkAndCreateShadowUser(String username, String email, String repId) throws Exception; + public Map checkAndCreateShadowUser(String username, String email, String repId) throws Exception; /** * get the versionhistory of a node * * @param nodeId - * @return HashMap with id and properties. the id is the nodeId of the frozen state in the VersionStore + * @return Map with id and properties. the id is the nodeId of the frozen state in the VersionStore * * @throws Throwable */ - public HashMap> getVersionHistory(String nodeId) throws Throwable; + public Map> getVersionHistory(String nodeId) throws Throwable; /** * revert a node to its state of a specified version @@ -419,7 +418,7 @@ enum ContextSearchMode{ * @return * @throws Throwable */ - public abstract HashMap> getChilden(String parentId, String type, HashMap props) throws Throwable; + public abstract Map> getChilden(String parentId, String type, Map props) throws Throwable; /** * find a node that matches the given properties while navigatigating through all the children of the node with parentId @@ -430,7 +429,7 @@ enum ContextSearchMode{ * @return the child prop if found else null * @throws Throwable */ - public HashMap getChildRecursive(String parentId, String type, HashMap props)throws Throwable; + public Map getChildRecursive(String parentId, String type, Map props)throws Throwable; /** * fina all chidren taht match the given type and return i t in a flat Map structure @@ -439,7 +438,7 @@ enum ContextSearchMode{ * @return * @throws Throwable */ - public HashMap> getChildrenRecursive(String parentId, String type)throws Throwable; + public Map> getChildrenRecursive(String parentId, String type)throws Throwable; /** * find out if the given type is subtype of parentType @@ -457,7 +456,7 @@ enum ContextSearchMode{ * @return * @throws Exception */ - public HashMap getUserInfo(String userName) throws Exception; + public Map getUserInfo(String userName) throws Exception; @@ -496,7 +495,7 @@ enum ContextSearchMode{ * @param async * @throws Exception */ - public abstract void executeAction(String nodeId, String actionName, String actionId, HashMap parameters, boolean async) throws Exception; + public abstract void executeAction(String nodeId, String actionName, String actionId, Map parameters, boolean async) throws Exception; public String copyNode(String nodeId, String toNodeId, boolean copyChildren) throws Exception; @@ -516,7 +515,7 @@ enum ContextSearchMode{ public String guessMimetype(String filename); - public HashMap> getChildren(String parentID, String[] permissionsOnChild) throws Throwable; + public Map> getChildren(String parentID, String[] permissionsOnChild) throws Throwable; public void removeGlobalAspectFromGroup(String groupNodeId) throws Exception; @@ -527,12 +526,12 @@ enum ContextSearchMode{ public void removeNode(String storeProtocol, String storeId, String nodeId); - public HashMap getProperties(String storeId, String storeProtocol, String nodeId) throws Throwable; + public Map getProperties(String storeId, String storeProtocol, String nodeId) throws Throwable; - public HashMap hasAllPermissions(String storeProtocol, String storeId, String nodeId, String[] permissions); + public Map hasAllPermissions(String storeProtocol, String storeId, String nodeId, String[] permissions); public String[] getAspects(String storeProtocol, String storeId, String nodeId); - public void addAspect(String nodeId, String aspect); + public void addAspect(String nodeId, String aspect) throws Exception; } diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/MCAlfrescoClientAdapter.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/MCAlfrescoClientAdapter.java index 4465fb0421..5421b88dc3 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/MCAlfrescoClientAdapter.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/MCAlfrescoClientAdapter.java @@ -4,6 +4,7 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; +import java.util.Map; import org.edu_sharing.repository.client.rpc.ACL; import org.edu_sharing.repository.client.rpc.EduGroup; @@ -23,22 +24,22 @@ public ACL getPermissions(String nodeId) throws Exception { } @Override - public HashMap getBaskets() throws Throwable { + public Map> getBaskets() throws Throwable { return null; } @Override - public HashMap> search(String luceneString, String type) throws Exception { + public Map> search(String luceneString, String type) throws Exception { return null; } @Override - public HashMap> search(String luceneString) throws Throwable { + public Map> search(String luceneString) throws Throwable { return null; } @Override - public HashMap> search(String luceneString, ContextSearchMode mode) + public Map> search(String luceneString, ContextSearchMode mode) throws Throwable { return null; } @@ -54,18 +55,18 @@ public String[] searchNodeIds(String luceneString, int limit) throws Exception { } @Override - public HashMap> getChildren(String parentID) throws Throwable { + public Map> getChildren(String parentID) throws Throwable { return null; } @Override - public HashMap> getChildrenByAssociation(String nodeId, String association) + public Map> getChildrenByAssociation(String nodeId, String association) throws Exception { return null; } @Override - public HashMap> getChildrenByAssociation(String store, String nodeId, + public Map> getChildrenByAssociation(String store, String nodeId, String association) throws Exception { return null; } @@ -100,12 +101,12 @@ public String getGroupFolderId() throws Throwable { } @Override - public HashMap getGroupFolders() throws Throwable { + public Map> getGroupFolders() throws Throwable { return null; } @Override - public HashMap getParents(String nodeID, boolean primary) throws Throwable { + public Map> getParents(String nodeID, boolean primary) throws Throwable { return null; } @@ -114,13 +115,13 @@ public void removeChild(String parentID, String childID, String association) thr } @Override - public HashMap hasAllPermissions(String nodeId, String authority, String[] permissions) + public Map hasAllPermissions(String nodeId, String authority, String[] permissions) throws Exception { return null; } @Override - public HashMap hasAllPermissions(String nodeId, String[] permissions) throws Exception { + public Map hasAllPermissions(String nodeId, String[] permissions) throws Exception { return null; } @@ -130,12 +131,12 @@ public boolean hasPermissions(String nodeId, String authority, String[] permissi } @Override - public String dropToBasketRemoteNode(String basketId, HashMap params) throws Exception { + public String dropToBasketRemoteNode(String basketId, Map params) throws Exception { return null; } @Override - public HashMap getAssocNode(String nodeID, String association) throws Throwable { + public Map> getAssocNode(String nodeID, String association) throws Throwable { return null; } @@ -166,13 +167,13 @@ public Group getEduGroupContextOfNode(String nodeId) { } @Override - public HashMap checkAndCreateShadowUser(String username, String email, String repId) + public Map checkAndCreateShadowUser(String username, String email, String repId) throws Exception { return null; } @Override - public HashMap> getVersionHistory(String nodeId) throws Throwable { + public Map> getVersionHistory(String nodeId) throws Throwable { return null; } @@ -210,18 +211,18 @@ public String checkSystemFolderAndReturn(String foldername) throws Throwable { } @Override - public HashMap> getChilden(String parentId, String type, HashMap props) + public Map> getChilden(String parentId, String type, Map props) throws Throwable { return null; } @Override - public HashMap getChildRecursive(String parentId, String type, HashMap props) throws Throwable { + public Map getChildRecursive(String parentId, String type, Map props) throws Throwable { return null; } @Override - public HashMap> getChildrenRecursive(String parentId, String type) + public Map> getChildrenRecursive(String parentId, String type) throws Throwable { return null; } @@ -266,7 +267,7 @@ public GetPreviewResult getPreviewUrl(String storeProtocol, String storeIdentifi } @Override - public void executeAction(String nodeId, String actionName, String actionId, HashMap parameters, boolean async) + public void executeAction(String nodeId, String actionName, String actionId, Map parameters, boolean async) throws Exception { } @@ -313,7 +314,7 @@ public String guessMimetype(String filename) { } @Override - public HashMap> getChildren(String parentID, String[] permissionsOnChild) + public Map> getChildren(String parentID, String[] permissionsOnChild) throws Throwable { return null; } @@ -343,12 +344,12 @@ public void removeNode(String storeProtocol, String storeId, String nodeId) { } @Override - public HashMap getProperties(String storeId, String storeProtocol, String nodeId) throws Throwable { + public Map getProperties(String storeId, String storeProtocol, String nodeId) throws Throwable { return null; } @Override - public HashMap hasAllPermissions(String storeProtocol, String storeId, String nodeId, + public Map hasAllPermissions(String storeProtocol, String storeId, String nodeId, String[] permissions) { return null; } @@ -360,12 +361,12 @@ public String[] getAspects(String storeId, String storeProtocol, String nodeId) @Override public String createNode(String parentID, String nodeTypeString, String childAssociation, - HashMap _props) throws Exception { + Map _props) throws Exception { return null; } @Override - public String createNode(String parentID, String nodeTypeString, HashMap _props) throws Exception { + public String createNode(String parentID, String nodeTypeString, Map _props) throws Exception { return null; } @@ -374,7 +375,7 @@ public void addAspect(String nodeId, String aspect) { } @Override - public void updateNode(String nodeId, HashMap _props) throws Exception { + public void updateNode(String nodeId, Map _props) throws Exception { } @Override @@ -387,12 +388,12 @@ public void writeContent(String nodeID, byte[] content, String mimetype, String } @Override - public HashMap getProperties(String nodeId) throws Throwable { + public Map getProperties(String nodeId) throws Throwable { return null; } @Override - public HashMap getChild(String parentId, String type, String property, String value) + public Map getChild(String parentId, String type, String property, String value) throws Throwable { return null; } @@ -416,12 +417,12 @@ public void removeAssociation(String fromID, String toID, String association) th } @Override - public HashMap> getChildrenByType(String nodeId, String type) throws Exception { + public Map> getChildrenByType(String nodeId, String type) throws Exception { return null; } @Override - public HashMap getUserInfo(String userName) throws Exception { + public Map getUserInfo(String userName) throws Exception { return null; } @@ -445,12 +446,12 @@ public boolean hasPermissions(String nodeId, String[] permissions) throws Except } @Override - public MCBaseClient getInstance(HashMap _authenticationInfo) { + public MCBaseClient getInstance(Map _authenticationInfo) { return null; } @Override - public MCBaseClient getInstance(String _repositoryFile, HashMap _authenticationInfo) { + public MCBaseClient getInstance(String _repositoryFile, Map _authenticationInfo) { return null; } diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/MCBaseClient.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/MCBaseClient.java index 55cd86a17f..437bcd93de 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/MCBaseClient.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/MCBaseClient.java @@ -27,8 +27,8 @@ */ package org.edu_sharing.repository.server; -import java.util.HashMap; import java.util.List; +import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -43,12 +43,12 @@ public abstract class MCBaseClient { /** * username, ticket for the current repository */ - protected HashMap authenticationInfo = null; + protected Map authenticationInfo = null; /** * @return the authenticationInfo */ - public HashMap getAuthenticationInfo() { + public Map getAuthenticationInfo() { return authenticationInfo; } @@ -65,7 +65,7 @@ protected String getRedirectServletLink(String repId, String nodeId){ * @return * @throws Exception */ - public abstract String createNode(String parentID, String nodeTypeString, String childAssociation, HashMap _props) throws Exception; + public abstract String createNode(String parentID, String nodeTypeString, String childAssociation, Map _props) throws Exception; /** * Creates a node with the default ChildAssociation @@ -75,7 +75,7 @@ protected String getRedirectServletLink(String repId, String nodeId){ * @return * @throws Exception */ - public abstract String createNode( String parentID, String nodeTypeString, HashMap _props) throws Exception; + public abstract String createNode( String parentID, String nodeTypeString, Map _props) throws Exception; /** * Adds a aspect to a node @@ -94,7 +94,7 @@ protected String getRedirectServletLink(String repId, String nodeId){ * @param _props the properties of the node * @throws Exception */ - public abstract void updateNode(String nodeId, HashMap _props) throws Exception; + public abstract void updateNode(String nodeId, Map _props) throws Exception; /** * Creates an association between 2 nodes @@ -123,7 +123,7 @@ protected String getRedirectServletLink(String repId, String nodeId){ * @return * @throws Throwable */ - public abstract HashMap getProperties(String nodeId) throws Throwable; + public abstract Map getProperties(String nodeId) throws Throwable; /** * get the first child that matches the params @@ -135,7 +135,7 @@ protected String getRedirectServletLink(String repId, String nodeId){ * @return * @throws Throwable */ - public abstract HashMap getChild(String parentId, String type, String property, String value) throws Throwable; + public abstract Map getChild(String parentId, String type, String property, String value) throws Throwable; /** @@ -179,19 +179,19 @@ protected String getRedirectServletLink(String repId, String nodeId){ * * @param nodeId the node id * @param type the type of children - * @return a nested HashMap of nodeIds and the corresponding properties + * @return a nested Map of nodeIds and the corresponding properties * @throws Exception */ - public abstract HashMap> getChildrenByType( String nodeId, String type) throws Exception; + public abstract Map> getChildrenByType( String nodeId, String type) throws Exception; /** * get all properties of a person * * @param userName the username of the person - * @return property/value HashMap + * @return property/value Map * @throws Exception */ - public abstract HashMap getUserInfo(String userName) throws Exception; + public abstract Map getUserInfo(String userName) throws Exception; /** * remove a node from a given parent. if the node is the primary child it will be deleted. when its a secondary parent @@ -251,13 +251,13 @@ protected String getRedirectServletLink(String repId, String nodeId){ * http://stackoverflow.com/questions/435553/java-reflection-performance * * so we will do reflection constructor call only the first time for every Application. - * For every ApplicationFile we remember a Object of the configured MCBaseClient Subclass in HashMap in the + * For every ApplicationFile we remember a Object of the configured MCBaseClient Subclass in Map in the * Class org.edu_sharing.repository.server.RepoFactory. When we need a new Instance the getInstance Method of the Object will be called, * which calls the constructor directly. * @param _authenticationInfo * @return */ - public abstract MCBaseClient getInstance(HashMap _authenticationInfo); + public abstract MCBaseClient getInstance(Map _authenticationInfo); /** * Classes that extend MCBaseClient are instantiated dynamicaly by Reflections. * Reflections constructor calls are much slower than direct constructor calls @@ -266,11 +266,11 @@ protected String getRedirectServletLink(String repId, String nodeId){ * http://stackoverflow.com/questions/435553/java-reflection-performance * * so we will do reflection constructor call only the first time for every Application. - * For every ApplicationFile we remember a Object of the configured MCBaseClient Subclass in HashMap in the + * For every ApplicationFile we remember a Object of the configured MCBaseClient Subclass in Map in the * Class org.edu_sharing.repository.server.RepoFactory. When we need a new Instance the getInstance Method of the Object will be called, * which calls the constructor directly. * @param _authenticationInfo * @return */ - public abstract MCBaseClient getInstance(String _repositoryFile, HashMap _authenticationInfo); + public abstract MCBaseClient getInstance(String _repositoryFile, Map _authenticationInfo); } diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/NgServlet.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/NgServlet.java index 21f694cc54..6514e993ec 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/NgServlet.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/NgServlet.java @@ -30,6 +30,7 @@ import java.security.SecureRandom; import java.util.Base64; import java.util.HashMap; +import java.util.Map; public class NgServlet extends HttpServlet { public static final String COMPONENTS_RENDER = "components/render"; @@ -84,7 +85,7 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws Se private static String addSEO(String html, URL url) { try { NodeRefVersion node = getNodeFromURL(url); - HashMap props = NodeServiceHelper.getPropertiesVersion(node.getNodeRef(), node.getVersion()); + Map props = NodeServiceHelper.getPropertiesVersion(node.getNodeRef(), node.getVersion()); Document doc = Jsoup.parse(html); String title = (String) (props.get(CCConstants.LOM_PROP_GENERAL_TITLE)); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/PreviewServlet.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/PreviewServlet.java index 765f12abd1..0d6654abab 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/PreviewServlet.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/PreviewServlet.java @@ -131,7 +131,7 @@ private void fetchNodeData(HttpServletRequest req, HttpServletResponse resp) thr // check nodetype for security reasons String inNodeId=nodeId; - HashMap props = new HashMap<>(); + Map props; if (nodeId != null) { try { props = nodeService.getProperties(storeRef.getProtocol(),storeRef.getIdentifier(),nodeId); @@ -212,9 +212,9 @@ private void fetchNodeData(HttpServletRequest req, HttpServletResponse resp) thr PreviewDetail getPrevResult = null; // check if version is requested and version seems to be NOT the current node version if(version != null && !version.trim().equals("") && !isCollection && !version.equals(props.get(CCConstants.LOM_PROP_LIFECYCLE_VERSION))){ - HashMap> versionHistory = nodeService.getVersionHistory(nodeId); + Map> versionHistory = nodeService.getVersionHistory(nodeId); if(versionHistory != null){ - for(Map.Entry> entry : versionHistory.entrySet()){ + for(Map.Entry> entry : versionHistory.entrySet()){ String tmpVers = (String)entry.getValue().get(CCConstants.LOM_PROP_LIFECYCLE_VERSION); if(version.equals(tmpVers)){ @@ -273,7 +273,7 @@ public Boolean doWork() throws IOException { if (getPrevResult.getType().equals(PreviewDetail.TYPE_GENERATED)) { - HashMap previewProps = null; + Map previewProps = null; final String fnodeId = nodeId; if(isCollection) { prevNodeRef = AuthenticationUtil.runAsSystem( @@ -331,21 +331,18 @@ public Boolean doWork() throws IOException { * fallback to mime first, then default */ try{ - HashMap props; + Map props; String[] aspects=new String[]{}; String type=null; if(isCollection){ final String nodeIdFinal=nodeId; - props=AuthenticationUtil.runAsSystem(new RunAsWork>() { - @Override - public HashMap doWork() throws Exception { - try{ - return NodeServiceFactory.getLocalService().getProperties(storeRef.getProtocol(), storeRef.getIdentifier(),nodeIdFinal); - }catch(Throwable t){ - throw new Exception(t); - } - } - }); + props=AuthenticationUtil.runAsSystem(() -> { + try{ + return NodeServiceFactory.getLocalService().getProperties(storeRef.getProtocol(), storeRef.getIdentifier(),nodeIdFinal); + }catch(Throwable t){ + throw new Exception(t); + } + }); } else{ props=nodeService.getProperties(storeRef.getProtocol(), storeRef.getIdentifier(),nodeId); @@ -366,7 +363,7 @@ private void validatePermissions(StoreRef storeRef, String nodeId) { throw new AccessDeniedException("No "+CCConstants.PERMISSION_READ_PREVIEW+" on "+nodeId); } - private void validateScope(HttpServletRequest req, HashMap props) { + private void validateScope(HttpServletRequest req, Map props) { String scope=(String) req.getSession().getAttribute(CCConstants.AUTH_SCOPE); // Allow only valid scope if(props.containsKey(CCConstants.CCM_PROP_EDUSCOPE_NAME)){ @@ -703,7 +700,7 @@ private void deliverImage(String mimetype, DataInputStream in, HttpServletRespon public static PreviewDetail getPreview(NodeService nodeService,String storeProtocol, String storeIdentifier, String nodeId){ return getPreview(nodeService,storeProtocol,storeIdentifier,nodeId,null); } - public static PreviewDetail getPreview(NodeService nodeService,String storeProtocol, String storeIdentifier, String nodeId,HashMap nodeProps){ + public static PreviewDetail getPreview(NodeService nodeService,String storeProtocol, String storeIdentifier, String nodeId,Map nodeProps){ StoreRef storeRef = new StoreRef(storeProtocol,storeIdentifier); NodeRef nodeRef = new NodeRef(storeRef,nodeId); if(!nodeService.getType(nodeId).equals(CCConstants.CCM_TYPE_IO)){ diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/RedirectServlet.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/RedirectServlet.java index eb3f0bbac4..a45d0b8970 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/RedirectServlet.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/RedirectServlet.java @@ -176,7 +176,7 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws Se // contenturl if ((renderServiceUrl == null || renderServiceUrl.trim().equals(""))) { - HashMap authInfo = new HashMap(); + Map authInfo = new HashMap<>(); authInfo.put(CCConstants.AUTH_USERNAME, username); authInfo.put(CCConstants.AUTH_TICKET, ticket); try { @@ -187,9 +187,9 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws Se renderServiceUrl = mcAlfrescoBaseClient.getAlfrescoContentUrl(renderUrlNodeId); if(version != null && !version.trim().equals("")){ - HashMap> versHist = mcAlfrescoBaseClient.getVersionHistory(renderUrlNodeId); + Map> versHist = mcAlfrescoBaseClient.getVersionHistory(renderUrlNodeId); - for(Map.Entry> entry : versHist.entrySet()){ + for(Map.Entry> entry : versHist.entrySet()){ String currentVers = (String)entry.getValue().get(CCConstants.CM_PROP_VERSIONABLELABEL); @@ -232,7 +232,7 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws Se }else{ - HashMap props = NodeServiceFactory.getNodeService(appId).getProperties(StoreRef.PROTOCOL_WORKSPACE,StoreRef.STORE_REF_WORKSPACE_SPACESSTORE.getIdentifier(),nodeId); + Map props = NodeServiceFactory.getNodeService(appId).getProperties(StoreRef.PROTOCOL_WORKSPACE,StoreRef.STORE_REF_WORKSPACE_SPACESSTORE.getIdentifier(),nodeId); if(props != null){ String technicalLocation = (String)props.get(CCConstants.LOM_PROP_TECHNICAL_LOCATION); @@ -290,7 +290,7 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws Se private String setUrlParameters(String appId, String nodeId, ApplicationInfo repInfo, String redirectUrl) throws Throwable { NodeService nodeService = NodeServiceFactory.getNodeService(appId); - HashMap props = nodeService.getProperties(StoreRef.PROTOCOL_WORKSPACE,StoreRef.STORE_REF_WORKSPACE_SPACESSTORE.getIdentifier(),nodeId); + Map props = nodeService.getProperties(StoreRef.PROTOCOL_WORKSPACE,StoreRef.STORE_REF_WORKSPACE_SPACESSTORE.getIdentifier(),nodeId); if (props != null) { String title = (String) props.get(CCConstants.LOM_PROP_GENERAL_TITLE); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/RepoFactory.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/RepoFactory.java index f46f29d1a3..408edbe911 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/RepoFactory.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/RepoFactory.java @@ -27,10 +27,7 @@ */ package org.edu_sharing.repository.server; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Properties; +import java.util.*; import jakarta.servlet.http.HttpSession; @@ -64,9 +61,9 @@ public class RepoFactory { * time then use direct contructor calls with getInstance of the * MCBaseClient subclass */ - static HashMap appClassCache = new HashMap(); + static Map appClassCache = new HashMap<>(); - static HashMap appAuthToolCache = new HashMap(); + static Map appAuthToolCache = new HashMap<>(); private static Log logger = LogFactory.getLog(RepoFactory.class); @@ -95,7 +92,7 @@ public static MCBaseClient getInstance(String repositoryId, HttpSession session) AuthenticationTool authTool = RepoFactory.getAuthenticationToolInstance(repositoryId); //for remote repositories: the authinfo is created by this method if its missing - HashMap authInfo = authTool.validateAuthentication(session); + Map authInfo = authTool.validateAuthentication(session); ApplicationInfo repInfo = ApplicationInfoList.getRepositoryInfoById(repositoryId); if(authInfo != null){ @@ -119,7 +116,7 @@ public static MCBaseClient getInstance(String repositoryId, HttpSession session) * @return * @throws Throwable */ - public static MCBaseClient getInstance(String repositoryId, HashMap homeRepAuthInfo) throws Throwable { + public static MCBaseClient getInstance(String repositoryId, Map homeRepAuthInfo) throws Throwable { logger.debug("repositoryId:" + repositoryId); ApplicationInfo repInfo = null; @@ -128,7 +125,7 @@ public static MCBaseClient getInstance(String repositoryId, HashMap homeRepAuthI } else { repInfo = ApplicationInfoList.getRepositoryInfoById(repositoryId); } - HashMap remoteAuthInfo = null; + Map remoteAuthInfo = null; // authenticate when it's an remote Repository and an // AuthenticationWebservice is configured @@ -155,7 +152,7 @@ public static MCBaseClient getInstance(String repositoryId, HashMap homeRepAuthI * @return * @throws Throwable */ - public static MCBaseClient getInstanceForRepo(ApplicationInfo repInfo, HashMap authInfo) throws Throwable { + public static MCBaseClient getInstanceForRepo(ApplicationInfo repInfo, Map authInfo) throws Throwable { String repositoryId = repInfo.getAppId(); @@ -242,7 +239,7 @@ public static List getMetadataSetsForRepository(String reposito repositoryId = ApplicationInfoList.getHomeRepository().getAppId(); } ApplicationInfo appInfo = ApplicationInfoList.getRepositoryInfoById(repositoryId); - ArrayList sets = new ArrayList(); + ArrayList sets = new ArrayList<>(); for(String id : appInfo.getMetadatsets()){ MetadataSetInfo info=new MetadataSetInfo(); MetadataSet mds = MetadataHelper.getMetadataset(appInfo, id); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/authentication/AuthenticationFilter.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/authentication/AuthenticationFilter.java index 260b4b3ec0..5d64136f14 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/authentication/AuthenticationFilter.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/authentication/AuthenticationFilter.java @@ -23,6 +23,7 @@ import java.util.Arrays; import java.util.HashMap; import java.util.List; +import java.util.Map; public class AuthenticationFilter implements jakarta.servlet.Filter { @@ -270,7 +271,7 @@ private boolean authenticateByGuest(HttpServletRequest req) { } try{ AuthenticationTool authTool = RepoFactory.getAuthenticationToolInstance(null); - HashMap result = authTool.createNewSession(guestUn, guestPw); + Map result = authTool.createNewSession(guestUn, guestPw); //save ticket in session HttpSession session = req.getSession(); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/authentication/AuthenticationFilterPreview.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/authentication/AuthenticationFilterPreview.java index ef4c4b1f3d..b4bf7e234f 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/authentication/AuthenticationFilterPreview.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/authentication/AuthenticationFilterPreview.java @@ -201,7 +201,7 @@ else if (accessToken != null && !accessToken.trim().equals("")) { } else if (authHdr!=null && authHdr.length() > 5 && authHdr.substring(0, 5).equalsIgnoreCase("BASIC")) { try { - HashMap authResult = ApiAuthenticationFilter.httpBasicAuth(authHdr); + Map authResult = ApiAuthenticationFilter.httpBasicAuth(authHdr); if(authResult == null) { throw new Exception("Auth failed"); } @@ -223,7 +223,7 @@ else if (accessToken != null && !accessToken.trim().equals("")) { */ if(repoId != null && !ApplicationInfoList.getHomeRepository().getAppId().equals(repoId)){ - HashMap localAuthInfo = new HashMap(); + Map localAuthInfo = new HashMap<>(); localAuthInfo.put(CCConstants.AUTH_TICKET, ticket); localAuthInfo.put(CCConstants.AUTH_USERNAME, authService.getCurrentUserName()); try{ diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/authentication/CASFilter.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/authentication/CASFilter.java index b6feae6673..aa6a6890a8 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/authentication/CASFilter.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/authentication/CASFilter.java @@ -2,6 +2,7 @@ import java.io.IOException; import java.util.HashMap; +import java.util.Map; import jakarta.servlet.FilterChain; import jakarta.servlet.FilterConfig; @@ -41,7 +42,7 @@ public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) AuthenticationToolAPI authTool = new AuthenticationToolAPI(); - HashMap validAuthInfo = authTool.validateAuthentication(httpReq.getSession()); + Map validAuthInfo = authTool.validateAuthentication(httpReq.getSession()); if (validAuthInfo != null ) { if(validAuthInfo.get(CCConstants.AUTH_USERNAME).equals(remoteUser)){ @@ -68,7 +69,7 @@ public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) } SSOAuthorityMapper ssoMapper = (SSOAuthorityMapper)eduApplicationContext.getBean("ssoAuthorityMapper"); - HashMap ssoMap = new HashMap(); + Map ssoMap = new HashMap<>(); ssoMap.put(ssoMapper.getSSOUsernameProp(), remoteUser); authService.authenticateBySSO(SSOAuthorityMapper.SSO_TYPE_CAS, ssoMap); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/authentication/CASServlet.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/authentication/CASServlet.java index 237b54f77e..d2a19bfde5 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/authentication/CASServlet.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/authentication/CASServlet.java @@ -3,6 +3,7 @@ import java.io.IOException; import java.util.Enumeration; import java.util.HashMap; +import java.util.Map; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServlet; @@ -36,7 +37,7 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws Se AuthenticationToolAPI authTool = new AuthenticationToolAPI(); - HashMap validAuthInfo = authTool.validateAuthentication(req.getSession()); + Map validAuthInfo = authTool.validateAuthentication(req.getSession()); if(validAuthInfo != null ){ if(validAuthInfo.get(CCConstants.AUTH_USERNAME).equals(remoteUser)){ @@ -63,7 +64,7 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws Se SSOAuthorityMapper ssoMapper = (SSOAuthorityMapper)eduApplicationContext.getBean("ssoAuthorityMapper"); - HashMap ssoMap = new HashMap(); + Map ssoMap = new HashMap<>(); ssoMap.put(ssoMapper.getSSOUsernameProp(), remoteUser); authService.authenticateBySSO(SSOAuthorityMapper.SSO_TYPE_CAS, ssoMap); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/authentication/GuestFilter.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/authentication/GuestFilter.java index 0240da7be8..4e28b30335 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/authentication/GuestFilter.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/authentication/GuestFilter.java @@ -2,6 +2,7 @@ import java.io.IOException; import java.util.HashMap; +import java.util.Map; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; @@ -47,7 +48,7 @@ public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) try { AuthenticationTool authTool = RepoFactory.getAuthenticationToolInstance(ApplicationInfoList.getHomeRepository().getAppId()); HttpSession session = httpRequest.getSession(true); - HashMap authentication = authTool.validateAuthentication(session); + Map authentication = authTool.validateAuthentication(session); String guestFilterdisabled = req.getParameter(CCConstants.REQUEST_PARAM_DISABLE_GUESTFILTER); String guestFilterHeader=((HttpServletRequest)req).getHeader("DisableGuest"); @@ -63,7 +64,7 @@ else if (authentication == null && !new Boolean(guestFilterdisabled)) { logger.debug("guest filter disabled for context "+ConfigServiceFactory.getCurrentDomain()); } else { - HashMap authInfoGuest = authTool.createNewSession(guestLogin, guestPW); + Map authInfoGuest = authTool.createNewSession(guestLogin, guestPW); authTool.storeAuthInfoInSession(authInfoGuest.get(CCConstants.AUTH_USERNAME), authInfoGuest.get(CCConstants.AUTH_TICKET),CCConstants.AUTH_TYPE_DEFAULT, session); // prewarm tp session cache diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/authentication/LoginServlet.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/authentication/LoginServlet.java index f00de6f1c2..080f9f17c8 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/authentication/LoginServlet.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/authentication/LoginServlet.java @@ -2,6 +2,7 @@ import java.io.IOException; import java.util.HashMap; +import java.util.Map; import jakarta.servlet.RequestDispatcher; import jakarta.servlet.ServletException; @@ -41,7 +42,7 @@ private void loginProcess(HttpServletRequest req, HttpServletResponse resp, Stri redirectSuccessUrl = appInfo.getClientBaseUrl(); } AuthenticationTool authTool = RepoFactory.getAuthenticationToolInstance(ApplicationInfoList.getHomeRepository().getAppId()); - HashMap authInfo = authTool.createNewSession(userName, password); + Map authInfo = authTool.createNewSession(userName, password); authTool.storeAuthInfoInSession(userName, authInfo.get(CCConstants.AUTH_TICKET), CCConstants.AUTH_TYPE_DEFAULT, req.getSession()); if (redirectSuccessUrl.length()<=1) { try {Thread.sleep(1000);} catch(Exception ex) {} diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/authentication/NetworkAuthentication.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/authentication/NetworkAuthentication.java index 996bd2047b..7fd8b86148 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/authentication/NetworkAuthentication.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/authentication/NetworkAuthentication.java @@ -12,7 +12,7 @@ */ public class NetworkAuthentication { - Map authStore = new HashMap(); + Map authStore = new HashMap<>(); public class Authentication{ diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/authentication/ShibbolethServlet.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/authentication/ShibbolethServlet.java index 06e6a452c4..d25af6c6aa 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/authentication/ShibbolethServlet.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/authentication/ShibbolethServlet.java @@ -109,7 +109,7 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws Se } AuthenticationToolAPI authTool = new AuthenticationToolAPI(); - HashMap validAuthInfo = authTool.validateAuthentication(req.getSession()); + Map validAuthInfo = authTool.validateAuthentication(req.getSession()); redirectUrl = (String)req.getSession().getAttribute(NgServlet.PREVIOUS_ANGULAR_URL); // prefer the login url since it will intercept the regular angular url @@ -147,7 +147,7 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws Se req.setCharacterEncoding("UTF-8"); } - HashMap ssoMap = new HashMap(); + Map ssoMap = new HashMap<>(); for(String ssoKey : ssoMapper.getMappingConfig().getAllSSOAttributes()){ ssoMap.put(ssoKey, getShibValue(ssoKey,req)); } diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/authentication/oauth2/TokenEndpoint.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/authentication/oauth2/TokenEndpoint.java index 343fe18c06..9b0cf7f2cc 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/authentication/oauth2/TokenEndpoint.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/authentication/oauth2/TokenEndpoint.java @@ -28,6 +28,7 @@ import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; +import java.util.Map; public class TokenEndpoint extends HttpServlet { @@ -81,7 +82,7 @@ protected void doPost(HttpServletRequest request, String username = oauthRequest.getUsername(); // check - HashMap authInfo = RepoFactory.getAuthenticationToolInstance(null) + Map authInfo = RepoFactory.getAuthenticationToolInstance(null) .createNewSession(username, oauthRequest.getPassword()); tokenService.createToken(username, accessToken, refreshToken, clientId,authInfo.get(CCConstants.AUTH_TICKET)); @@ -119,7 +120,7 @@ protected void doPost(HttpServletRequest request, else if (GrantType.CLIENT_CREDENTIALS.toString().equals(grantType)) { try { - HashMap authInfo = RepoFactory.getAuthenticationToolInstance(null) + Map authInfo = RepoFactory.getAuthenticationToolInstance(null) .validateAuthentication(request.getSession()); String userName=authInfo.get("UserName"); if(authInfo==null || userName==null) diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/connector/ConnectorServlet.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/connector/ConnectorServlet.java index 16af3ad029..c407c39f37 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/connector/ConnectorServlet.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/connector/ConnectorServlet.java @@ -53,7 +53,7 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws Se String nodeId = req.getParameter("nodeId"); - HashMap auth = new AuthenticationToolAPI().validateAuthentication(req.getSession()); + Map auth = new AuthenticationToolAPI().validateAuthentication(req.getSession()); if(auth == null){ resp.sendError(HttpServletResponse.SC_UNAUTHORIZED); @@ -127,7 +127,7 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws Se return; } - HashMap properties=null; + Map properties; try { properties = NodeServiceHelper.getPropertiesOriginal(nodeRef); } catch (Throwable e1) { diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/exporter/OAILOMExporter.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/exporter/OAILOMExporter.java index 61b017b0a8..7039f64ff7 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/exporter/OAILOMExporter.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/exporter/OAILOMExporter.java @@ -51,7 +51,7 @@ public class OAILOMExporter { public static String configCatalog = "exporter.oai.lom.identifier.catalog"; protected String lomIdentifierCatalog = (LightbendConfigLoader.get().hasPath(configCatalog)) ? LightbendConfigLoader.get().getString(configCatalog) : ApplicationInfoList.getHomeRepository().getAppId(); - protected HashMap properties; + protected Map properties; public OAILOMExporter() throws ParserConfigurationException { ApplicationContext context = AlfAppContextGate.getApplicationContext(); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/exporter/OAILOMExporterHSOER.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/exporter/OAILOMExporterHSOER.java index 64c5c3444a..a96c05cb50 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/exporter/OAILOMExporterHSOER.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/exporter/OAILOMExporterHSOER.java @@ -84,7 +84,7 @@ public Element addContributer(Element eleParent, String contributerProp, String for(MetadataKey metadataKey : valuesAsMap.values()){ if(metadataKey.getKey().equals(university)){ - HashMap map = new HashMap<>(); + Map map = new HashMap<>(); map.put(CCConstants.VCARD_ORG,metadataKey.getCaption()); map.put(CCConstants.VCARD_URL,"https://"+university); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/exporter/OAILOMWithSubobjectsExporter.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/exporter/OAILOMWithSubobjectsExporter.java index eee274107c..6343a5bd7f 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/exporter/OAILOMWithSubobjectsExporter.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/exporter/OAILOMWithSubobjectsExporter.java @@ -49,19 +49,19 @@ class TagDef{ String subTagProperty; - HashMap properties = new HashMap(); + Map properties = new HashMap<>(); String type; String childAssociation; - List subTags = new ArrayList(); + List subTags = new ArrayList<>(); - public HashMap getProperties() { + public Map getProperties() { return properties; } - public void setProperties(HashMap properties) { + public void setProperties(Map properties) { this.properties = properties; } @@ -147,7 +147,7 @@ public OAILOMWithSubobjectsExporter(String ioId) throws ParserConfigurationExcep */ lom.setTag("lom"); - List lomSubTags = new ArrayList(); + List lomSubTags = new ArrayList<>(); lom.setSubTags(lomSubTags); /** @@ -223,7 +223,7 @@ public OAILOMWithSubobjectsExporter(String ioId) throws ParserConfigurationExcep lcContribute.setTag("contribute"); lcContribute.setType(CCConstants.LOM_TYPE_CONTRIBUTE); lcContribute.setChildAssociation(CCConstants.LOM_ASSOC_LIFECYCLE_CONTRIBUTE); - List lcContributeSubTags = new ArrayList(); + List lcContributeSubTags = new ArrayList<>(); lcContribute.setSubTags(lcContributeSubTags); lcContribute.getProperties().put(CCConstants.LOM_PROP_CONTRIBUTE_ENTITY, "entity"); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/BinaryHandlerTechnicalLocation.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/BinaryHandlerTechnicalLocation.java index a9799190fe..8b000de5bf 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/BinaryHandlerTechnicalLocation.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/BinaryHandlerTechnicalLocation.java @@ -4,6 +4,7 @@ import java.net.URL; import java.net.URLConnection; import java.util.HashMap; +import java.util.Map; import org.apache.commons.httpclient.util.URIUtil; import org.apache.log4j.Logger; @@ -24,7 +25,7 @@ public class BinaryHandlerTechnicalLocation implements BinaryHandler{ public BinaryHandlerTechnicalLocation() throws Throwable { ApplicationInfo homeRep = ApplicationInfoList.getHomeRepository(); AuthenticationTool authTool = RepoFactory.getAuthenticationToolInstance(homeRep.getAppId()); - HashMap authInfo = authTool.createNewSession(homeRep.getUsername(), homeRep.getPassword()); + Map authInfo = authTool.createNewSession(homeRep.getUsername(), homeRep.getPassword()); mcAlfrescoAPIClient = (MCAlfrescoAPIClient) RepoFactory.getInstance(homeRep.getAppId(), authInfo); } diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/ExcelLOMImporter.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/ExcelLOMImporter.java index 8353bb3cad..f54a35d76a 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/ExcelLOMImporter.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/ExcelLOMImporter.java @@ -33,7 +33,7 @@ public class ExcelLOMImporter { Logger logger = Logger.getLogger(ExcelLOMImporter.class); - HashMap excelAlfMap = null; + Map excelAlfMap = null; ServiceRegistry serviceRegistry = (ServiceRegistry)AlfAppContextGate.getApplicationContext().getBean(ServiceRegistry.SERVICE_REGISTRY); @@ -48,7 +48,7 @@ public class ExcelLOMImporter { MCAlfrescoAPIClient apiClient = new MCAlfrescoAPIClient(); - private HashMap> currentLevelObjects = null; + private Map> currentLevelObjects = null; private int rowCount; @@ -68,7 +68,7 @@ public ExcelLOMImporter(String targetFolder, InputStream is, Boolean addToCollec this.is = is; - HashMap IdxColumnMap = new HashMap(); + Map IdxColumnMap = new HashMap<>(); try{ Workbook workbook = WorkbookFactory.create(this.is); @@ -85,7 +85,7 @@ public ExcelLOMImporter(String targetFolder, InputStream is, Boolean addToCollec NodeRef currentFolder = nodeService.getChildByName(targetFolderNodeRef, assocTypeContains, folderName); if(currentFolder == null){ - Map folderProps = new HashMap(); + Map folderProps = new HashMap<>(); folderProps.put(QName.createQName(CCConstants.CM_NAME), folderName); folderProps.put(QName.createQName(CCConstants.CM_PROP_C_TITLE), folderName); parentFolder = nodeService.createNode(targetFolderNodeRef,assocTypeContains, QName.createQName(folderName), QName.createQName(CCConstants.CCM_TYPE_MAP),folderProps).getChildRef().getId(); @@ -99,10 +99,10 @@ public ExcelLOMImporter(String targetFolder, InputStream is, Boolean addToCollec if(IdxColumnMap.size() > 0){ //we got the headers - HashMap toSafe = new HashMap(); + Map toSafe = new HashMap<>(); String contentUrl = null; - LinkedHashSet collectionsToImportTo = new LinkedHashSet(); + LinkedHashSet collectionsToImportTo = new LinkedHashSet<>(); for(Cell cell : row){ int colIdxIdx = cell.getColumnIndex(); @@ -144,7 +144,7 @@ public ExcelLOMImporter(String targetFolder, InputStream is, Boolean addToCollec if(propDef != null) { if(propDef.isMultiValued() && !alfrescoProperty.contains("contributer")){ - ArrayList multival = new ArrayList(); + ArrayList multival = new ArrayList<>(); //String[] vals = value.split(","); StringTool.escape(CCConstants.MULTIVALUE_SEPARATOR) String[] vals = value.split(StringTool.escape(CCConstants.MULTIVALUE_SEPARATOR)); @@ -226,7 +226,7 @@ public ExcelLOMImporter(String targetFolder, InputStream is, Boolean addToCollec } - private void addThumbnail(HashMap toSafe, String wwwUrl) { + private void addThumbnail(Map toSafe, String wwwUrl) { String thumbnailUrl = (String) toSafe.get(qnameThumbnail); if(thumbnailUrl == null && wwwUrl != null && wwwUrl.contains("youtu")){ String youtubeId = getYoutubeId(wwwUrl); @@ -247,7 +247,7 @@ private void addThumbnail(HashMap toSafe, String wwwUrl) { * @param wwwUrl * @return */ - private String addName(HashMap toSafe, String wwwUrl) { + private String addName(Map toSafe, String wwwUrl) { if(toSafe.get(qnameTitle) == null && wwwUrl != null && wwwUrl.startsWith("http")){ WebsiteInformation websiteInfo = ClientUtilsService.getWebsiteInformation(wwwUrl); if(websiteInfo != null){ @@ -277,7 +277,7 @@ private String addName(HashMap toSafe, String wwwUrl) { return null; } - HashMap eduProps = new HashMap(); + Map eduProps = new HashMap<>(); eduProps.put(CCConstants.CM_NAME, nodeName); eduProps.put(CCConstants.LOM_PROP_GENERAL_TITLE, nodeName); new DuplicateFinder().transformToSafeName(currentLevelObjects, eduProps); @@ -367,9 +367,9 @@ private static String getYoutubeId(String wwwUrl){ } } - public HashMap getExcelAlfMap() { + public Map getExcelAlfMap() { if(excelAlfMap == null){ - excelAlfMap = new HashMap(); + excelAlfMap = new HashMap<>(); excelAlfMap.put("catalog", CCConstants.CCM_PROP_IO_REPLICATIONSOURCE); excelAlfMap.put("identifier", CCConstants.CCM_PROP_IO_REPLICATIONSOURCEID); excelAlfMap.put("datestamp", CCConstants.CCM_PROP_IO_REPLICATIONSOURCETIMESTAMP); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/ImportCleaner.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/ImportCleaner.java index 8b57b2d598..36d66dcfbc 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/ImportCleaner.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/ImportCleaner.java @@ -130,7 +130,7 @@ public void removeDeletedImportedObjects(List allNodes) throws Throwabl ApplicationInfo homeRep = ApplicationInfoList.getHomeRepository(); AuthenticationTool authTool = RepoFactory.getAuthenticationToolInstance(homeRep.getAppId()); - HashMap authInfo = authTool.createNewSession(homeRep.getUsername(), homeRep.getPassword()); + Map authInfo = authTool.createNewSession(homeRep.getUsername(), homeRep.getPassword()); MCAlfrescoBaseClient mcAlfrescoBaseClient = (MCAlfrescoBaseClient ) RepoFactory.getInstance(homeRep.getAppId(), authInfo); int countDeletedObjects = 0; if(allNodes != null){ @@ -143,8 +143,8 @@ public void removeDeletedImportedObjects(List allNodes) throws Throwabl boolean nodeExists = nodeExists(importedId, importedKatalog); if(!nodeExists){ logger.info("Node with REPLICATIONSOURCEID:"+importedId+" REPLICATIONSOURCE:"+importedKatalog+" seems deleted. Delete the imported Object nodeId:"+alfNodeId); - HashMap primaryParents = mcAlfrescoBaseClient.getParents(alfNodeId, true); - Map.Entry primaryParentEntry = primaryParents.entrySet().iterator().next(); + Map> primaryParents = mcAlfrescoBaseClient.getParents(alfNodeId, true); + Map.Entry> primaryParentEntry = primaryParents.entrySet().iterator().next(); mcAlfrescoBaseClient.removeNode(alfNodeId, primaryParentEntry.getKey()); countDeletedObjects++; } diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/ImportCleanerIdentifiersList.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/ImportCleanerIdentifiersList.java index 0a06d72779..4e6e1808bd 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/ImportCleanerIdentifiersList.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/ImportCleanerIdentifiersList.java @@ -42,7 +42,7 @@ public class ImportCleanerIdentifiersList { XPath xpath = pfactory.newXPath(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - List nodeAtOaiService = new ArrayList(); + List nodeAtOaiService = new ArrayList<>(); /** * @@ -51,7 +51,7 @@ public class ImportCleanerIdentifiersList { MCAlfrescoAPIClient mcAlfrescoBaseClient = new MCAlfrescoAPIClient(); - List toDeleteList = new ArrayList(); + List toDeleteList = new ArrayList<>(); public ImportCleanerIdentifiersList(String baseUrl, String set, String metadataPrefix, boolean testMode) { try { diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/ImporterJobDDB.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/ImporterJobDDB.java index 2d031f25e4..3e2e96ed12 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/ImporterJobDDB.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/ImporterJobDDB.java @@ -52,12 +52,12 @@ void start(String ddbFile, String query, int nrOfResults) throws Throwable{ MetadataSet mds=MetadataHelper.getMetadataset(app, CCConstants.metadatasetdefault_id); SearchToken token = new SearchToken(); - HashMap criterias = new HashMap(); + Map criterias = new HashMap<>(); criterias.put(MetadataSet.DEFAULT_CLIENT_QUERY_CRITERIA, new String[] {query}); List ddbObjects = new SearchServiceDDBImpl(app.getAppId()).search(mds, MetadataSet.DEFAULT_CLIENT_QUERY,criterias,token).getData(); for(NodeRef node : ddbObjects){ - HashMap ddbObject = new NodeServiceDDBImpl(app.getAppId()).getProperties(node.getStoreProtocol(), node.getStoreId(), node.getNodeId()); + Map ddbObject = new NodeServiceDDBImpl(app.getAppId()).getProperties(node.getStoreProtocol(), node.getStoreId(), node.getNodeId()); ddbObject.put(CCConstants.CCM_PROP_IO_REPLICATIONSOURCEID, ddbObject.get(CCConstants.SYS_PROP_NODE_UID)); @@ -95,7 +95,7 @@ void start(String ddbFile, String query, int nrOfResults) throws Throwable{ @Override public Class[] getJobClasses() { // TODO Auto-generated method stub - ArrayList jobs = new ArrayList(); + ArrayList jobs = new ArrayList<>(); jobs.addAll(Arrays.asList(allJobs)); jobs.add(ImporterJobDDB.class); return jobs.toArray(new Class[jobs.size()]); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/MoodleImporter.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/MoodleImporter.java index 7231fc6f47..7cca66d2f2 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/MoodleImporter.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/MoodleImporter.java @@ -4,6 +4,7 @@ import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; +import java.util.Map; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; @@ -77,7 +78,7 @@ public MoodleImporter( for (int i = 0, c = nodeList.getLength(); i < c; ++i) { Node node = nodeList.item(i); - HashMap eduProps = new HashMap(); + Map eduProps = new HashMap<>(); String id = xPath.compile("KEY[@name='id']/VALUE/text()").evaluate(node); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/OPALImporter.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/OPALImporter.java index 81244afddb..5dacbef7b8 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/OPALImporter.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/OPALImporter.java @@ -4,6 +4,7 @@ import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; +import java.util.Map; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; @@ -77,7 +78,7 @@ public OPALImporter( for (Response.RepositoryResource course : data.repositoryResource) { - HashMap eduProps = new HashMap(); + Map eduProps = new HashMap<>(); eduProps.put( CCConstants.CCM_PROP_IO_REPLICATIONSOURCE, diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/PersistenHandlerKeywordsDNBMarc.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/PersistenHandlerKeywordsDNBMarc.java index dcf095d626..b5c3c3a11b 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/PersistenHandlerKeywordsDNBMarc.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/PersistenHandlerKeywordsDNBMarc.java @@ -48,7 +48,7 @@ public PersistenHandlerKeywordsDNBMarc(){ @Override public String safe(RecordHandlerInterfaceBase recordHandler, String cursor, String set) throws Throwable { - HashMap props = recordHandler.getProperties(); + Map props = recordHandler.getProperties(); String id = (String)props.get(RecordHandlerKeywordsDNBMarc.ID); if(id == null){ logger.error("no id provided"); @@ -254,7 +254,7 @@ public long countEntries(){ } - public List> getEntriesByDisplayValue(String value){ + public List> getEntriesByDisplayValue(String value){ value = value.trim(); String[] splitted = value.split(" \\("); @@ -262,7 +262,7 @@ public List> getEntriesByDisplayValue(String value){ String tempSyn = (splitted.length > 1) ? splitted[1].replaceAll("\\)","") : null; String[] termSyns = (tempSyn != null) ? tempSyn.split(", ") : null; - List> result = new ArrayList<>(); + List> result = new ArrayList<>(); Connection con = null; PreparedStatement statement = null; ConnectionDBAlfresco dbAlf = new ConnectionDBAlfresco(); @@ -291,7 +291,7 @@ public List> getEntriesByDisplayValue(String value){ java.sql.ResultSet resultSet = statement.executeQuery(); while (resultSet.next()){ - HashMap row = new HashMap<>(); + Map row = new HashMap<>(); int colCount = resultSet.getMetaData().getColumnCount(); for(int i = 1; i <= colCount; i++){ row.put(resultSet.getMetaData().getColumnName(i),resultSet.getObject(i)); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/PersistentHandlerDB.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/PersistentHandlerDB.java index 7dcb2b959a..bde2096b88 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/PersistentHandlerDB.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/PersistentHandlerDB.java @@ -48,7 +48,7 @@ public void initTable() throws Exception{ public String safe(RecordHandlerInterfaceBase recordHandler, String cursor, String set) throws Throwable{ - HashMap tableStruct = this.getTableStructure(null, recordHandler.getProperties(), null); + Map tableStruct = this.getTableStructure(null, recordHandler.getProperties(), null); String checkTableExistsSql = "show tables"; @@ -148,13 +148,13 @@ public void cleanUp() throws Exception{ } } - HashMap getTableStructure(HashMap tablestructure, Map props, String colNamePrefix){ + Map getTableStructure(Map tablestructure, Map props, String colNamePrefix){ if(tablestructure == null){ - tablestructure = new HashMap(); + tablestructure = new HashMap<>(); } - HashMap simpleProps = new HashMap(); - HashMap nodeProps = new HashMap(); + Map simpleProps = new HashMap<>(); + Map nodeProps = new HashMap<>(); for(Object key:props.keySet()){ String propKey = (String)key; if(propKey.startsWith("TYPE#")){ diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/PersistentHandlerEdusharing.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/PersistentHandlerEdusharing.java index a769626ff2..617677f380 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/PersistentHandlerEdusharing.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/PersistentHandlerEdusharing.java @@ -71,8 +71,8 @@ public class PersistentHandlerEdusharing implements PersistentHandlerInterface { List allNodesInImportfolder = null; // - HashMap replIdTimestampMap = null; - HashMap replIdMap = null; + Map replIdTimestampMap = null; + Map replIdMap = null; private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:sss"); @@ -145,7 +145,7 @@ public static void removeAllImportedObjects(AbstractJob job) throws Throwable { } public String safe(RecordHandlerInterfaceBase recordHandler, String cursor, String set) throws Throwable { - HashMap newNodeProps = recordHandler.getProperties(); + Map newNodeProps = recordHandler.getProperties(); String replicationId = (String) newNodeProps.get(CCConstants.CCM_PROP_IO_REPLICATIONSOURCEID); String lomCatalogId = (String) newNodeProps.get(CCConstants.CCM_PROP_IO_REPLICATIONSOURCE); @@ -162,18 +162,18 @@ public String safe(RecordHandlerInterfaceBase recordHandler, String cursor, Stri // watch out if object was already imported - // HashMap> alfResult = + // Map> alfResult = // mcAlfrescoBaseClient.search("@ccm\\:replicationsourceid:"+replicationId+" AND @ccm\\:replicationsource:"+lomCatalogId, // CCConstants.CCM_TYPE_IO); // HashMap searchProps = new HashMap(); // searchProps.put(CCConstants.CCM_PROP_IO_REPLICATIONSOURCE, lomCatalogId); // searchProps.put(CCConstants.CCM_PROP_IO_REPLICATIONSOURCEID, replicationId); - // HashMap childProps = mcAlfrescoBaseClient.getChildRecursive(oaiImportBasefolder, CCConstants.CCM_TYPE_IO, searchProps); + // Map childProps = mcAlfrescoBaseClient.getChildRecursive(oaiImportBasefolder, CCConstants.CCM_TYPE_IO, searchProps); String nodeReplId=lomCatalogId+":"+replicationId; - HashMap filter = new HashMap() {{ - put(CCConstants.CCM_PROP_IO_REPLICATIONSOURCE, lomCatalogId); - put(CCConstants.CCM_PROP_IO_REPLICATIONSOURCEID, replicationId); - }}; + Map filter = new HashMap<>() {{ + put(CCConstants.CCM_PROP_IO_REPLICATIONSOURCE, lomCatalogId); + put(CCConstants.CCM_PROP_IO_REPLICATIONSOURCEID, replicationId); + }}; NodeRef childId = getNodeIfExists(filter); getLogger().debug("child id "+nodeReplId+": "+childId); @@ -249,9 +249,9 @@ private synchronized String createFolderStructure(String cursor, String set) thr return importFolderCursorIds.get(searchId); String folderId=importFolderId; - HashMap setChild = mcAlfrescoBaseClient.getChild(folderId, CCConstants.CCM_TYPE_MAP, CCConstants.CM_NAME, set); + Map setChild = mcAlfrescoBaseClient.getChild(folderId, CCConstants.CCM_TYPE_MAP, CCConstants.CM_NAME, set); if (setChild == null) { - HashMap newimportFolderProps = new HashMap(); + Map newimportFolderProps = new HashMap<>(); newimportFolderProps.put(CCConstants.CM_NAME, set); newimportFolderProps.put(CCConstants.CM_PROP_C_TITLE, set); getLogger().info("Folder for set "+set+" does not yet exists, will be created"); @@ -262,9 +262,9 @@ private synchronized String createFolderStructure(String cursor, String set) thr - HashMap cursorChild = mcAlfrescoBaseClient.getChild(folderId, CCConstants.CCM_TYPE_MAP, CCConstants.CM_NAME, cursor); + Map cursorChild = mcAlfrescoBaseClient.getChild(folderId, CCConstants.CCM_TYPE_MAP, CCConstants.CM_NAME, cursor); if (cursorChild == null) { - HashMap newimportFolderProps = new HashMap(); + Map newimportFolderProps = new HashMap<>(); newimportFolderProps.put(CCConstants.CM_NAME, cursor); newimportFolderProps.put(CCConstants.CM_PROP_C_TITLE, cursor); getLogger().info("Folder for set "+set+" with cursor "+cursor+" does not yet exists, will be created"); @@ -279,11 +279,11 @@ private synchronized String createFolderStructure(String cursor, String set) thr public static String prepareImportFolder() throws Throwable { MCAlfrescoAPIClient mcAlfrescoBaseClient = new MCAlfrescoAPIClient(); String companyHomeId = mcAlfrescoBaseClient.getCompanyHomeNodeId(); - HashMap importFolderProps = mcAlfrescoBaseClient.getChild(companyHomeId, CCConstants.CCM_TYPE_MAP, CCConstants.CM_NAME, + Map importFolderProps = mcAlfrescoBaseClient.getChild(companyHomeId, CCConstants.CCM_TYPE_MAP, CCConstants.CM_NAME, OAIPMHLOMImporter.FOLDER_NAME_IMPORTED_OBJECTS); String importFolderId; if (importFolderProps == null) { - HashMap newimportFolderProps = new HashMap(); + Map newimportFolderProps = new HashMap<>(); newimportFolderProps.put(CCConstants.CM_NAME, OAIPMHLOMImporter.FOLDER_NAME_IMPORTED_OBJECTS); newimportFolderProps.put(CCConstants.CM_PROP_C_TITLE, OAIPMHLOMImporter.FOLDER_NAME_IMPORTED_OBJECTS); importFolderId = mcAlfrescoBaseClient.createNode(companyHomeId, CCConstants.CCM_TYPE_MAP, newimportFolderProps); @@ -374,13 +374,13 @@ public List getAllNodesInImportfolder(String importFolderId) throws Thr public void updateNode(String nodeId, Map props, List propertiesToRemove) throws Throwable { // idea first delete all childs and create them new synchronized (this) { - HashMap children = mcAlfrescoBaseClient.getChildren(nodeId); + Map> children = mcAlfrescoBaseClient.getChildren(nodeId); for (Object key : children.keySet()) { mcAlfrescoBaseClient.removeNode((String) key, nodeId, false); } } - HashMap simpleProps = new HashMap(); - HashMap nodeProps = new HashMap(); + Map simpleProps = new HashMap<>(); + Map nodeProps = new HashMap<>(); for (Object key : props.keySet()) { String propKey = (String) key; if (propKey.startsWith("TYPE#")) { @@ -414,7 +414,7 @@ public void updateNode(String nodeId, Map props, List propertiesToRemove createChildobjects(nodeId, nodeProps); } - private void createChildobjects(String nodeId, HashMap nodeProps) throws Throwable { + private void createChildobjects(String nodeId, Map nodeProps) throws Throwable { if(importer!=null && !importer.getRecordHandler().createSubobjects()){ return; } @@ -439,12 +439,12 @@ private void createChildobjects(String nodeId, HashMap nodeProps } } - public String createNode(String parentId, String type, String association, Map props) throws Throwable { - HashMap simpleProps = new HashMap(); - HashMap nodeProps = new HashMap(); + public String createNode(String parentId, String type, String association, Map props) throws Throwable { + Map simpleProps = new HashMap<>(); + Map nodeProps = new HashMap<>(); String[] aspects=null; - for (Object key : props.keySet()) { - String propKey = (String) key; + for (String key : props.keySet()) { + String propKey = key; if(propKey.equals("ASPECTS")){ aspects=(String[])props.get(propKey); } @@ -474,11 +474,11 @@ else if (propKey.startsWith("TYPE#")) { return newNodeId; } - public HashMap getReplIdMap() { + public Map getReplIdMap() { return replIdMap; } - public HashMap getReplicationIdTimestampMap() { + public Map getReplicationIdTimestampMap() { if(!hasTimestampMap) { replIdMap = new HashMap<>(); replIdTimestampMap=new HashMap<>(); @@ -589,7 +589,7 @@ public synchronized boolean mustBePersisted(NodeRef childId, String replId, Stri private String getOldTimestamp(String replId) { if(!hasTimestampMap) { try { - NodeRef node = getNodeIfExists(new HashMap() {{ + NodeRef node = getNodeIfExists(new HashMap<>() {{ put(CCConstants.CCM_PROP_IO_REPLICATIONSOURCEID, replId); }}); return NodeServiceHelper.getProperty(node, CCConstants.CCM_PROP_IO_REPLICATIONSOURCETIMESTAMP); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/RecordHandlerDublinCoreDMG.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/RecordHandlerDublinCoreDMG.java index 3287ecf644..5d91e4709a 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/RecordHandlerDublinCoreDMG.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/RecordHandlerDublinCoreDMG.java @@ -2,6 +2,7 @@ import java.util.ArrayList; import java.util.HashMap; +import java.util.Map; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.xpath.XPath; @@ -25,12 +26,12 @@ public class RecordHandlerDublinCoreDMG implements RecordHandlerInterface { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); String metadataSetId = null; - HashMap toSafeMap = new HashMap(); + Map toSafeMap = new HashMap<>(); int counter = 0; @Override - public HashMap getProperties() { + public Map getProperties() { return toSafeMap; } @@ -81,7 +82,7 @@ public void handleRecord(Node nodeRecord, String cursor, String set) throws Thro lomCatalogId = replicationId.substring(0,replicationId.lastIndexOf(":")); } - HashMap generalIdentifierToSafeMap = new HashMap(); + Map generalIdentifierToSafeMap = new HashMap<>(); generalIdentifierToSafeMap.put(CCConstants.LOM_PROP_IDENTIFIER_ENTRY, replicationId); generalIdentifierToSafeMap.put(CCConstants.LOM_PROP_IDENTIFIER_CATALOG, lomCatalogId); @@ -106,7 +107,7 @@ public void handleRecord(Node nodeRecord, String cursor, String set) throws Thro String keywords = title; keywords = keywords.replaceAll(",", " "); String[] splittetTitle = keywords.split(" "); - ArrayList listTitle = new ArrayList(); + ArrayList listTitle = new ArrayList<>(); if(splittetTitle != null && splittetTitle.length > 0){ for(String titleEle : splittetTitle){ titleEle = titleEle.trim(); @@ -146,11 +147,11 @@ public void handleRecord(Node nodeRecord, String cursor, String set) throws Thro Node metadataCreatorNode = metadataCreator.item(i); String metadataCreatorString = ((String)xpath.evaluate(".", metadataCreatorNode, XPathConstants.STRING)).trim(); if(!metadataCreatorString.equals("")){ - HashMap vcardMap = new HashMap(); + Map vcardMap = new HashMap<>(); vcardMap.put(CCConstants.VCARD_SURNAME, metadataCreatorString); String vcardString = VCardTool.hashMap2VCard(vcardMap); - HashMap contributerMetadataCreator = new HashMap(); + Map contributerMetadataCreator = new HashMap<>(); contributerMetadataCreator.put(CCConstants.LOM_PROP_CONTRIBUTE_ENTITY, vcardString); contributerMetadataCreator.put(CCConstants.LOM_PROP_CONTRIBUTE_ROLE, "creator"); toSafeMap.put("TYPE#" + CCConstants.LOM_TYPE_CONTRIBUTE + "#" + CCConstants.LOM_ASSOC_META_METADATA_CONTRIBUTE, contributerMetadataCreator); @@ -163,11 +164,11 @@ public void handleRecord(Node nodeRecord, String cursor, String set) throws Thro Node contributerPublisherNode= contributerPublisher.item(i); String contributerPublisherString = ((String)xpath.evaluate(".", contributerPublisherNode, XPathConstants.STRING)).trim(); if(!contributerPublisherString.equals("")){ - HashMap vcardMap = new HashMap(); + Map vcardMap = new HashMap<>(); vcardMap.put(CCConstants.VCARD_SURNAME, contributerPublisherString); String vcardString = VCardTool.hashMap2VCard(vcardMap); - HashMap contributerPublisherMap = new HashMap(); + Map contributerPublisherMap = new HashMap<>(); contributerPublisherMap.put(CCConstants.LOM_PROP_CONTRIBUTE_ENTITY, vcardString); contributerPublisherMap.put(CCConstants.LOM_PROP_CONTRIBUTE_ROLE, "publisher"); toSafeMap.put("TYPE#" + CCConstants.LOM_TYPE_CONTRIBUTE + "#" + CCConstants.LOM_ASSOC_LIFECYCLE_CONTRIBUTE, contributerPublisherMap); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/RecordHandlerElixier.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/RecordHandlerElixier.java index f8877635a6..40676fc7b8 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/RecordHandlerElixier.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/RecordHandlerElixier.java @@ -28,6 +28,7 @@ package org.edu_sharing.repository.server.importer; import java.util.HashMap; +import java.util.Map; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; @@ -44,7 +45,7 @@ public class RecordHandlerElixier implements RecordHandlerInterface{ XPathFactory pfactory = XPathFactory.newInstance(); XPath xpath = pfactory.newXPath(); - HashMap toSafeList = new HashMap(); + Map toSafeList = new HashMap<>(); public RecordHandlerElixier() { } @@ -75,7 +76,7 @@ public void handleRecord(Node nodeRecord, String cursor, String set) throws Thro } @Override - public HashMap getProperties() { + public Map getProperties() { return toSafeList; } diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/RecordHandlerInterface.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/RecordHandlerInterface.java index d7d405ab33..6834185689 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/RecordHandlerInterface.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/RecordHandlerInterface.java @@ -31,7 +31,7 @@ public interface RecordHandlerInterface extends RecordHandlerInterfaceBase { - public void handleRecord(Node nodeRecord,String cursor,String set) throws Throwable; + void handleRecord(Node nodeRecord, String cursor, String set) throws Throwable; /** * override this in any Record Handler to control if the peristent handler shall create subojects later diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/RecordHandlerInterfaceBase.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/RecordHandlerInterfaceBase.java index d5f7e93b89..f74c365469 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/RecordHandlerInterfaceBase.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/RecordHandlerInterfaceBase.java @@ -3,10 +3,11 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; +import java.util.Map; public interface RecordHandlerInterfaceBase { - public HashMap getProperties(); + Map getProperties(); default List getPropertiesToRemove(){ return new ArrayList<>(); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/RecordHandlerKeywordsDNBMarc.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/RecordHandlerKeywordsDNBMarc.java index 5d72207669..3c1c139949 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/RecordHandlerKeywordsDNBMarc.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/RecordHandlerKeywordsDNBMarc.java @@ -125,7 +125,7 @@ public static void main(String[] args) throws Throwable { } @Override - public HashMap getProperties() { + public Map getProperties() { return toSafeMap; } } diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/RecordHandlerLOM.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/RecordHandlerLOM.java index 04644bc99b..9486e92023 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/RecordHandlerLOM.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/RecordHandlerLOM.java @@ -104,7 +104,7 @@ public void handleRecord(Node nodeRecord, String cursor, String set) throws Thro String replicationId = null; String lomCatalogId = null; - List> generalIdentifierList = new ArrayList>(); + List> generalIdentifierList = new ArrayList<>(); NodeList identifierNodeList = (NodeList) xpath.evaluate("metadata/lom/general/identifier", nodeRecord, XPathConstants.NODESET); for(int i = 0; i < identifierNodeList.getLength(); i++){ // general identifier @@ -116,7 +116,7 @@ public void handleRecord(Node nodeRecord, String cursor, String set) throws Thro lomCatalogId = tmpLomCatalogId; } - HashMap generalIdentifierToSafeMap = new HashMap(); + Map generalIdentifierToSafeMap = new HashMap<>(); generalIdentifierToSafeMap.put(CCConstants.LOM_PROP_IDENTIFIER_ENTRY, tmpReplicationId); generalIdentifierToSafeMap.put(CCConstants.LOM_PROP_IDENTIFIER_CATALOG, tmpLomCatalogId); @@ -243,21 +243,21 @@ public void handleRecord(Node nodeRecord, String cursor, String set) throws Thro String lifecycleStatusValue = (String) xpath.evaluate("status/value", lifecycleNode, XPathConstants.STRING); // lifecycleContribute - ArrayList> lifecycleContributes = null; + ArrayList> lifecycleContributes; /** * search replication preferred from LOM */ - HashMap> replLifecycleContributer = new HashMap>(); + Map> replLifecycleContributer = new HashMap<>(); lifecycleContributes = getContributes(lifecycleNode); if(lifecycleContributes != null){ - ArrayList> assignedLicenses = new ArrayList>(); - List assignedLicensesAuthorities = new ArrayList(); + ArrayList> assignedLicenses = new ArrayList<>(); + List assignedLicensesAuthorities = new ArrayList<>(); Date assignedLicenseExpiryDate = null; - for (HashMap contr : lifecycleContributes) { + for (Map contr : lifecycleContributes) { String role = (String) contr.get(CCConstants.LOM_PROP_CONTRIBUTE_ROLE); String entity = (String) contr.get(CCConstants.LOM_PROP_CONTRIBUTE_ENTITY); @@ -268,14 +268,14 @@ public void handleRecord(Node nodeRecord, String cursor, String set) throws Thro String lc_property = CCConstants.getLifecycleContributerProp(role.trim()); if(lc_property != null && !lc_property.trim().equals("")){ ArrayList tmpLCList = replLifecycleContributer.get(lc_property); - if(tmpLCList == null) tmpLCList = new ArrayList(); + if(tmpLCList == null) tmpLCList = new ArrayList<>(); /** * add Date */ if(date != null){ - ArrayList> vards = VCardConverter.vcardToHashMap(entity); + ArrayList> vards = VCardConverter.vcardToMap(entity); if(vards != null && vards.size() > 0) { vards.get(0).put(CCConstants.VCARD_EXT_LOM_CONTRIBUTE_DATE, date); entity = VCardTool.hashMap2VCard((HashMap)vards.get(0)); @@ -310,7 +310,7 @@ public void handleRecord(Node nodeRecord, String cursor, String set) throws Thro } if (role != null && role.equals("distributor")) { String vcard = (String)contr.get(CCConstants.LOM_PROP_CONTRIBUTE_ENTITY); - ArrayList> vcards =VCardConverter.vcardToHashMap(vcard); + ArrayList> vcards =VCardConverter.vcardToHashMap(vcard); if(vcards != null){ String mediaCenter = (String)vcards.get(0).get("FN"); if(mediaCenter != null && !mediaCenter.trim().equals("")){ @@ -321,9 +321,9 @@ public void handleRecord(Node nodeRecord, String cursor, String set) throws Thro } if(assignedLicenseExpiryDate != null){ - ArrayList> assignedLicensesNodes = new ArrayList>(); + ArrayList> assignedLicensesNodes = new ArrayList>(); for(String authority : assignedLicensesAuthorities){ - HashMap props = new HashMap(); + Map props = new HashMap<>(); props.put(CCConstants.CCM_PROP_ASSIGNED_LICENSE_AUTHORITY, AuthorityType.GROUP.getPrefixString() + authority); props.put(CCConstants.CCM_PROP_ASSIGNED_LICENSE_ASSIGNEDLICENSE_EXPIRY, assignedLicenseExpiryDate); //props.put(CCConstants.CCM_PROP_ASSIGNED_LICENSE_ASSIGNEDLICENSE_EXPIRY, new Date(System.currentTimeMillis() + 600000)); @@ -371,15 +371,15 @@ public void handleRecord(Node nodeRecord, String cursor, String set) throws Thro String identifierEntry = (String) xpath.evaluate("identifier/entry", nodeMetaMetadata, XPathConstants.STRING); String language = (String) xpath.evaluate("language", nodeMetaMetadata, XPathConstants.STRING); - ArrayList> metaMetadataContributes = getContributes(nodeMetaMetadata); + ArrayList> metaMetadataContributes = getContributes(nodeMetaMetadata); // metadata contributer creator als replication attribut - ArrayList creatorList = new ArrayList(); + ArrayList creatorList = new ArrayList<>(); //metadata contribuiter provider - ArrayList providerList = new ArrayList(); + ArrayList providerList = new ArrayList<>(); if (metaMetadataContributes != null) { - for (HashMap map : metaMetadataContributes) { + for (Map map : metaMetadataContributes) { String role = (String) map.get(CCConstants.LOM_PROP_CONTRIBUTE_ROLE); if (role != null && role.trim().equals("creator")) { @@ -527,7 +527,7 @@ public void handleRecord(Node nodeRecord, String cursor, String set) throws Thro NodeList nodeEducationalList = (NodeList) xpath.evaluate("metadata/lom/educational", nodeRecord, XPathConstants.NODESET); List educationalToSafeList = new ArrayList(); // LOM Replication lists - List lomReplicationLearningresourceTypeList = new ArrayList(); + List lomReplicationLearningresourceTypeList = new ArrayList<>(); List lomReplicationEducationalContextList = new ArrayList(); List lomReplicationIntendedEndUserList = new ArrayList(); List lomReplicationTypicalAgeRangeList = new ArrayList(); @@ -628,7 +628,7 @@ public void handleRecord(Node nodeRecord, String cursor, String set) throws Thro List lomReplicationTaxonEntry = new ArrayList(); List lomReplicationTaxonId = new ArrayList(); - List classificationKeywords = new ArrayList(); + List classificationKeywords = new ArrayList<>(); for (int i = 0; i < nodeClassificationList.getLength(); i++) { Node classificationNode = nodeClassificationList.item(i); String purposeSource = (String) xpath.evaluate("purpose/source", classificationNode, XPathConstants.STRING); @@ -706,8 +706,8 @@ public void handleRecord(Node nodeRecord, String cursor, String set) throws Thro // //alf5 solr4 don't likes to get null for mltext properties (solr tracking failed). So we put an empty list here // - toSafeMap.put(CCConstants.CCM_PROP_IO_REPL_TAXON_ENTRY, new ArrayList()); - toSafeMap.put(CCConstants.CCM_PROP_IO_REPL_TAXON_ID, new ArrayList()); + toSafeMap.put(CCConstants.CCM_PROP_IO_REPL_TAXON_ENTRY, new ArrayList<>()); + toSafeMap.put(CCConstants.CCM_PROP_IO_REPL_TAXON_ID, new ArrayList<>()); */ /** * add them to the remove list, this is better than empty lists @@ -753,7 +753,7 @@ public void handleRecord(Node nodeRecord, String cursor, String set) throws Thro */ // getting Thumbnail thru elixier dialect - ArrayList fach_sachgebietListOriginal = new ArrayList(); + ArrayList fach_sachgebietListOriginal = new ArrayList<>(); String serientitel = null; List relationToSafeList = new ArrayList(); @@ -829,7 +829,7 @@ private static List convertListToString(NodeList nodes) { * @throws XPathExpressionException */ public ArrayList getMultiLangValueNew(Node node) throws XPathExpressionException { - ArrayList result = new ArrayList(); + ArrayList result = new ArrayList<>(); if (node != null) { NodeList langList = (NodeList) xpath.evaluate("string", node, XPathConstants.NODESET); if(langList.getLength() == 0) langList = (NodeList) xpath.evaluate("langstring", node, XPathConstants.NODESET); @@ -891,11 +891,11 @@ public List getMultivalue(Node parent, String nodeName,boolean ignoreEmpty) thro return null; } - public ArrayList> getContributes(Node parent) throws XPathExpressionException { - ArrayList> result = new ArrayList>(); + public ArrayList> getContributes(Node parent) throws XPathExpressionException { + ArrayList> result = new ArrayList<>(); NodeList contributes = (NodeList) xpath.evaluate("contribute", parent, XPathConstants.NODESET); for (int i = 0; i < contributes.getLength(); i++) { - HashMap map = new HashMap(); + Map map = new HashMap<>(); Node nodeContribute = contributes.item(i); String contributeRoleSource = (String) xpath.evaluate("role/source", nodeContribute, XPathConstants.STRING); String contributeRoleValue = (String) xpath.evaluate("role/value", nodeContribute, XPathConstants.STRING); @@ -995,7 +995,7 @@ private String adaptValue(String value) { } @Override - public HashMap getProperties() { + public Map getProperties() { return toSafeMap; } diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/RecordHandlerMods.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/RecordHandlerMods.java index 46bb66837a..b2a40b241d 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/RecordHandlerMods.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/RecordHandlerMods.java @@ -8,6 +8,7 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; +import java.util.Map; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; @@ -41,7 +42,7 @@ public class RecordHandlerMods implements RecordHandlerInterface { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); String metadataSetId = null; - HashMap toSafeMap = new HashMap(); + Map toSafeMap = new HashMap<>(); public RecordHandlerMods(String metadataSetId) { if(metadataSetId == null || metadataSetId.trim().equals("")){ @@ -75,7 +76,7 @@ public void handleRecord(Node nodeRecord, String cursor, String set) throws Thro String keywords = (String) xpath.evaluate("subject/topic", nodeMods, XPathConstants.STRING); if(keywords != null) { String[] splitted = keywords.split(","); - List kws = new ArrayList(); + List kws = new ArrayList<>(); for(String kw : splitted) { kws.add(kw); } @@ -104,7 +105,7 @@ public void handleRecord(Node nodeRecord, String cursor, String set) throws Thro String role = (String) xpath.evaluate("role/roleTerm[@type='text']", contributer.item(i), XPathConstants.STRING); String firstName = (String) xpath.evaluate("namePart[@type='given']", contributer.item(i), XPathConstants.STRING); String lastName = (String) xpath.evaluate("namePart[@type='family']", contributer.item(i), XPathConstants.STRING); - HashMap properties = new HashMap(); + Map properties = new HashMap<>(); properties.put(CCConstants.VCARD_SURNAME, lastName ); properties.put(CCConstants.VCARD_GIVENNAME, firstName ); if(role.equals("Author")) { @@ -171,13 +172,13 @@ private String query(URL url) throws IOException { con.setReadTimeout(5000); con.connect(); - String result = IOUtils.toString(con.getInputStream(), StandardCharsets.UTF_8.name()); + String result = IOUtils.toString(con.getInputStream(), StandardCharsets.UTF_8); con.disconnect(); return result; } @Override - public HashMap getProperties() { + public Map getProperties() { // TODO Auto-generated method stub return toSafeMap; } diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/RecordHandlerStatic.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/RecordHandlerStatic.java index 1017c4c8a0..aee545461e 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/RecordHandlerStatic.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/RecordHandlerStatic.java @@ -2,20 +2,21 @@ import java.util.HashMap; import java.util.List; +import java.util.Map; /** * dummy class to wrap a property list into an record handler */ public class RecordHandlerStatic implements RecordHandlerInterfaceBase { - private final HashMap props; + private final Map props; - public RecordHandlerStatic(HashMap props) { + public RecordHandlerStatic(Map props) { this.props=props; } @Override - public HashMap getProperties() { + public Map getProperties() { return props; } } diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/SerloImporter.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/SerloImporter.java index 3c4577e94e..a107951a19 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/SerloImporter.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/SerloImporter.java @@ -130,7 +130,7 @@ public void startImport() throws Throwable { for(int i = 0; i < ja.size(); i++){ - HashMap eduProps = new HashMap(); + Map eduProps = new HashMap<>(); JSONObject jo = (JSONObject)ja.get(i); @@ -160,7 +160,7 @@ public void startImport() throws Throwable { eduProps.put(CCConstants.CM_NAME, name); eduProps.put(CCConstants.LOM_PROP_GENERAL_DESCRIPTION, (String) jo.get("description")); - List generalKeywords = new ArrayList(); + List generalKeywords = new ArrayList<>(); if(jo.get("keywords") instanceof JSONObject){ JSONObject kw = (JSONObject)jo.get("keywords"); for(Object valueKW: kw.values()){ @@ -272,7 +272,7 @@ public void startImport() throws Throwable { eduProps.put(CCConstants.CCM_PROP_IO_COMMONLICENSE_KEY, CCConstants.COMMON_LICENSE_CC_BY_SA); - HashMap serloContributer = new HashMap(); + Map serloContributer = new HashMap<>(); serloContributer.put(CCConstants.VCARD_SURNAME, "serlo"); serloContributer.put(CCConstants.VCARD_ORG, "serlo"); serloContributer.put(CCConstants.VCARD_EMAIL, "info-de@serlo.org"); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/WpImporter.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/WpImporter.java index ec816265c0..a1806c7ddc 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/WpImporter.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/WpImporter.java @@ -2,10 +2,7 @@ import java.lang.reflect.Constructor; import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.List; +import java.util.*; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.http.client.methods.HttpGet; @@ -57,7 +54,7 @@ public List getPostTags(Integer postId){ String result = new HttpQueryTool().query(url); - List generalKeywords = new ArrayList(); + List generalKeywords = new ArrayList<>(); try{ JSONArray ja = (JSONArray) new JSONParser().parse(result); @@ -130,7 +127,7 @@ public void startImport() throws Throwable { for(int i = 0; i < ja.size(); i++){ - HashMap eduProps = new HashMap(); + Map eduProps = new HashMap<>(); JSONObject jo = (JSONObject)ja.get(i); eduProps.put(CCConstants.CCM_PROP_IO_REPLICATIONSOURCE,"wp"); @@ -167,7 +164,7 @@ public void startImport() throws Throwable { eduProps.put(CCConstants.CCM_PROP_IO_COMMONLICENSE_KEY, CCConstants.COMMON_LICENSE_CC_BY_SA); - HashMap wpContributer = new HashMap(); + Map wpContributer = new HashMap<>(); wpContributer.put(CCConstants.VCARD_SURNAME, "wordpress"); wpContributer.put(CCConstants.VCARD_ORG, "wordpress"); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/collections/CollectionImporter.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/collections/CollectionImporter.java index d094e80882..17dc26296d 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/collections/CollectionImporter.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/collections/CollectionImporter.java @@ -23,6 +23,7 @@ import java.net.URL; import java.net.URLConnection; import java.util.HashMap; +import java.util.Map; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; @@ -126,7 +127,7 @@ private String createCollection(String parentId, Collections.Collection collecti // set custom collection properties if(collection.getProperty()!=null) { - HashMap properties=new HashMap<>(); + Map properties=new HashMap<>(); for(Property property : collection.getProperty()) { properties.put(property.getKey(),property.getValue().toArray(new String[0])); } diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/collections/xmlclasses/Collections.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/collections/xmlclasses/Collections.java index 4eafbd09df..3d0db0c17b 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/collections/xmlclasses/Collections.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/collections/xmlclasses/Collections.java @@ -417,7 +417,7 @@ public static class Property { */ public List getValue() { if (value == null) { - value = new ArrayList(); + value = new ArrayList<>(); } return this.value; } diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/sax/ListIdentifiersHandler.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/sax/ListIdentifiersHandler.java index 0c42af5adb..754ec3aabe 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/sax/ListIdentifiersHandler.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/sax/ListIdentifiersHandler.java @@ -36,7 +36,7 @@ public class ListIdentifiersHandler extends DefaultHandler { Logger logger = Logger.getLogger(ListIdentifiersHandler.class); - List openedElements = new ArrayList(); + List openedElements = new ArrayList<>(); String currentValue = null; String currentResumptionToken = null; diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/sax/RecordHandlerLOM.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/sax/RecordHandlerLOM.java index ab63c9bde4..f4e1824de9 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/sax/RecordHandlerLOM.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/importer/sax/RecordHandlerLOM.java @@ -1,6 +1,5 @@ package org.edu_sharing.repository.server.importer.sax; -import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; @@ -10,7 +9,6 @@ import org.apache.log4j.Logger; import org.edu_sharing.repository.client.tools.CCConstants; -import org.edu_sharing.repository.server.tools.HttpQueryTool; import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; import org.xml.sax.InputSource; @@ -19,402 +17,402 @@ import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLReaderFactory; -public class RecordHandlerLOM implements RecordHandlerInterface, ContentHandler{ - - Logger logger = Logger.getLogger(RecordHandlerLOM.class); - - String metadataSetId = null; - - String cursor = null; - String set = null; - - String currentValue = null; - Attributes currentAtts = null; - - boolean currentRecordIsDeleted = false; - - String error = null; - String errorCode = null; - - //specialAtts - String currentContributeRole = null; - String currentContributeEntity = null; - - String currentRelationKind = null; - String currentRelationDescription = null; - - HashMap properties = new HashMap(); - - public RecordHandlerLOM( String metadataSetId) { - this.metadataSetId = metadataSetId; - if(this.metadataSetId == null){ - this.metadataSetId = "default"; - } - - } - - List openedElements = new ArrayList(); - - @Override - public void handleRecord(InputStream isRecord) throws SAXException, IOException { - XMLReader xmlReader = XMLReaderFactory.createXMLReader(); - - // Stream to xml file - InputSource inputSource = new InputSource(isRecord); - - xmlReader.setContentHandler(this); - - // Start parsing - xmlReader.parse(inputSource); - } - - @Override - public void startDocument() throws SAXException { - } - - @Override - public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { - - currentValue = ""; - openedElements.add(localName); - currentAtts = atts; - - - String parentLocalName = (openedElements.size() > 1) ? openedElements.get(openedElements.size() - 2).toLowerCase() : ""; - String lowerLocalName = localName.toLowerCase(); - - if(parentLocalName.equals("record") && lowerLocalName.equals("header")){ - - String status = currentAtts.getValue("status"); - if(status != null && status.trim().equals("deleted")){ - currentRecordIsDeleted = true; - } - } - - } - - @Override - public void endElement(String uri, String localName, String qName) throws SAXException { - - currentValue = currentValue.trim(); - - String parentLocalName = (openedElements.size() > 1) ? openedElements.get(openedElements.size() - 2).toLowerCase() : ""; - - String grandParentLocalName = (openedElements.size() > 2) ? openedElements.get(openedElements.size() - 3).toLowerCase() : ""; - - String grandGrandParentLocalName = (openedElements.size() > 3) ? openedElements.get(openedElements.size() - 4).toLowerCase() : ""; - - String lowerLocalName = localName.toLowerCase(); - - //reset deleted status - if( parentLocalName.equals("record") && lowerLocalName.equals("header")){ - currentRecordIsDeleted = false; - } - - if(parentLocalName.equals("oai-pmh") && lowerLocalName.equals("error")){ - this.error = currentValue; - this.errorCode = currentAtts.getValue("code"); - } - - if(parentLocalName.equals("header") && lowerLocalName.equals("identifier")){ - handleSingleValue(CCConstants.CCM_PROP_IO_REPLICATIONSOURCEID); - } - - if(parentLocalName.equals("header") && lowerLocalName.equals("datestamp")){ - handleSingleValue(CCConstants.CCM_PROP_IO_REPLICATIONSOURCETIMESTAMP); - } - - /** - * general - */ - if(parentLocalName.equals("identifier") && lowerLocalName.equals("catalog")){ - handleSingleValue(CCConstants.CCM_PROP_IO_REPLICATIONSOURCE); - } - - if(grandParentLocalName.equals("general") && parentLocalName.equals("title") && lowerLocalName.equals("string")){ - handleMultiLangValue(CCConstants.LOM_PROP_GENERAL_TITLE); - } - - if(parentLocalName.equals("general") && lowerLocalName.equals("language")){ - handleMultiValue(CCConstants.LOM_PROP_GENERAL_LANGUAGE); - } - - if(grandParentLocalName.equals("general") && parentLocalName.equals("description") && lowerLocalName.equals("string")){ - handleMultiLangValue(CCConstants.LOM_PROP_GENERAL_DESCRIPTION); - } - - if(grandParentLocalName.equals("general") && parentLocalName.equals("keyword") && lowerLocalName.equals("string")){ - handleMultiValueMultiLang(CCConstants.LOM_PROP_GENERAL_KEYWORD); - } - - //@TODO structure - //@TODO aggregationLevel - - /** - * lifeCycle - */ - if(grandParentLocalName.equals("lifecycle") && parentLocalName.equals("version") && lowerLocalName.equals("string")){ - handleMultiLangValue(CCConstants.LOM_PROP_LIFECYCLE_VERSION); - } - - if(grandParentLocalName.equals("lifecycle") && parentLocalName.equals("status") && lowerLocalName.equals("value")){ - handleSingleValue(CCConstants.LOM_PROP_LIFECYCLE_STATUS); - } - - if(grandGrandParentLocalName.equals("lifecycle") && grandParentLocalName.equals("contribute") && parentLocalName.equals("role") && lowerLocalName.equals("value")){ - currentContributeRole = currentValue; - handleLCContributer(); - } - - if(grandParentLocalName.equals("lifecycle") && parentLocalName.equals("contribute") && lowerLocalName.equals("entity")){ - currentContributeEntity = currentValue; - handleLCContributer(); - } - - /** - * metadata - */ - if(grandGrandParentLocalName.equals("metametadata") && grandParentLocalName.equals("contribute") && parentLocalName.equals("role") && lowerLocalName.equals("value")){ - currentContributeRole = currentValue; - handleMDContributer(); - } - - if(grandParentLocalName.equals("metametadata") && parentLocalName.equals("contribute") && lowerLocalName.equals("entity")){ - currentContributeEntity = currentValue; - handleMDContributer(); - } - - /** - * technical - */ - if(parentLocalName.equals("technical") && lowerLocalName.equals("format")){ - handleSingleValue(CCConstants.LOM_PROP_TECHNICAL_FORMAT); - } - if(parentLocalName.equals("technical") && lowerLocalName.equals("location")){ - handleSingleValue(CCConstants.LOM_PROP_TECHNICAL_LOCATION); - } - - /** - * educational - */ - if(grandParentLocalName.equals("educational") && parentLocalName.equals("learningresourcetype") && lowerLocalName.equals("value")){ - handleMultiValue(CCConstants.CCM_PROP_IO_REPL_EDUCATIONAL_LEARNINGRESSOURCETYPE); - } - - if(grandParentLocalName.equals("educational") && parentLocalName.equals("intendedenduserrole") && lowerLocalName.equals("value")){ - handleMultiValue(CCConstants.CCM_PROP_IO_REPL_EDUCATIONAL_INTENDEDENDUSERROLE); - } - - if(grandParentLocalName.equals("educational") && parentLocalName.equals("context") && lowerLocalName.equals("value")){ - handleMultiValue(CCConstants.CCM_PROP_IO_REPL_EDUCATIONAL_CONTEXT); - } - - if(grandParentLocalName.equals("educational") && parentLocalName.equals("typicalagerange") && lowerLocalName.equals("string")){ - handleMultiLangValue(CCConstants.CCM_PROP_IO_REPL_EDUCATIONAL_TYPICALAGERANGE); - } - - if(parentLocalName.equals("educational") && lowerLocalName.equals("language")){ - handleMultiValue(CCConstants.CCM_PROP_IO_REPL_EDUCATIONAL_LANGUAGE); - } - - /** - * rights - */ - if(grandParentLocalName.equals("rights") && parentLocalName.equals("copyrightandotherrestrictions") && lowerLocalName.equals("value")){ - if (currentValue.equals("yes") || currentValue.equals("no")) { - Boolean copyRightValBool = (currentValue.equals("yes")) ? true : false; - handleSingleValue(CCConstants.LOM_PROP_RIGHTS_COPY_RIGHT, copyRightValBool.toString()); - } else { - logger.info("unknown value for copyRightVal:" + currentValue); - } - } - - if(grandParentLocalName.equals("rights") && parentLocalName.equals("description") && lowerLocalName.equals("string")){ - handleMultiLangValue(CCConstants.LOM_PROP_RIGHTS_RIGHTS_DESCRIPTION); - } - - /** - * relation - */ - if(grandParentLocalName.equals("relation") && parentLocalName.equals("kind") && lowerLocalName.equals("value")){ - currentRelationKind = currentValue; - } - - if(grandGrandParentLocalName.equals("relation") && grandParentLocalName.equals("resource") && parentLocalName.equals("description") && lowerLocalName.equals("string")){ - currentRelationDescription = currentValue; - } - - /** - * classification - */ - - if(grandParentLocalName.equals("taxonpath") && parentLocalName.equals("taxon") && lowerLocalName.equals("id")){ - - handleMultiValue(CCConstants.CCM_PROP_IO_REPL_TAXON_ID); - } - - if(grandGrandParentLocalName.equals("taxonpath") && grandParentLocalName.equals("taxon") && parentLocalName.equals("entry") && lowerLocalName.equals("string")){ - - handleMultiValueMultiLang(CCConstants.CCM_PROP_IO_REPL_TAXON_ENTRY); - } - - //cleanup stack - if(openedElements.get(openedElements.size() - 1).equals(localName)){ - logger.debug("will remove "+localName+ " from stack"); - openedElements.remove(openedElements.size() - 1); - - }else{ - String message = "something went wrong closed element is not the last on stack."; - logger.error(message); - throw new SAXException(message); - } - - } - - @Override - public void endDocument() throws SAXException { - - if(error != null){ - logger.error("error:"+error+" errorcode:"+errorCode); - - properties.clear(); - return; - } - - if(currentRecordIsDeleted ){ - logger.info("current record is deleted" + properties.get(CCConstants.CCM_PROP_IO_REPLICATIONSOURCEID)); - properties.clear(); - return; - } - - properties.put(CCConstants.CM_PROP_METADATASET_EDU_METADATASET, this.metadataSetId); - - } - - - @Override - public void characters(char[] ch, int start, int length) throws SAXException { - currentValue += new String(ch, start, length); - } - - - @Override - public void endPrefixMapping(String prefix) throws SAXException { - } - - @Override - public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException { - } - - @Override - public void processingInstruction(String target, String data) throws SAXException { - } - - @Override - public void setDocumentLocator(Locator locator) { - } - - @Override - public void skippedEntity(String name) throws SAXException { - } - - @Override - public void startPrefixMapping(String prefix, String uri) throws SAXException { - } - - private String adaptValue(String value) { - logger.debug("starting"); - String result = org.htmlparser.util.Translate.decode(value); - logger.debug("returning"); - return result; - } - - protected void handleSingleValue(String alfKey){ - handleSingleValue(alfKey, currentValue); - } - - protected void handleSingleValue(String alfKey, String value){ - properties.put(alfKey, value); - } - - protected void handleMultiLangValue(String alfKey){ - HashMap propertyVal = (HashMap)properties.get(alfKey); - if(propertyVal == null) propertyVal = new HashMap(); - String language = currentAtts.getValue("language"); - if(language != null && currentValue != null){ - - // country is needed so that i18n is working properly - if (language.length() == 2) { - language = language + "_" + language.toUpperCase(); - } - - propertyVal.put(language, adaptValue(currentValue)); - properties.put(alfKey, propertyVal); - } - } - - protected void handleMultiValue(String alfKey){ - handleMultiValue(alfKey, currentValue); - } - - protected void handleMultiValue(String alfKey, String value){ - List propertyValue = (List)properties.get(alfKey); - if(propertyValue == null){ - propertyValue = new ArrayList(); - } - propertyValue.add(value); - properties.put(alfKey, propertyValue); - } - - protected void handleMultiValueMultiLang(String alfKey){ - List> propertyValue = (List> )properties.get(alfKey); - if(propertyValue == null){ - propertyValue = new ArrayList>(); - } - - String language = currentAtts.getValue("language"); - if(language != null && currentValue != null){ - // country is needed so that i18n is working properly - if (language.length() == 2) { - language = language + "_" + language.toUpperCase(); - } - - HashMap mlVal = new HashMap(); - mlVal.put(language, adaptValue(currentValue)); - propertyValue.add(mlVal); - properties.put(alfKey, propertyValue); - } - } - - protected void handleLCContributer(){ - if(currentContributeRole != null && currentContributeEntity != null){ - String lc_property = CCConstants.getLifecycleContributerProp(currentContributeRole.trim()); - if(lc_property != null && !lc_property.trim().equals("")){ - handleMultiValue(lc_property,currentContributeEntity); - }else{ - logger.warn("can not map lifecycle contributer role "+currentContributeRole+" to edu-sharing property"); - } - - currentContributeRole = null; - currentContributeEntity = null; - } - } - - protected void handleMDContributer(){ - if(currentContributeRole != null && currentContributeEntity != null){ - String lc_property = CCConstants.getMetadataContributerProp(currentContributeRole.trim()); - if(lc_property != null && !lc_property.trim().equals("")){ - handleMultiValue(lc_property,currentContributeEntity); - }else{ - logger.warn("can not map lifecycle contributer role "+currentContributeRole+" to edu-sharing property"); - } - - currentContributeRole = null; - currentContributeEntity = null; - } - } - - public HashMap getProperties() { - return properties; - } +public class RecordHandlerLOM implements RecordHandlerInterface, ContentHandler { + + Logger logger = Logger.getLogger(RecordHandlerLOM.class); + + String metadataSetId = null; + + String cursor = null; + String set = null; + + String currentValue = null; + Attributes currentAtts = null; + + boolean currentRecordIsDeleted = false; + + String error = null; + String errorCode = null; + + //specialAtts + String currentContributeRole = null; + String currentContributeEntity = null; + + String currentRelationKind = null; + String currentRelationDescription = null; + + Map properties = new HashMap<>(); + + public RecordHandlerLOM(String metadataSetId) { + this.metadataSetId = metadataSetId; + if (this.metadataSetId == null) { + this.metadataSetId = "default"; + } + + } + + List openedElements = new ArrayList<>(); + + @Override + public void handleRecord(InputStream isRecord) throws SAXException, IOException { + XMLReader xmlReader = XMLReaderFactory.createXMLReader(); + + // Stream to xml file + InputSource inputSource = new InputSource(isRecord); + + xmlReader.setContentHandler(this); + + // Start parsing + xmlReader.parse(inputSource); + } + + @Override + public void startDocument() throws SAXException { + } + + @Override + public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { + + currentValue = ""; + openedElements.add(localName); + currentAtts = atts; + + + String parentLocalName = (openedElements.size() > 1) ? openedElements.get(openedElements.size() - 2).toLowerCase() : ""; + String lowerLocalName = localName.toLowerCase(); + + if (parentLocalName.equals("record") && lowerLocalName.equals("header")) { + + String status = currentAtts.getValue("status"); + if (status != null && status.trim().equals("deleted")) { + currentRecordIsDeleted = true; + } + } + + } + + @Override + public void endElement(String uri, String localName, String qName) throws SAXException { + + currentValue = currentValue.trim(); + + String parentLocalName = (openedElements.size() > 1) ? openedElements.get(openedElements.size() - 2).toLowerCase() : ""; + + String grandParentLocalName = (openedElements.size() > 2) ? openedElements.get(openedElements.size() - 3).toLowerCase() : ""; + + String grandGrandParentLocalName = (openedElements.size() > 3) ? openedElements.get(openedElements.size() - 4).toLowerCase() : ""; + + String lowerLocalName = localName.toLowerCase(); + + //reset deleted status + if (parentLocalName.equals("record") && lowerLocalName.equals("header")) { + currentRecordIsDeleted = false; + } + + if (parentLocalName.equals("oai-pmh") && lowerLocalName.equals("error")) { + this.error = currentValue; + this.errorCode = currentAtts.getValue("code"); + } + + if (parentLocalName.equals("header") && lowerLocalName.equals("identifier")) { + handleSingleValue(CCConstants.CCM_PROP_IO_REPLICATIONSOURCEID); + } + + if (parentLocalName.equals("header") && lowerLocalName.equals("datestamp")) { + handleSingleValue(CCConstants.CCM_PROP_IO_REPLICATIONSOURCETIMESTAMP); + } + + /** + * general + */ + if (parentLocalName.equals("identifier") && lowerLocalName.equals("catalog")) { + handleSingleValue(CCConstants.CCM_PROP_IO_REPLICATIONSOURCE); + } + + if (grandParentLocalName.equals("general") && parentLocalName.equals("title") && lowerLocalName.equals("string")) { + handleMultiLangValue(CCConstants.LOM_PROP_GENERAL_TITLE); + } + + if (parentLocalName.equals("general") && lowerLocalName.equals("language")) { + handleMultiValue(CCConstants.LOM_PROP_GENERAL_LANGUAGE); + } + + if (grandParentLocalName.equals("general") && parentLocalName.equals("description") && lowerLocalName.equals("string")) { + handleMultiLangValue(CCConstants.LOM_PROP_GENERAL_DESCRIPTION); + } + + if (grandParentLocalName.equals("general") && parentLocalName.equals("keyword") && lowerLocalName.equals("string")) { + handleMultiValueMultiLang(CCConstants.LOM_PROP_GENERAL_KEYWORD); + } + + //@TODO structure + //@TODO aggregationLevel + + /** + * lifeCycle + */ + if (grandParentLocalName.equals("lifecycle") && parentLocalName.equals("version") && lowerLocalName.equals("string")) { + handleMultiLangValue(CCConstants.LOM_PROP_LIFECYCLE_VERSION); + } + + if (grandParentLocalName.equals("lifecycle") && parentLocalName.equals("status") && lowerLocalName.equals("value")) { + handleSingleValue(CCConstants.LOM_PROP_LIFECYCLE_STATUS); + } + + if (grandGrandParentLocalName.equals("lifecycle") && grandParentLocalName.equals("contribute") && parentLocalName.equals("role") && lowerLocalName.equals("value")) { + currentContributeRole = currentValue; + handleLCContributer(); + } + + if (grandParentLocalName.equals("lifecycle") && parentLocalName.equals("contribute") && lowerLocalName.equals("entity")) { + currentContributeEntity = currentValue; + handleLCContributer(); + } + + /** + * metadata + */ + if (grandGrandParentLocalName.equals("metametadata") && grandParentLocalName.equals("contribute") && parentLocalName.equals("role") && lowerLocalName.equals("value")) { + currentContributeRole = currentValue; + handleMDContributer(); + } + + if (grandParentLocalName.equals("metametadata") && parentLocalName.equals("contribute") && lowerLocalName.equals("entity")) { + currentContributeEntity = currentValue; + handleMDContributer(); + } + + /** + * technical + */ + if (parentLocalName.equals("technical") && lowerLocalName.equals("format")) { + handleSingleValue(CCConstants.LOM_PROP_TECHNICAL_FORMAT); + } + if (parentLocalName.equals("technical") && lowerLocalName.equals("location")) { + handleSingleValue(CCConstants.LOM_PROP_TECHNICAL_LOCATION); + } + + /** + * educational + */ + if (grandParentLocalName.equals("educational") && parentLocalName.equals("learningresourcetype") && lowerLocalName.equals("value")) { + handleMultiValue(CCConstants.CCM_PROP_IO_REPL_EDUCATIONAL_LEARNINGRESSOURCETYPE); + } + + if (grandParentLocalName.equals("educational") && parentLocalName.equals("intendedenduserrole") && lowerLocalName.equals("value")) { + handleMultiValue(CCConstants.CCM_PROP_IO_REPL_EDUCATIONAL_INTENDEDENDUSERROLE); + } + + if (grandParentLocalName.equals("educational") && parentLocalName.equals("context") && lowerLocalName.equals("value")) { + handleMultiValue(CCConstants.CCM_PROP_IO_REPL_EDUCATIONAL_CONTEXT); + } + + if (grandParentLocalName.equals("educational") && parentLocalName.equals("typicalagerange") && lowerLocalName.equals("string")) { + handleMultiLangValue(CCConstants.CCM_PROP_IO_REPL_EDUCATIONAL_TYPICALAGERANGE); + } + + if (parentLocalName.equals("educational") && lowerLocalName.equals("language")) { + handleMultiValue(CCConstants.CCM_PROP_IO_REPL_EDUCATIONAL_LANGUAGE); + } + + /** + * rights + */ + if (grandParentLocalName.equals("rights") && parentLocalName.equals("copyrightandotherrestrictions") && lowerLocalName.equals("value")) { + if (currentValue.equals("yes") || currentValue.equals("no")) { + Boolean copyRightValBool = (currentValue.equals("yes")) ? true : false; + handleSingleValue(CCConstants.LOM_PROP_RIGHTS_COPY_RIGHT, copyRightValBool.toString()); + } else { + logger.info("unknown value for copyRightVal:" + currentValue); + } + } + + if (grandParentLocalName.equals("rights") && parentLocalName.equals("description") && lowerLocalName.equals("string")) { + handleMultiLangValue(CCConstants.LOM_PROP_RIGHTS_RIGHTS_DESCRIPTION); + } + + /** + * relation + */ + if (grandParentLocalName.equals("relation") && parentLocalName.equals("kind") && lowerLocalName.equals("value")) { + currentRelationKind = currentValue; + } + + if (grandGrandParentLocalName.equals("relation") && grandParentLocalName.equals("resource") && parentLocalName.equals("description") && lowerLocalName.equals("string")) { + currentRelationDescription = currentValue; + } + + /** + * classification + */ + + if (grandParentLocalName.equals("taxonpath") && parentLocalName.equals("taxon") && lowerLocalName.equals("id")) { + + handleMultiValue(CCConstants.CCM_PROP_IO_REPL_TAXON_ID); + } + + if (grandGrandParentLocalName.equals("taxonpath") && grandParentLocalName.equals("taxon") && parentLocalName.equals("entry") && lowerLocalName.equals("string")) { + + handleMultiValueMultiLang(CCConstants.CCM_PROP_IO_REPL_TAXON_ENTRY); + } + + //cleanup stack + if (openedElements.get(openedElements.size() - 1).equals(localName)) { + logger.debug("will remove " + localName + " from stack"); + openedElements.remove(openedElements.size() - 1); + + } else { + String message = "something went wrong closed element is not the last on stack."; + logger.error(message); + throw new SAXException(message); + } + + } + + @Override + public void endDocument() throws SAXException { + + if (error != null) { + logger.error("error:" + error + " errorcode:" + errorCode); + + properties.clear(); + return; + } + + if (currentRecordIsDeleted) { + logger.info("current record is deleted" + properties.get(CCConstants.CCM_PROP_IO_REPLICATIONSOURCEID)); + properties.clear(); + return; + } + + properties.put(CCConstants.CM_PROP_METADATASET_EDU_METADATASET, this.metadataSetId); + + } + + + @Override + public void characters(char[] ch, int start, int length) throws SAXException { + currentValue += new String(ch, start, length); + } + + + @Override + public void endPrefixMapping(String prefix) throws SAXException { + } + + @Override + public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException { + } + + @Override + public void processingInstruction(String target, String data) throws SAXException { + } + + @Override + public void setDocumentLocator(Locator locator) { + } + + @Override + public void skippedEntity(String name) throws SAXException { + } + + @Override + public void startPrefixMapping(String prefix, String uri) throws SAXException { + } + + private String adaptValue(String value) { + logger.debug("starting"); + String result = org.htmlparser.util.Translate.decode(value); + logger.debug("returning"); + return result; + } + + protected void handleSingleValue(String alfKey) { + handleSingleValue(alfKey, currentValue); + } + + protected void handleSingleValue(String alfKey, String value) { + properties.put(alfKey, value); + } + + protected void handleMultiLangValue(String alfKey) { + Map propertyVal = (Map) properties.get(alfKey); + if (propertyVal == null) propertyVal = new HashMap<>(); + String language = currentAtts.getValue("language"); + if (language != null && currentValue != null) { + + // country is needed so that i18n is working properly + if (language.length() == 2) { + language = language + "_" + language.toUpperCase(); + } + + propertyVal.put(language, adaptValue(currentValue)); + properties.put(alfKey, propertyVal); + } + } + + protected void handleMultiValue(String alfKey) { + handleMultiValue(alfKey, currentValue); + } + + protected void handleMultiValue(String alfKey, String value) { + List propertyValue = (List) properties.get(alfKey); + if (propertyValue == null) { + propertyValue = new ArrayList<>(); + } + propertyValue.add(value); + properties.put(alfKey, propertyValue); + } + + protected void handleMultiValueMultiLang(String alfKey) { + List> propertyValue = (List>) properties.get(alfKey); + if (propertyValue == null) { + propertyValue = new ArrayList>(); + } + + String language = currentAtts.getValue("language"); + if (language != null && currentValue != null) { + // country is needed so that i18n is working properly + if (language.length() == 2) { + language = language + "_" + language.toUpperCase(); + } + + Map mlVal = new HashMap<>(); + mlVal.put(language, adaptValue(currentValue)); + propertyValue.add(mlVal); + properties.put(alfKey, propertyValue); + } + } + + protected void handleLCContributer() { + if (currentContributeRole != null && currentContributeEntity != null) { + String lc_property = CCConstants.getLifecycleContributerProp(currentContributeRole.trim()); + if (lc_property != null && !lc_property.trim().equals("")) { + handleMultiValue(lc_property, currentContributeEntity); + } else { + logger.warn("can not map lifecycle contributer role " + currentContributeRole + " to edu-sharing property"); + } + + currentContributeRole = null; + currentContributeEntity = null; + } + } + + protected void handleMDContributer() { + if (currentContributeRole != null && currentContributeEntity != null) { + String lc_property = CCConstants.getMetadataContributerProp(currentContributeRole.trim()); + if (lc_property != null && !lc_property.trim().equals("")) { + handleMultiValue(lc_property, currentContributeEntity); + } else { + logger.warn("can not map lifecycle contributer role " + currentContributeRole + " to edu-sharing property"); + } + + currentContributeRole = null; + currentContributeEntity = null; + } + } + + public Map getProperties() { + return properties; + } } diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/helper/NodeHelper.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/helper/NodeHelper.java index e0f0b231ee..c0a19179d6 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/helper/NodeHelper.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/helper/NodeHelper.java @@ -25,8 +25,8 @@ public class NodeHelper { * @param startFolder * @return map with ccm:replicationSourceId as key and nodeRef as value */ - public HashMap getImportedNodes(String startFolder) { - HashMap result = new HashMap<>(); + public Map getImportedNodes(String startFolder) { + Map result = new HashMap<>(); int processNodes = runTask(startFolder,(ref) -> { String replicationSourceId = (String) serviceRegistry.getNodeService().getProperty(ref, QName.createQName(CCConstants.CCM_PROP_IO_REPLICATIONSOURCEID)); if (replicationSourceId != null) { @@ -42,7 +42,7 @@ public HashMap getImportedNodes(String startFolder) { * @return map with duplicates: ccm:replicationSourceId as key and list of nodeRef as value */ public Map> getDuplicatedImportedNodes(String startFolder){ - Map> collect = new HashMap>(); + Map> collect = new HashMap<>(); int processNodes = runTask(startFolder,(ref)->{ String replicationSourceId = (String) serviceRegistry.getNodeService().getProperty(ref, QName.createQName(CCConstants.CCM_PROP_IO_REPLICATIONSOURCEID)); if (replicationSourceId != null && !replicationSourceId.trim().equals("")) { diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/AbstractJob.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/AbstractJob.java index 506382ecb3..8494d704bf 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/AbstractJob.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/AbstractJob.java @@ -30,6 +30,7 @@ import java.util.ArrayList; import java.util.Arrays; +import lombok.Getter; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.edu_sharing.repository.server.jobs.quartz.annotation.JobDescription; @@ -42,13 +43,10 @@ public abstract class AbstractJob implements Job,InterruptableJob { boolean isStarted = false; - protected JobDataMap jobDataMap; + @Getter + protected JobDataMap jobDataMap; - public JobDataMap getJobDataMap() { - return jobDataMap; - } - - protected Class[] allJobs = new Class[] { ImporterJob.class, RefreshCacheJob.class,RemoveDeletedImportsJob.class,RemoveImportedObjectsJob.class,GetAllDamagedObjects.class,RefreshPublisherListJob.class, TrackingJob.class, ExporterJob.class}; + protected Class[] allJobs = new Class[] { ImporterJob.class, RefreshCacheJob.class,RemoveDeletedImportsJob.class,RemoveImportedObjectsJob.class,GetAllDamagedObjects.class,RefreshPublisherListJob.class, TrackingJob.class, ExporterJob.class}; protected boolean isInterrupted=false; //important for immediate executed Jobs so that we can give an user feedback if the job was vetoed @@ -62,15 +60,15 @@ public void setStarted(boolean isStarted) { this.isStarted = isStarted; } - public Class[] getJobClasses() { + public Class[] getJobClasses() { // TODO Auto-generated method stub return allJobs; } - protected synchronized void addJobClass(Class job) { + protected synchronized void addJobClass(Class job) { if(!Arrays.asList(allJobs).contains(job)) { - ArrayList list = new ArrayList(Arrays.asList(allJobs)); + ArrayList> list = new ArrayList<>(Arrays.asList(allJobs)); list.add(job); - allJobs = list.toArray(new Class[list.size()]); + allJobs = list.toArray(new Class[0]); } } diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/AssignedLicenseManagerJob.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/AssignedLicenseManagerJob.java index a12f430488..04a43a4161 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/AssignedLicenseManagerJob.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/AssignedLicenseManagerJob.java @@ -114,7 +114,7 @@ void manageExpiryDate(ResultSet rs){ } } List mediaCentres = (List)nodeService.getProperty(parentAssocRef.getParentRef(),QName.createQName(CCConstants.CCM_PROP_IO_MEDIACENTER)); - ArrayList newMediacentres = new ArrayList(); + ArrayList newMediacentres = new ArrayList<>(); if(mediaCentres != null){ for(String mediaCentre : mediaCentres){ if(!authority.replace(AuthorityType.GROUP.getPrefixString(), "").equals(mediaCentre)){ @@ -153,7 +153,7 @@ ResultSet fetch(int skipCount, int maxItems){ @Override public Class[] getJobClasses() { // TODO Auto-generated method stub - List allJobs = new ArrayList(Arrays.asList(super.allJobs)); + List allJobs = new ArrayList<>(Arrays.asList(super.allJobs)); allJobs.add(AssignedLicenseManagerJob.class); return allJobs.toArray(new Class[0]); } diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/ExporterJob.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/ExporterJob.java index b145535b32..2577914b8a 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/ExporterJob.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/ExporterJob.java @@ -44,7 +44,7 @@ public void execute(JobExecutionContext context) throws JobExecutionException { ApplicationInfo appInfo = ApplicationInfoList.getHomeRepository(); - HashMap authInfo = new AuthenticationToolAPI().createNewSession(appInfo.getUsername(), appInfo.getPassword()); + Map authInfo = new AuthenticationToolAPI().createNewSession(appInfo.getUsername(), appInfo.getPassword()); MCAlfrescoAPIClient apiClient = new MCAlfrescoAPIClient(authInfo); String[] nodeIds = apiClient.searchNodeIds(luceneFilter); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/FixElasticSearchDeletedNodes.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/FixElasticSearchDeletedNodes.java index 12573f09a8..5e748f57ff 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/FixElasticSearchDeletedNodes.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/FixElasticSearchDeletedNodes.java @@ -196,7 +196,7 @@ private void cleanupSubArray(String dbid, Hit searchHit, List params = new HashMap<>() {{ + Map params = new HashMap<>() {{ put("value", JsonData.of(subArrayName)); }}; diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/FixInitialVersion.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/FixInitialVersion.java index 98e362bf5b..a50698d920 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/FixInitialVersion.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/FixInitialVersion.java @@ -99,7 +99,7 @@ public Void execute() throws Throwable { } Map transformQNameKeyToString(Map props){ - Map result = new HashMap(); + Map result = new HashMap<>(); for(Map.Entry entry : props.entrySet()){ result.put(entry.getKey().toString(), entry.getValue()); } diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/FixNotifyDefaultScope.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/FixNotifyDefaultScope.java index 5aeffe3608..2ebcf7ca03 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/FixNotifyDefaultScope.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/FixNotifyDefaultScope.java @@ -35,8 +35,8 @@ public class FixNotifyDefaultScope extends AbstractJob { BehaviourFilter policyBehaviourFilter = (BehaviourFilter)applicationContext.getBean("policyBehaviourFilter"); PrintWriter out; - ArrayList processedEduGroups = new ArrayList(); - ArrayList eduGroupFolderNodeIds = new ArrayList(); + ArrayList processedEduGroups = new ArrayList<>(); + ArrayList eduGroupFolderNodeIds = new ArrayList<>(); int processedNodeCounter = 0; @@ -96,7 +96,7 @@ void setDefautScope(NodeRef parent, boolean test) throws Throwable{ if(!test){ - Map aspectProps = new HashMap(); + Map aspectProps = new HashMap<>(); aspectProps.put(QName.createQName(CCConstants.CCM_PROP_EDUSCOPE_NAME), null); @@ -115,7 +115,7 @@ public Void execute() throws Throwable { logger.info("updateing Map:"+ noderef +" in "+ nodeService.getPath(child.getChildRef())); if(!test){ - Map aspectProps = new HashMap(); + Map aspectProps = new HashMap<>(); aspectProps.put(QName.createQName(CCConstants.CCM_PROP_EDUSCOPE_NAME), null); serviceRegistry.getRetryingTransactionHelper().doInTransaction(new RetryingTransactionCallback() { @Override diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/ImportFactualTermsFromFileSax.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/ImportFactualTermsFromFileSax.java index 3b3ca0041a..f229aa1b26 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/ImportFactualTermsFromFileSax.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/ImportFactualTermsFromFileSax.java @@ -18,7 +18,7 @@ public class ImportFactualTermsFromFileSax implements ContentHandler { String currentValue = null; Attributes currentAtts = null; - List openedElements = new ArrayList(); + List openedElements = new ArrayList<>(); String currentDatafieldTag = null; @@ -176,7 +176,7 @@ public void handleRecord(InputStream isRecord) throws Throwable { } @Override - public HashMap getProperties() { + public Map getProperties() { return currentProperties; } },"",""); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/ImporterJobSAX.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/ImporterJobSAX.java index 488891feb0..aaca645071 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/ImporterJobSAX.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/ImporterJobSAX.java @@ -60,7 +60,7 @@ protected void start(String urlImport, String oaiBaseUrl, String metadataSetId, @Override public Class[] getJobClasses() { - List classList = new ArrayList(Arrays.asList(allJobs)); + List classList = new ArrayList<>(Arrays.asList(allJobs)); classList.add(ImporterJobSAX.class); return classList.toArray(new Class[classList.size()]); } diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/JobHandler.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/JobHandler.java index 600dddd082..8e34cf427e 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/JobHandler.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/JobHandler.java @@ -179,13 +179,13 @@ public class JobConfig { Class jobClass = null; Trigger trigger = null; - HashMap params = null; + Map params = null; String jobname = null; public JobConfig() { } - public JobConfig(Class jobClass, Trigger trigger, HashMap params, String name) { + public JobConfig(Class jobClass, Trigger trigger, Map params, String name) { this.jobClass = jobClass; this.trigger = trigger; this.params = params; @@ -208,11 +208,11 @@ public void setTrigger(Trigger trigger) { this.trigger = trigger; } - public HashMap getParams() { + public Map getParams() { return params; } - public void setParams(HashMap params) { + public void setParams(Map params) { this.params = params; } @@ -440,7 +440,7 @@ public synchronized void refresh(boolean triggerImmediateJobs) { if (jobName == null || jobName.trim().equals("")) { jobName = clazz.getSimpleName() + "_JobName_" + System.currentTimeMillis(); } - HashMap params = new HashMap<>(); + Map params = new HashMap<>(); if (job.hasPath("params")) { for (Map.Entry configParams : job.getConfig("params").entrySet()) { params.put(configParams.getKey(), configParams.getValue().unwrapped()); @@ -593,7 +593,7 @@ public List getRunningJobs() throws SchedulerException { * @return ImmediateJobListener * @throws SchedulerException */ - public ImmediateJobListener startJob(Class jobClass, HashMap params) throws SchedulerException, Exception { + public ImmediateJobListener startJob(Class jobClass, Map params) throws SchedulerException, Exception { checkPrimaryRepository(); String jobName = jobClass.getSimpleName() + IMMEDIATE_JOBNAME_SUFFIX; @@ -641,7 +641,7 @@ public String[] getJobListenerNames() { return iJobListener; } - public static JobDataMap createJobDataMap(HashMap params) { + public static JobDataMap createJobDataMap(Map params) { JobDataMap jdm = new JobDataMap(); if (params != null && params.size() > 0) { diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/JobLogger.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/JobLogger.java index 7fd7d5808a..cbe7b6763c 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/JobLogger.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/JobLogger.java @@ -23,7 +23,7 @@ public class JobLogger extends AbstractAppender { /** * logs are not shared in cluster for performance reasongs */ - private static HashMap> logs = new HashMap<>(); + private static Map> logs = new HashMap<>(); private final ApplicationContext applicationContext; diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/MediacenterMonthlyReportsJob.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/MediacenterMonthlyReportsJob.java index 5bae62b7aa..4f7d6ff66f 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/MediacenterMonthlyReportsJob.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/MediacenterMonthlyReportsJob.java @@ -22,7 +22,6 @@ import org.edu_sharing.repository.server.tools.NodeTool; import org.edu_sharing.repository.server.tools.UserEnvironmentTool; import org.edu_sharing.repository.server.tools.VCardConverter; -import org.edu_sharing.service.authority.AuthorityService; import org.edu_sharing.service.authority.AuthorityServiceFactory; import org.edu_sharing.service.authority.AuthorityServiceHelper; import org.edu_sharing.service.mediacenter.MediacenterService; @@ -41,11 +40,8 @@ import org.quartz.JobExecutionException; import org.springframework.context.ApplicationContext; -import java.awt.*; import java.io.ByteArrayOutputStream; -import java.io.IOException; import java.io.OutputStreamWriter; -import java.io.Serializable; import java.nio.charset.StandardCharsets; import java.time.LocalDate; import java.time.YearMonth; @@ -56,7 +52,6 @@ import java.util.List; import java.util.stream.Collectors; -import static org.edu_sharing.alfresco.service.AuthorityService.MEDIACENTER_ADMINISTRATORS_GROUP; import static org.edu_sharing.alfresco.service.AuthorityService.ORG_GROUP_PREFIX; @JobDescription(description = "Creates reports for all mediacenters on the 1st of each month for the last month") @@ -358,7 +353,7 @@ private void writeCSVFile(Map entries = new ArrayList(); + ArrayList entries = new ArrayList<>(); for (Map.Entry entry : data.entrySet()) { if(isInterrupted()) { return; @@ -374,7 +369,7 @@ private void writeCSVFile(Map> vcard = VCardConverter.vcardToHashMap(null, prop); + ArrayList> vcard = VCardConverter.vcardToMap(null, prop); if (vcard.size() == 0) { return ""; } diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/MigrateFactualTermsToKeyValue.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/MigrateFactualTermsToKeyValue.java index f13cd6f42e..643e9b8783 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/MigrateFactualTermsToKeyValue.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/MigrateFactualTermsToKeyValue.java @@ -20,10 +20,7 @@ import org.springframework.context.ApplicationContext; import java.io.Serializable; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; +import java.util.*; public class MigrateFactualTermsToKeyValue extends AbstractJob{ @@ -103,7 +100,7 @@ public void run(NodeRef startFolder){ ArrayList displays = new ArrayList<>(); for(String displayName : displayNames){ - List> matches = serviceRegistry.getRetryingTransactionHelper().doInTransaction(()-> ph.getEntriesByDisplayValue(displayName)); + List> matches = serviceRegistry.getRetryingTransactionHelper().doInTransaction(()-> ph.getEntriesByDisplayValue(displayName)); if(matches.size() == 0){ logger.error(n+";no keyword matches;" + displayName); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/MigrationJob.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/MigrationJob.java index 127f5e1571..71601bb19c 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/MigrationJob.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/MigrationJob.java @@ -421,7 +421,7 @@ private void protocolNode(NodeRef authority) { if(nodeEntries == null) { - nodeEntries = new ArrayList(); + nodeEntries = new ArrayList<>(); } nodeEntries.add(authority.getId()); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/NodeDistributionJob.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/NodeDistributionJob.java index af15ef8905..752a765127 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/NodeDistributionJob.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/NodeDistributionJob.java @@ -48,7 +48,7 @@ public void execute(JobExecutionContext context) throws JobExecutionException { ApplicationInfo homeRep = ApplicationInfoList.getHomeRepository(); AuthenticationTool authTool = RepoFactory.getAuthenticationToolInstance(homeRep.getAppId()); - HashMap authInfo = authTool.createNewSession(homeRep.getUsername(), homeRep.getPassword()); + Map authInfo = authTool.createNewSession(homeRep.getUsername(), homeRep.getPassword()); MCAlfrescoBaseClient client = (MCAlfrescoBaseClient) RepoFactory.getInstance(homeRep.getAppId(), authInfo); JobDataMap jobDataMap = context.getJobDetail().getJobDataMap(); @@ -63,7 +63,7 @@ public void execute(JobExecutionContext context) throws JobExecutionException { // request node - HashMap> search = + Map> search = client.search( "PATH:\"" + jobDataMap.getString(JOB_PATH) + "\"", CCConstants.CM_TYPE_FOLDER); @@ -76,16 +76,16 @@ public void execute(JobExecutionContext context) throws JobExecutionException { // request io's - HashMap> children = + Map> children = client.getChildrenByType(rootId, CCConstants.CCM_TYPE_IO); Calendar calendar = Calendar.getInstance(); - Map cache = new HashMap(); + Map cache = new HashMap<>(); - for (Entry> child : children.entrySet()) { + for (Entry> child : children.entrySet()) { String childId = child.getKey(); - HashMap childProps = child.getValue(); + Map childProps = child.getValue(); Date created = new Date(Long.parseLong((String) childProps.get(CCConstants.CM_PROP_C_CREATED))); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/OAIXMLValidatorJob.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/OAIXMLValidatorJob.java index 3857d97eb0..fb7003369f 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/OAIXMLValidatorJob.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/OAIXMLValidatorJob.java @@ -25,7 +25,7 @@ protected void start(String urlImport, String oaiBaseUrl, String metadataSetId, @Override public Class[] getJobClasses() { - List classList = new ArrayList(Arrays.asList(allJobs)); + List classList = new ArrayList<>(Arrays.asList(allJobs)); classList.add(OAIXMLValidatorJob.class); return classList.toArray(new Class[classList.size()]); } diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/ProtocolDiffDBSolrJob.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/ProtocolDiffDBSolrJob.java index 6149c7fc52..77fa711a35 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/ProtocolDiffDBSolrJob.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/ProtocolDiffDBSolrJob.java @@ -74,7 +74,7 @@ private void run(String startFolder){ logger.info("collection db nodes"); List nodesInDb = new NodeHelper().getNodes(startFolder); - List diff = new ArrayList(nodesInDb); + List diff = new ArrayList<>(nodesInDb); diff.removeAll(nodesInSolr); if(diff.size() == 0){ logger.info("no diff between database and solr in this folder " + startFolder); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/RefreshCacheExecuter.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/RefreshCacheExecuter.java index e778327bdf..1aca75a86e 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/RefreshCacheExecuter.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/RefreshCacheExecuter.java @@ -28,6 +28,7 @@ package org.edu_sharing.repository.server.jobs.quartz; import java.util.HashMap; +import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -45,7 +46,7 @@ public class RefreshCacheExecuter { protected Log logger = LogFactory.getLog(RefreshCacheExecuter.class); - public void excecute(String rootFolderId, boolean sticky, HashMap authInfo) throws Throwable { + public void excecute(String rootFolderId, boolean sticky, Map authInfo) throws Throwable { if (authInfo == null) { String userName = ApplicationInfoList.getHomeRepository().getUsername(); String password = ApplicationInfoList.getHomeRepository().getPassword(); @@ -61,7 +62,7 @@ public void excecute(String rootFolderId, boolean sticky, HashMap authInfo) thro MCAlfrescoBaseClient mcAlfrescoBaseClient = (MCAlfrescoBaseClient) mcBaseClient; String repositoryRoot = mcAlfrescoBaseClient.getRepositoryRoot(); String companyHomeId = mcAlfrescoBaseClient.getCompanyHomeNodeId(); - HashMap importFolderProps = mcAlfrescoBaseClient.getChild(companyHomeId, CCConstants.CCM_TYPE_MAP, CCConstants.CM_NAME, + Map importFolderProps = mcAlfrescoBaseClient.getChild(companyHomeId, CCConstants.CCM_TYPE_MAP, CCConstants.CM_NAME, OAIPMHLOMImporter.FOLDER_NAME_IMPORTED_OBJECTS); if (importFolderProps != null) { rootFolderId = (String) importFolderProps.get(CCConstants.SYS_PROP_NODE_UID); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/RefreshPublisherListJob.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/RefreshPublisherListJob.java index 060128364a..a15e19a03f 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/RefreshPublisherListJob.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/RefreshPublisherListJob.java @@ -28,6 +28,7 @@ package org.edu_sharing.repository.server.jobs.quartz; import java.util.HashMap; +import java.util.Map; import org.apache.log4j.Logger; import org.edu_sharing.metadataset.v2.MetadataReader; @@ -77,7 +78,7 @@ public void execute(JobExecutionContext jobContext) throws JobExecutionException ApplicationInfo homeRep = ApplicationInfoList.getHomeRepository(); try{ AuthenticationTool authTool = RepoFactory.getAuthenticationToolInstance(homeRep.getAppId()); - HashMap authInfo = authTool.createNewSession(homeRep.getUsername(), homeRep.getPassword()); + Map authInfo = authTool.createNewSession(homeRep.getUsername(), homeRep.getPassword()); AdminServiceFactory.getInstance().writePublisherToMDSXml(vcardProps, valuespaceProp, ignoreEntries, filePath, authInfo); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/RemoveImportedDuplicates.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/RemoveImportedDuplicates.java index 9f295db453..67c6976339 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/RemoveImportedDuplicates.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/RemoveImportedDuplicates.java @@ -86,7 +86,7 @@ private void excecute(String startFolder, boolean execute, String ignoreModifier QName.createQName(CCConstants.CM_NAME) ) + " " + entry.getValue().stream().map(NodeRef::getId).collect(Collectors.joining(",")) ); - HashMap result = new HashMap<>(); + Map result = new HashMap<>(); for(NodeRef nodeRef : entry.getValue()){ int isInUse = 0; List children = nodeService.getChildAssocs(nodeRef, new HashSet(Arrays.asList(new QName[]{ diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/RepairBrockhausRemoteIosJob.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/RepairBrockhausRemoteIosJob.java index eca387ff3b..68efbb3106 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/RepairBrockhausRemoteIosJob.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/RepairBrockhausRemoteIosJob.java @@ -128,7 +128,7 @@ public void execute(JobExecutionContext context) throws JobExecutionException { SearchResultNodeRef results = searchServiceBrockhaus.search(null, MetadataSet.DEFAULT_CLIENT_QUERY, criteria, token); String finalDescription = (String) description; List filtered = results.getData().stream().filter(r -> { - HashMap props = r.getProperties(); + Map props = r.getProperties(); return ( Objects.equals(props.get(CCConstants.LOM_PROP_GENERAL_TITLE), title) && diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/SetPermissionsOrgAdminGroup.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/SetPermissionsOrgAdminGroup.java index dafd1a6059..d8152d76d0 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/SetPermissionsOrgAdminGroup.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/SetPermissionsOrgAdminGroup.java @@ -64,7 +64,7 @@ private void run(String[] orgs, boolean execute) { public Class[] getJobClasses() { //addJobClass(SetPermissionsOrgAdminGroup.class); - ArrayList al = new ArrayList(Arrays.asList(allJobs)); + ArrayList al = new ArrayList<>(Arrays.asList(allJobs)); al.add(SetPermissionsOrgAdminGroup.class); return al.toArray(new Class[0]) ; } diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/TrashcanCleanerJob.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/TrashcanCleanerJob.java index 5be888e1b2..c6ad5ebbf4 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/TrashcanCleanerJob.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/TrashcanCleanerJob.java @@ -2,6 +2,7 @@ import java.util.Arrays; import java.util.HashMap; +import java.util.Map; import java.util.Map.Entry; import org.alfresco.service.cmr.repository.StoreRef; @@ -81,7 +82,7 @@ void execute() throws Throwable { ApplicationInfo homeRep = ApplicationInfoList.getHomeRepository(); AuthenticationTool authTool = RepoFactory.getAuthenticationToolInstance(homeRep.getAppId()); - HashMap authInfo = authTool.createNewSession(homeRep.getUsername(), homeRep.getPassword()); + Map authInfo = authTool.createNewSession(homeRep.getUsername(), homeRep.getPassword()); MCAlfrescoAPIClient apiClient = (MCAlfrescoAPIClient) RepoFactory.getInstance(null, authInfo); @@ -89,7 +90,7 @@ void execute() throws Throwable { logger.info("Cleaning trashcan starting (timeToKeep: " + timeToKeep + ", batchSize: " + batchSize +")"); - HashMap> childrenByAssociation = + Map> childrenByAssociation = apiClient.getChildrenByAssociation( storeRef, apiClient.getRootNode(storeRef), @@ -102,7 +103,7 @@ void execute() throws Throwable { long now = System.currentTimeMillis(); - for (Entry> entry : childrenByAssociation.entrySet()) { + for (Entry> entry : childrenByAssociation.entrySet()) { String archivedDate = (String) entry.getValue().get(PROP_ARCHIVED_DATE); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/TrashcanCleanerSolr.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/TrashcanCleanerSolr.java index 1d4a891141..fbac8245cc 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/TrashcanCleanerSolr.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/jobs/quartz/TrashcanCleanerSolr.java @@ -34,7 +34,7 @@ public class TrashcanCleanerSolr { private static final int PAGE_SIZE = 100; - List list = new ArrayList(); + List list = new ArrayList<>(); public TrashcanCleanerSolr(long timeToKeep, int batchCount) { this.to = new Date(System.currentTimeMillis() - timeToKeep); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/monitoring/Monitoring.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/monitoring/Monitoring.java index cf2d11a0e4..ccc38b0cf3 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/monitoring/Monitoring.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/monitoring/Monitoring.java @@ -11,6 +11,7 @@ import javax.management.MBeanServer; import javax.management.ObjectInstance; import javax.management.ObjectName; + import jakarta.servlet.ServletException; import jakarta.servlet.ServletOutputStream; import jakarta.servlet.http.HttpServlet; @@ -29,124 +30,121 @@ public class Monitoring extends HttpServlet { - private transient BasicDataSource dataSource = null; - - private static Logger logger = Logger.getLogger(Monitoring.class); - - @Override - public void init() throws ServletException { - ApplicationContext applicationContext = AlfAppContextGate.getApplicationContext(); - dataSource = (BasicDataSource) applicationContext.getBean("defaultDataSource"); - - super.init(); - } - - @Override - protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - - try { - if (!new MCAlfrescoAPIClient().isAdmin()) { - resp.getOutputStream().println("access denied"); - return; - } - - } catch (Exception e) { - e.printStackTrace(); - } - - doIt(resp.getOutputStream()); - } - - - private void doIt(ServletOutputStream outputStream){ - try{ - MonitoringDao dao = new MonitoringDao(); - - - info(outputStream, "**********DATABASE****************"); - for(Map.Entry entry : dao.getDataBasePoolInfo().entrySet()){ - info(outputStream,entry.getKey() + ":" + entry.getValue()); - - } - - info(outputStream,""); - - info(outputStream,"**********THREADS****************"); - - for(String mbean : dao.getMBeans()){ - - info(outputStream,""); - - - info(outputStream,"MBEAN:" + mbean); - - - HashMap attributes = dao.getMBeanAttributes(mbean, MonitoringDao.mbeanAttributes); - for(Map.Entry entry : attributes.entrySet()){ - info(outputStream,entry.getKey() + ":" + entry.getValue()); - - } - } - - info(outputStream,""); - - - info(outputStream,"**********SessionCount****************"); - - HashMap map = dao.getSessionCount("localhost"); - for(Map.Entry entry : map.entrySet()){ - info(outputStream,entry.getKey().getName() + " " + entry.getValue()); - } - - }catch(Exception e){ - logger.error(e.getMessage(),e); - } - } - - - - protected ObjectName objName = null; - - public void mbeans() throws Exception { - - MBeanServer mBeanServer = Registry.getRegistry(null, null).getMBeanServer(); - String onStr = "*:type=ThreadPool,*"; - ObjectName objectName = new ObjectName(onStr); - Set set = mBeanServer.queryMBeans(objectName, null); - Iterator iterator = set.iterator(); - while (iterator.hasNext()) { - ObjectInstance oi = iterator.next(); - System.out.println(oi.getClassName()); - - objName = oi.getObjectName(); - String name = objName.getKeyProperty("name"); - System.out.println("name:" + name); - - MBeanInfo mbeanInfo = mBeanServer.getMBeanInfo(objName); - - - - for (MBeanAttributeInfo info : mbeanInfo.getAttributes()) { - try { - System.out.println("mbean attribute: " + info.getName() + ": " + mBeanServer.getAttribute(objName, info.getName())); - } catch (javax.management.ReflectionException e) { - } - } - - } - - - - } - - - private void info(ServletOutputStream output, String text) { - logger.info(text); - try{ - output.println(text); - }catch(IOException e){ - logger.error(e.getMessage(),e); - } - } + private transient BasicDataSource dataSource = null; + + private static Logger logger = Logger.getLogger(Monitoring.class); + + @Override + public void init() throws ServletException { + ApplicationContext applicationContext = AlfAppContextGate.getApplicationContext(); + dataSource = (BasicDataSource) applicationContext.getBean("defaultDataSource"); + + super.init(); + } + + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + + try { + if (!new MCAlfrescoAPIClient().isAdmin()) { + resp.getOutputStream().println("access denied"); + return; + } + + } catch (Exception e) { + e.printStackTrace(); + } + + doIt(resp.getOutputStream()); + } + + + private void doIt(ServletOutputStream outputStream) { + try { + MonitoringDao dao = new MonitoringDao(); + + + info(outputStream, "**********DATABASE****************"); + for (Map.Entry entry : dao.getDataBasePoolInfo().entrySet()) { + info(outputStream, entry.getKey() + ":" + entry.getValue()); + + } + + info(outputStream, ""); + + info(outputStream, "**********THREADS****************"); + + for (String mbean : dao.getMBeans()) { + + info(outputStream, ""); + + + info(outputStream, "MBEAN:" + mbean); + + + Map attributes = dao.getMBeanAttributes(mbean, MonitoringDao.mbeanAttributes); + for (Map.Entry entry : attributes.entrySet()) { + info(outputStream, entry.getKey() + ":" + entry.getValue()); + + } + } + + info(outputStream, ""); + + + info(outputStream, "**********SessionCount****************"); + + Map map = dao.getSessionCount("localhost"); + for (Map.Entry entry : map.entrySet()) { + info(outputStream, entry.getKey().getName() + " " + entry.getValue()); + } + + } catch (Exception e) { + logger.error(e.getMessage(), e); + } + } + + + protected ObjectName objName = null; + + public void mbeans() throws Exception { + + MBeanServer mBeanServer = Registry.getRegistry(null, null).getMBeanServer(); + String onStr = "*:type=ThreadPool,*"; + ObjectName objectName = new ObjectName(onStr); + Set set = mBeanServer.queryMBeans(objectName, null); + Iterator iterator = set.iterator(); + while (iterator.hasNext()) { + ObjectInstance oi = iterator.next(); + System.out.println(oi.getClassName()); + + objName = oi.getObjectName(); + String name = objName.getKeyProperty("name"); + System.out.println("name:" + name); + + MBeanInfo mbeanInfo = mBeanServer.getMBeanInfo(objName); + + + for (MBeanAttributeInfo info : mbeanInfo.getAttributes()) { + try { + System.out.println("mbean attribute: " + info.getName() + ": " + mBeanServer.getAttribute(objName, info.getName())); + } catch (javax.management.ReflectionException e) { + } + } + + } + + + } + + + private void info(ServletOutputStream output, String text) { + logger.info(text); + try { + output.println(text); + } catch (IOException e) { + logger.error(e.getMessage(), e); + } + } } diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/monitoring/MonitoringJob.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/monitoring/MonitoringJob.java index 5fe1eac319..6a7c6a287a 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/monitoring/MonitoringJob.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/monitoring/MonitoringJob.java @@ -46,7 +46,7 @@ public void execute(JobExecutionContext context) throws JobExecutionException { logger.info("MBEAN:" + mbean); - HashMap attributes = dao.getMBeanAttributes(mbean, MonitoringDao.mbeanAttributes); + Map attributes = dao.getMBeanAttributes(mbean, MonitoringDao.mbeanAttributes); for(Map.Entry entry : attributes.entrySet()){ logger.info(entry.getKey() + ":" + entry.getValue()); } @@ -54,7 +54,7 @@ public void execute(JobExecutionContext context) throws JobExecutionException { logger.info("**********SessionCount****************"); - HashMap map = dao.getSessionCount("localhost"); + Map map = dao.getSessionCount("localhost"); for(Map.Entry entry : map.entrySet()){ logger.info(entry.getKey().getName() + " " + entry.getValue()); } @@ -66,8 +66,8 @@ public void execute(JobExecutionContext context) throws JobExecutionException { } @Override - public Class[] getJobClasses() { - Class[] result = Arrays.copyOf(allJobs, allJobs.length + 1); + public Class[] getJobClasses() { + Class[] result = Arrays.copyOf(allJobs, allJobs.length + 1); result[result.length - 1] = MonitoringJob.class; return result; } diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/oai/OaiServlet.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/oai/OaiServlet.java index cecd14df5f..5c480bc2fd 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/oai/OaiServlet.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/oai/OaiServlet.java @@ -139,7 +139,7 @@ public List getSets() { @Override public ListItemIdentifiersResult getIdentifiersFrom(int from, int length, Date date, String set) throws OAIException { - HashMap criterias = new HashMap<>(); + Map criterias = new HashMap<>(); criterias.put("from",new String[]{convertDateSolr(date)}); return getIdentifiersSolr(from, length,criterias, set); } @@ -150,13 +150,13 @@ private String convertDateSolr(Date date) { @Override public ListItemIdentifiersResult getIdentifiersUntil(int from, int length, Date date, String set) throws OAIException { - HashMap criterias = new HashMap<>(); + Map criterias = new HashMap<>(); criterias.put("until",new String[]{convertDateSolr(date)}); return getIdentifiersSolr(from, length,criterias, set); } @Override public ListItemIdentifiersResult getIdentifiersFromUntil(int from, int length, Date fromDate, Date untilDate, String set) throws OAIException { - HashMap criterias = new HashMap<>(); + Map criterias = new HashMap<>(); criterias.put("from",new String[]{convertDateSolr(fromDate)}); criterias.put("until",new String[]{convertDateSolr(untilDate)}); return getIdentifiersSolr(from, length, criterias, set); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/rendering/RenderingProxy.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/rendering/RenderingProxy.java index f51a6cd766..e09350e679 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/rendering/RenderingProxy.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/rendering/RenderingProxy.java @@ -253,7 +253,7 @@ private String handleUserParameter(ApplicationInfo homeRep, String rep_id, Strin AuthenticationUtil.RunAsWork runAs = () -> { String localUsername = new String(usernameDecrypted2).trim(); MCAlfrescoAPIClient apiClient = new MCAlfrescoAPIClient(); - HashMap personData = apiClient.getUserInfo(localUsername); + Map personData = apiClient.getUserInfo(localUsername); /** * make sure that the remote user exists diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/tools/AuthenticatorRemoteAppResult.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/tools/AuthenticatorRemoteAppResult.java index ed073d700d..9fe47057aa 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/tools/AuthenticatorRemoteAppResult.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/tools/AuthenticatorRemoteAppResult.java @@ -27,15 +27,15 @@ */ package org.edu_sharing.repository.server.tools; -import java.util.HashMap; +import java.util.Map; public class AuthenticatorRemoteAppResult { - HashMap authenticationInfo = null; + Map authenticationInfo = null; String exceptionMessage = null; - public HashMap getAuthenticationInfo() { + public Map getAuthenticationInfo() { return authenticationInfo; } - public void setAuthenticationInfo(HashMap authenticationInfo) { + public void setAuthenticationInfo(Map authenticationInfo) { this.authenticationInfo = authenticationInfo; } public String getExceptionMessage() { diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/tools/AuthenticatorRemoteRepository.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/tools/AuthenticatorRemoteRepository.java index 5b8ca348fd..1e69036162 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/tools/AuthenticatorRemoteRepository.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/tools/AuthenticatorRemoteRepository.java @@ -83,7 +83,7 @@ public class AuthenticatorRemoteRepository { */ public AuthenticatorRemoteAppResult getAuthInfoForApp(String username, ApplicationInfo remoteAppInfo) throws Throwable{ - HashMap resultAuthInfo = new HashMap(); + Map resultAuthInfo = new HashMap<>(); MCAlfrescoBaseClient mcAlfrescoBaseClient = new MCAlfrescoAPIClient(); AuthenticationToken authToken = null; @@ -121,7 +121,7 @@ private AuthenticationToken remoteAuth(String appId, String username) throws Exc logger.info("startSession remoteApplicationId:"+appId +" localAppId:"+localAppId); - HashMap personMapping = new HashMap<>(ssoAuthorityMapper.getMappingConfig().getPersonMapping()); + Map personMapping = new HashMap<>(ssoAuthorityMapper.getMappingConfig().getPersonMapping()); String remoteUserid = ApplicationInfoList.getRepositoryInfoById(appId).getString(ApplicationInfo.REMOTE_USERID, null); if(remoteUserid!=null && !remoteUserid.isEmpty()){ logger.info("remote_userid configured "+remoteUserid+", will change auth"); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/tools/EduGroupTool.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/tools/EduGroupTool.java index 715af9591a..ce86ff03ef 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/tools/EduGroupTool.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/tools/EduGroupTool.java @@ -74,10 +74,10 @@ public class EduGroupTool { // Map [PROP_AUTHORITYNAME] --> [NODEREF OF EDUGROUP] // Important: [NAME OF A GROUP] is unique on an Alfresco node - private static HashMap cachedGroupNameMap = null; + private static Map cachedGroupNameMap = null; // Map [NODEREF OF EDUGROUP (String)] --> [PARENT NODEREF OF EDUGROUP (String)] - private static HashMap cachedGroupParentMap = null; + private static Map cachedGroupParentMap = null; // use this object for synchronized code blocks that are working stateful on // cachedGroupNameMap OR cachedGroupParentMap @@ -105,13 +105,13 @@ private static synchronized void init()throws Exception { } /** - * Loads a cashed HashMap of all edugroups from userStore. + * Loads a cashed Map of all edugroups from userStore. * Use if a lot requests are performed on Map and its no problem if Map is less than 20 secs old * * KEY -> Groupname * VALUE -> NodeRef */ - private static HashMap getCashedEduGroupMap() throws Exception { + private static Map getCashedEduGroupMap() throws Exception { // check if map needs refresh synchronized(syncAccessLock) { @@ -139,8 +139,8 @@ private static HashMap getCashedEduGroupMap() throws Exception { * @return * @throws Exception */ - private static HashMap createCachedGroupParentMap(NodeService nodeService, HashMap groupMap) throws Exception { - HashMap result = new HashMap(); + private static Map createCachedGroupParentMap(NodeService nodeService, Map groupMap) throws Exception { + Map result = new HashMap<>(); for (String groupName : groupMap.keySet()) { NodeRef nodeRef = groupMap.get(groupName); if (nodeService.getParentAssocs(nodeRef).size()==1) { @@ -154,19 +154,16 @@ private static HashMap createCachedGroupParentMap(NodeService no } /** - * Loads a fresh HashMap of all edugroups from userStore. + * Loads a fresh Map of all edugroups from userStore. * KEY -> Groupname * VALUE -> NodeRef */ - public static HashMap getEduGroupMap(final NodeService nodeService) throws Exception { + public static Map getEduGroupMap(final NodeService nodeService) throws Exception { - AuthenticationUtil.RunAsWork> runAs = new AuthenticationUtil.RunAsWork>() { - @Override - public HashMap doWork() throws Exception { - if (!doneInit) init(); - return getEduGroupMapFromNodeContainer(nodeService, authorityRootNodeRef, 1); - } - }; + AuthenticationUtil.RunAsWork> runAs = () -> { + if (!doneInit) init(); + return getEduGroupMapFromNodeContainer(nodeService, authorityRootNodeRef, 1); + }; return AuthenticationUtil.runAs(runAs, ApplicationInfoList.getHomeRepository().getUsername()); } @@ -232,9 +229,9 @@ public static String getParentPathForEduGroup(String group_NodeRefStr_UserIsIn) /* * Recursive traversal of userstore ... */ - private static HashMap getEduGroupMapFromNodeContainer(NodeService nodeService, NodeRef node, int recDepth) { + private static Map getEduGroupMapFromNodeContainer(NodeService nodeService, NodeRef node, int recDepth) { - HashMap results = new HashMap(); + Map results = new HashMap<>(); // to prevent possible infintiv loops in a node graph ... stop at a recursive level of 5 if (recDepth>5) return results; @@ -426,7 +423,7 @@ public static void processEduGroupMicroCommand(String propName) throws Exception nodeService.setType(homeRef, QNAME_HOMEDIR); // add aspect to group - Map params = new HashMap(); + Map params = new HashMap<>(); params.put(QName.createQName(CCM_PROP_EDUGROUP_EDU_HOMEDIR), homeRef); params.put(QName.createQName(CCM_PROP_EDUGROUP_EDU_UNIQUENAME), linkName); nodeService.addAspect(groupRef, QNAME_EDUGROUP, params); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/tools/EduSharingLockManager.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/tools/EduSharingLockManager.java index e7938c878a..27a6d9e89d 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/tools/EduSharingLockManager.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/tools/EduSharingLockManager.java @@ -1,6 +1,7 @@ package org.edu_sharing.repository.server.tools; import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; import java.util.concurrent.Semaphore; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; @@ -9,15 +10,10 @@ * for non-clustered environments */ public class EduSharingLockManager { - private static final ConcurrentHashMap pool = new ConcurrentHashMap<>(); + private static final ConcurrentMap pool = new ConcurrentHashMap<>(); - protected synchronized Lock getLock(Class clazz, String keyName) { - Lock lock = pool.get(getKey(clazz, keyName)); - if(lock == null) { - lock = new ReentrantLock(); - pool.put(getKey(clazz, keyName), lock); - } - return lock; + protected synchronized Lock getLock(Class clazz, String keyName) { + return pool.computeIfAbsent(getKey(clazz, keyName), k -> new ReentrantLock()); } protected synchronized void cleanupLock(Lock lock) { if (!((ReentrantLock)lock).hasQueuedThreads()) { @@ -25,7 +21,7 @@ protected synchronized void cleanupLock(Lock lock) { } } - protected String getKey(Class clazz, String lockName) { + protected String getKey(Class clazz, String lockName) { return clazz.getName() + "_" + lockName; } } diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/tools/LRMITool.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/tools/LRMITool.java index 8d75f0c485..16349aaf74 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/tools/LRMITool.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/tools/LRMITool.java @@ -12,15 +12,12 @@ import org.edu_sharing.repository.client.tools.forms.VCardTool; import org.edu_sharing.repository.client.tools.metadata.ValueTool; import org.edu_sharing.repository.server.NodeRefVersion; -import org.edu_sharing.repository.server.tools.cache.PersonCache; import org.edu_sharing.service.license.LicenseService; -import org.edu_sharing.service.nodeservice.NodeServiceFactory; import org.edu_sharing.service.nodeservice.NodeServiceHelper; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; -import java.io.Serializable; import java.util.*; import java.util.stream.Collectors; @@ -41,7 +38,7 @@ public class LRMITool { public static JSONObject getLRMIJson(NodeRefVersion node) throws Throwable { JSONObject lrmi=new JSONObject(); // TODO: This probably has to work for remote repos in future - HashMap props = NodeServiceHelper.getPropertiesVersion(node.getNodeRef(), node.getVersion()); + Map props = NodeServiceHelper.getPropertiesVersion(node.getNodeRef(), node.getVersion()); Config lrmiProps = getMappingFile(); lrmi.put("@context","http://schema.org/"); lrmi.put("@type",new String[]{"CreativeWork","MediaObject"}); @@ -98,13 +95,13 @@ private static String getDate(Object property) { } } - private static Object getFromVCard(String key,HashMap props) throws JSONException { + private static Object getFromVCard(String key,Map props) throws JSONException { if(props.get(key)==null) return null; String[] values=new ValueTool().getMultivalue(props.get(key).toString()); JSONArray result=new JSONArray(); for(String v: values) { - HashMap vcard = VCardConverter.getVCardHashMap(null, key, v); + Map vcard = VCardConverter.getVCardMap(null, key, v); if (vcard == null || vcard.size() == 0) return null; @@ -139,7 +136,7 @@ private static Object getFromVCard(String key,HashMap props) thro * @param keys * @return */ - private static Object getPropertyCombined(HashMap props, List> keys) { + private static Object getPropertyCombined(Map props, List> keys) { for(List keyArray : keys){ List result=new ArrayList<>(); for(String key : keyArray) { @@ -166,7 +163,7 @@ else if(result.size()>1) } return null; } - private static Object getProperty(HashMap props, List keys) { + private static Object getProperty(Map props, List keys) { return getPropertyCombined(props,Collections.singletonList(keys)); } @@ -222,7 +219,7 @@ else if(data instanceof String){ * }, */ private static String asVCard(JSONObject object) throws JSONException { - HashMap map=new HashMap<>(); + Map map = new HashMap<>(); String type = object.getString("@type"); if(type.equals("Person")){ map.put(CCConstants.VCARD_GIVENNAME, object.getString("givenName")); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/tools/NameSpaceTool.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/tools/NameSpaceTool.java index 55632e84d2..493d24878b 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/tools/NameSpaceTool.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/tools/NameSpaceTool.java @@ -52,7 +52,7 @@ public Map transformKeysToLongQname(Map properties){ public static List transFormToShortQName(List qnames){ - List list = new ArrayList(); + List list = new ArrayList<>(); for(String qname : qnames){ if(qname.matches(CCConstants.NAMESPACE_PREFIX_REGEX_SHORT)){ list.add(qname); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/tools/NodeTool.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/tools/NodeTool.java index 8ad8896c6c..aada68f802 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/tools/NodeTool.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/tools/NodeTool.java @@ -2,6 +2,7 @@ import java.util.Arrays; import java.util.HashMap; +import java.util.Map; import org.edu_sharing.repository.client.tools.CCConstants; import org.edu_sharing.repository.server.MCAlfrescoBaseClient; @@ -14,11 +15,11 @@ public String createOrGetNodeByName(MCAlfrescoBaseClient client, String nodeId, String name = path[0]; - HashMap child = client.getChild(nodeId, CCConstants.CCM_TYPE_MAP, CCConstants.CM_NAME, name); + Map child = client.getChild(nodeId, CCConstants.CCM_TYPE_MAP, CCConstants.CM_NAME, name); if (child == null) { - HashMap _props = new HashMap(); + Map _props = new HashMap<>(); _props.put(CCConstants.CM_NAME, name); nodeId = client.createNode(nodeId, CCConstants.CCM_TYPE_MAP, _props); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/tools/StringTool.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/tools/StringTool.java index ec7e783e1a..a631e4e962 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/tools/StringTool.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/tools/StringTool.java @@ -47,7 +47,7 @@ public static String getEncoded(byte[] value){ public static String[] getPhrases(String str) { - List result = new ArrayList(); + List result = new ArrayList<>(); String[] tokens = str.split(PHRASE_DELIMITER); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/tools/URLTool.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/tools/URLTool.java index 2404422fe1..2052d9bf52 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/tools/URLTool.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/tools/URLTool.java @@ -29,6 +29,7 @@ import java.text.MessageFormat; import java.util.HashMap; +import java.util.Map; import jakarta.servlet.http.HttpServletRequest; @@ -212,7 +213,7 @@ public static String getPreviewServletUrl(String node, String storeProtocol,Stri String repoId = (String)alfNodeService.getProperty(nodeRef, QName.createQName(CCConstants.CCM_PROP_REMOTEOBJECT_REPOSITORYID)); String remoteNodeId = (String)alfNodeService.getProperty(nodeRef, QName.createQName(CCConstants.CCM_PROP_REMOTEOBJECT_NODEID)); try { - HashMap props = NodeServiceFactory.getNodeService(repoId).getProperties(null,null,remoteNodeId); + Map props = NodeServiceFactory.getNodeService(repoId).getProperties(null, null, remoteNodeId); return (String)props.get(CCConstants.CM_ASSOC_THUMBNAILS); } catch (Throwable e) { // TODO Auto-generated catch block diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/tools/UserEnvironmentTool.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/tools/UserEnvironmentTool.java index 995aedb535..3f8b0c920c 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/tools/UserEnvironmentTool.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/tools/UserEnvironmentTool.java @@ -1,28 +1,4 @@ /** - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * * */ package org.edu_sharing.repository.server.tools; @@ -49,175 +25,180 @@ import org.springframework.stereotype.Component; public class UserEnvironmentTool { - - private static Log logger = LogFactory.getLog(UserEnvironmentTool.class); - MCAlfrescoAPIClient mcBaseClient = new MCAlfrescoAPIClient(); - String username = null; - private final NodeService nodeService; + private static Log logger = LogFactory.getLog(UserEnvironmentTool.class); + MCAlfrescoAPIClient mcBaseClient = new MCAlfrescoAPIClient(); + String username = null; + + private final NodeService nodeService; public UserEnvironmentTool() throws Throwable { this(AuthenticationUtil.getFullyAuthenticatedUser()); } - /** - * use this for running this class in an runAs context - * @throws Throwable - */ - public UserEnvironmentTool(String runAsUser) { - this(NodeServiceFactory.getLocalService(), runAsUser); - } - - public UserEnvironmentTool(NodeService nodeService) { - this(nodeService, AuthenticationUtil.getFullyAuthenticatedUser()); - } - - public UserEnvironmentTool(NodeService nodeService, String runAsUser) { - username = runAsUser; - this.nodeService = nodeService; - } - - public UserEnvironmentTool(String repositoryId, Map authInfo) { - this(NodeServiceFactory.getLocalService(), repositoryId, authInfo); - } - - public UserEnvironmentTool(NodeService nodeService, String repositoryId, Map authInfo) { - this(nodeService, authInfo.get(CCConstants.AUTH_USERNAME)); - } - - public String getDefaultUserDataFolder() throws Throwable{ - - String homeFolderId = mcBaseClient.getHomeFolderID(username); - - logger.info("homefolder:"+homeFolderId); - String result = null; - - HashMap defaultDataFolderProps = mcBaseClient.getChild(homeFolderId, CCConstants.CCM_TYPE_MAP, CCConstants.CCM_PROP_MAP_TYPE, CCConstants.CCM_VALUE_MAP_TYPE_DOCUMENTS); - if(defaultDataFolderProps != null){ - result = (String)defaultDataFolderProps.get(CCConstants.SYS_PROP_NODE_UID); - }else{ - logger.error("something went wrong! no datafolder for current user "+username+" found!"); - } - - return result; - } - - public String getDefaultImageFolder() throws Throwable{ - - String homeFolderId = mcBaseClient.getHomeFolderID(username); - - logger.info("homefolder:"+homeFolderId); - String result = null; - - HashMap defaultImageFolderProps = mcBaseClient.getChild(homeFolderId, CCConstants.CCM_TYPE_MAP, CCConstants.CCM_PROP_MAP_TYPE, CCConstants.CCM_VALUE_MAP_TYPE_IMAGES); - if(defaultImageFolderProps != null){ - result = (String)defaultImageFolderProps.get(CCConstants.SYS_PROP_NODE_UID); - }else{ - logger.error("something went wrong! no image folder for current user "+username+" found!"); - } - - return result; - } - - public String getEdu_SharingSystemFolderBase() throws Throwable{ - if(!mcBaseClient.isAdmin() && !AuthenticationUtil.isRunAsUserTheSystemUser()){ - throw new Exception("Admin group required"); - } - String companyHomeNodeId = mcBaseClient.getCompanyHomeNodeId(); - NodeRef edu_SharingSysMap = nodeService.getChild(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE,companyHomeNodeId, CCConstants.CCM_TYPE_MAP, CCConstants.CCM_PROP_MAP_TYPE, CCConstants.CCM_VALUE_MAP_TYPE_EDU_SHARING_SYSTEM); - - String result = null; - if(edu_SharingSysMap == null){ - - String systemFolderName = I18nServer.getTranslationDefaultResourcebundle(CCConstants.I18n_SYSTEMFOLDER_BASE); - HashMap newEdu_SharingSysMapProps = new HashMap(); - newEdu_SharingSysMapProps.put(CCConstants.CM_NAME, systemFolderName); - - HashMap i18nTitle = new HashMap(); - i18nTitle.put("de_DE", I18nServer.getTranslationDefaultResourcebundle(CCConstants.I18n_SYSTEMFOLDER_BASE, "de_DE")); - i18nTitle.put("en_EN", I18nServer.getTranslationDefaultResourcebundle(CCConstants.I18n_SYSTEMFOLDER_BASE, "en_EN")); - i18nTitle.put("en_US", I18nServer.getTranslationDefaultResourcebundle(CCConstants.I18n_SYSTEMFOLDER_BASE, "en_US")); - - newEdu_SharingSysMapProps.put(CCConstants.CM_PROP_C_TITLE, i18nTitle); - newEdu_SharingSysMapProps.put(CCConstants.CCM_PROP_MAP_TYPE, CCConstants.CCM_VALUE_MAP_TYPE_EDU_SHARING_SYSTEM); - result = mcBaseClient.createNode(companyHomeNodeId, CCConstants.CCM_TYPE_MAP, newEdu_SharingSysMapProps); - }else{ - result = edu_SharingSysMap.getId(); - } - return result; - } - - public String getEdu_SharingSystemFolderUpdate() throws Throwable{ - if(!mcBaseClient.isAdmin()){ - throw new Exception("Admin group required"); - } - - String systemFolderId = getEdu_SharingSystemFolderBase(); - HashMap edu_SharingSystemFolderUpdate = mcBaseClient.getChild(systemFolderId, CCConstants.CCM_TYPE_MAP, CCConstants.CCM_PROP_MAP_TYPE, CCConstants.CCM_VALUE_MAP_TYPE_EDU_SHARING_SYSTEM_UPDATE); - - String result = null; - if(edu_SharingSystemFolderUpdate == null){ - String systemFolderName = I18nServer.getTranslationDefaultResourcebundle(CCConstants.I18n_SYSTEMFOLDER_UPDATE); - HashMap newEdu_SharingSysMapProps = new HashMap(); - newEdu_SharingSysMapProps.put(CCConstants.CM_NAME, systemFolderName); - - HashMap i18nTitle = new HashMap(); - i18nTitle.put("de_DE", I18nServer.getTranslationDefaultResourcebundle(CCConstants.I18n_SYSTEMFOLDER_UPDATE, "de_DE")); - i18nTitle.put("en_EN", I18nServer.getTranslationDefaultResourcebundle(CCConstants.I18n_SYSTEMFOLDER_UPDATE, "en_EN")); - i18nTitle.put("en_US", I18nServer.getTranslationDefaultResourcebundle(CCConstants.I18n_SYSTEMFOLDER_UPDATE, "en_US")); - - newEdu_SharingSysMapProps.put(CCConstants.CM_PROP_C_TITLE, i18nTitle); - newEdu_SharingSysMapProps.put(CCConstants.CCM_PROP_MAP_TYPE, CCConstants.CCM_VALUE_MAP_TYPE_EDU_SHARING_SYSTEM_UPDATE); - result = mcBaseClient.createNode(systemFolderId, CCConstants.CCM_TYPE_MAP, newEdu_SharingSysMapProps); - }else{ - result = (String)edu_SharingSystemFolderUpdate.get(CCConstants.SYS_PROP_NODE_UID); - } - return result; - } - - - public String getEdu_SharingNotifyFolder() throws Throwable{ - String systemFolderId = getEdu_SharingSystemFolderBase(); - - String currentScope = NodeServiceInterceptor.getEduSharingScope(); - - //String notifyRootFolderName = (currentScope == null || currentScope.trim().isEmpty()) ? CCConstants.CCM_VALUE_MAP_TYPE_EDU_SHARING_SYSTEM_NOTIFY : CCConstants.CCM_VALUE_MAP_TYPE_EDU_SHARING_SYSTEM_NOTIFY + "_" + currentScope; - - String systemFolderName = I18nServer.getTranslationDefaultResourcebundle(CCConstants.I18n_SYSTEMFOLDER_NOTIFY); - systemFolderName = (currentScope == null || currentScope.trim().isEmpty()) ? systemFolderName: systemFolderName + "_" + currentScope; - NodeRef edu_SharingSystemFolderNotify = nodeService.getChild(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, systemFolderId, CCConstants.CCM_TYPE_MAP, CCConstants.CM_NAME,systemFolderName); - String result = null; - if(edu_SharingSystemFolderNotify == null){ - - HashMap newEdu_SharingSysMapProps = new HashMap(); - newEdu_SharingSysMapProps.put(CCConstants.CM_NAME, systemFolderName); - - HashMap i18nTitle = new HashMap(); - i18nTitle.put("de_DE", I18nServer.getTranslationDefaultResourcebundle(CCConstants.I18n_SYSTEMFOLDER_NOTIFY, "de_DE")); - i18nTitle.put("en_EN", I18nServer.getTranslationDefaultResourcebundle(CCConstants.I18n_SYSTEMFOLDER_NOTIFY, "en_EN")); - i18nTitle.put("en_US", I18nServer.getTranslationDefaultResourcebundle(CCConstants.I18n_SYSTEMFOLDER_NOTIFY, "en_US")); - - newEdu_SharingSysMapProps.put(CCConstants.CM_PROP_C_TITLE, i18nTitle); - newEdu_SharingSysMapProps.put(CCConstants.CCM_PROP_MAP_TYPE, CCConstants.CCM_VALUE_MAP_TYPE_EDU_SHARING_SYSTEM_NOTIFY); - result = mcBaseClient.createNode(systemFolderId, CCConstants.CCM_TYPE_MAP, newEdu_SharingSysMapProps); - }else{ - result = edu_SharingSystemFolderNotify.getId(); - } - return result; - } - public String getEdu_SharingConfigFolder() throws Throwable { - return getOrCreateSystemFolderByName(CCConstants.CCM_VALUE_MAP_TYPE_EDU_SHARING_SYSTEM_SERVICE, CCConstants.I18n_SYSTEMFOLDER_CONFIG); - } - public String getEdu_SharingMediacenterFolder() throws Throwable { - return getOrCreateSystemFolderByName(CCConstants.CCM_VALUE_MAP_TYPE_EDU_SHARING_SYSTEM_MEDIACENTER, CCConstants.I18n_SYSTEMFOLDER_MEDIACENTER); - } + + /** + * use this for running this class in an runAs context + * @throws Throwable + */ + public UserEnvironmentTool(String runAsUser) { + this(NodeServiceFactory.getLocalService(), runAsUser); + } + + public UserEnvironmentTool(NodeService nodeService) { + this(nodeService, AuthenticationUtil.getFullyAuthenticatedUser()); + } + + public UserEnvironmentTool(NodeService nodeService, String runAsUser) { + username = runAsUser; + this.nodeService = nodeService; + } + + public UserEnvironmentTool(String repositoryId, Map authInfo) { + this(NodeServiceFactory.getLocalService(), repositoryId, authInfo); + } + + public UserEnvironmentTool(NodeService nodeService, String repositoryId, Map authInfo) { + this(nodeService, authInfo.get(CCConstants.AUTH_USERNAME)); + } + + public String getDefaultUserDataFolder() throws Throwable { + + String homeFolderId = mcBaseClient.getHomeFolderID(username); + + logger.info("homefolder:" + homeFolderId); + String result = null; + + Map defaultDataFolderProps = mcBaseClient.getChild(homeFolderId, CCConstants.CCM_TYPE_MAP, CCConstants.CCM_PROP_MAP_TYPE, CCConstants.CCM_VALUE_MAP_TYPE_DOCUMENTS); + if (defaultDataFolderProps != null) { + result = (String) defaultDataFolderProps.get(CCConstants.SYS_PROP_NODE_UID); + } else { + logger.error("something went wrong! no datafolder for current user " + username + " found!"); + } + + return result; + } + + public String getDefaultImageFolder() throws Throwable { + + String homeFolderId = mcBaseClient.getHomeFolderID(username); + + logger.info("homefolder:" + homeFolderId); + String result = null; + + Map defaultImageFolderProps = mcBaseClient.getChild(homeFolderId, CCConstants.CCM_TYPE_MAP, CCConstants.CCM_PROP_MAP_TYPE, CCConstants.CCM_VALUE_MAP_TYPE_IMAGES); + if (defaultImageFolderProps != null) { + result = (String) defaultImageFolderProps.get(CCConstants.SYS_PROP_NODE_UID); + } else { + logger.error("something went wrong! no image folder for current user " + username + " found!"); + } + + return result; + } + + public String getEdu_SharingSystemFolderBase() throws Throwable { + if (!mcBaseClient.isAdmin() && !AuthenticationUtil.isRunAsUserTheSystemUser()) { + throw new Exception("Admin group required"); + } + String companyHomeNodeId = mcBaseClient.getCompanyHomeNodeId(); + NodeRef edu_SharingSysMap = nodeService.getChild(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, companyHomeNodeId, CCConstants.CCM_TYPE_MAP, CCConstants.CCM_PROP_MAP_TYPE, CCConstants.CCM_VALUE_MAP_TYPE_EDU_SHARING_SYSTEM); + + String result = null; + if (edu_SharingSysMap == null) { + + String systemFolderName = I18nServer.getTranslationDefaultResourcebundle(CCConstants.I18n_SYSTEMFOLDER_BASE); + HashMap newEdu_SharingSysMapProps = new HashMap(); + newEdu_SharingSysMapProps.put(CCConstants.CM_NAME, systemFolderName); + + HashMap i18nTitle = new HashMap(); + i18nTitle.put("de_DE", I18nServer.getTranslationDefaultResourcebundle(CCConstants.I18n_SYSTEMFOLDER_BASE, "de_DE")); + i18nTitle.put("en_EN", I18nServer.getTranslationDefaultResourcebundle(CCConstants.I18n_SYSTEMFOLDER_BASE, "en_EN")); + i18nTitle.put("en_US", I18nServer.getTranslationDefaultResourcebundle(CCConstants.I18n_SYSTEMFOLDER_BASE, "en_US")); + + newEdu_SharingSysMapProps.put(CCConstants.CM_PROP_C_TITLE, i18nTitle); + newEdu_SharingSysMapProps.put(CCConstants.CCM_PROP_MAP_TYPE, CCConstants.CCM_VALUE_MAP_TYPE_EDU_SHARING_SYSTEM); + result = mcBaseClient.createNode(companyHomeNodeId, CCConstants.CCM_TYPE_MAP, newEdu_SharingSysMapProps); + } else { + result = edu_SharingSysMap.getId(); + } + return result; + } + + public String getEdu_SharingSystemFolderUpdate() throws Throwable { + if (!mcBaseClient.isAdmin()) { + throw new Exception("Admin group required"); + } + + String systemFolderId = getEdu_SharingSystemFolderBase(); + Map edu_SharingSystemFolderUpdate = mcBaseClient.getChild(systemFolderId, CCConstants.CCM_TYPE_MAP, CCConstants.CCM_PROP_MAP_TYPE, CCConstants.CCM_VALUE_MAP_TYPE_EDU_SHARING_SYSTEM_UPDATE); + + String result = null; + if (edu_SharingSystemFolderUpdate == null) { + String systemFolderName = I18nServer.getTranslationDefaultResourcebundle(CCConstants.I18n_SYSTEMFOLDER_UPDATE); + HashMap newEdu_SharingSysMapProps = new HashMap(); + newEdu_SharingSysMapProps.put(CCConstants.CM_NAME, systemFolderName); + + HashMap i18nTitle = new HashMap(); + i18nTitle.put("de_DE", I18nServer.getTranslationDefaultResourcebundle(CCConstants.I18n_SYSTEMFOLDER_UPDATE, "de_DE")); + i18nTitle.put("en_EN", I18nServer.getTranslationDefaultResourcebundle(CCConstants.I18n_SYSTEMFOLDER_UPDATE, "en_EN")); + i18nTitle.put("en_US", I18nServer.getTranslationDefaultResourcebundle(CCConstants.I18n_SYSTEMFOLDER_UPDATE, "en_US")); + + newEdu_SharingSysMapProps.put(CCConstants.CM_PROP_C_TITLE, i18nTitle); + newEdu_SharingSysMapProps.put(CCConstants.CCM_PROP_MAP_TYPE, CCConstants.CCM_VALUE_MAP_TYPE_EDU_SHARING_SYSTEM_UPDATE); + result = mcBaseClient.createNode(systemFolderId, CCConstants.CCM_TYPE_MAP, newEdu_SharingSysMapProps); + } else { + result = (String) edu_SharingSystemFolderUpdate.get(CCConstants.SYS_PROP_NODE_UID); + } + return result; + } + + + public String getEdu_SharingNotifyFolder() throws Throwable { + String systemFolderId = getEdu_SharingSystemFolderBase(); + + String currentScope = NodeServiceInterceptor.getEduSharingScope(); + + //String notifyRootFolderName = (currentScope == null || currentScope.trim().isEmpty()) ? CCConstants.CCM_VALUE_MAP_TYPE_EDU_SHARING_SYSTEM_NOTIFY : CCConstants.CCM_VALUE_MAP_TYPE_EDU_SHARING_SYSTEM_NOTIFY + "_" + currentScope; + + String systemFolderName = I18nServer.getTranslationDefaultResourcebundle(CCConstants.I18n_SYSTEMFOLDER_NOTIFY); + systemFolderName = (currentScope == null || currentScope.trim().isEmpty()) ? systemFolderName : systemFolderName + "_" + currentScope; + NodeRef edu_SharingSystemFolderNotify = nodeService.getChild(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, systemFolderId, CCConstants.CCM_TYPE_MAP, CCConstants.CM_NAME, systemFolderName); + String result = null; + if (edu_SharingSystemFolderNotify == null) { + + HashMap newEdu_SharingSysMapProps = new HashMap(); + newEdu_SharingSysMapProps.put(CCConstants.CM_NAME, systemFolderName); + + HashMap i18nTitle = new HashMap(); + i18nTitle.put("de_DE", I18nServer.getTranslationDefaultResourcebundle(CCConstants.I18n_SYSTEMFOLDER_NOTIFY, "de_DE")); + i18nTitle.put("en_EN", I18nServer.getTranslationDefaultResourcebundle(CCConstants.I18n_SYSTEMFOLDER_NOTIFY, "en_EN")); + i18nTitle.put("en_US", I18nServer.getTranslationDefaultResourcebundle(CCConstants.I18n_SYSTEMFOLDER_NOTIFY, "en_US")); + + newEdu_SharingSysMapProps.put(CCConstants.CM_PROP_C_TITLE, i18nTitle); + newEdu_SharingSysMapProps.put(CCConstants.CCM_PROP_MAP_TYPE, CCConstants.CCM_VALUE_MAP_TYPE_EDU_SHARING_SYSTEM_NOTIFY); + result = mcBaseClient.createNode(systemFolderId, CCConstants.CCM_TYPE_MAP, newEdu_SharingSysMapProps); + } else { + result = edu_SharingSystemFolderNotify.getId(); + } + return result; + } + + public String getEdu_SharingConfigFolder() throws Throwable { + return getOrCreateSystemFolderByName(CCConstants.CCM_VALUE_MAP_TYPE_EDU_SHARING_SYSTEM_SERVICE, CCConstants.I18n_SYSTEMFOLDER_CONFIG); + } + + public String getEdu_SharingMediacenterFolder() throws Throwable { + return getOrCreateSystemFolderByName(CCConstants.CCM_VALUE_MAP_TYPE_EDU_SHARING_SYSTEM_MEDIACENTER, CCConstants.I18n_SYSTEMFOLDER_MEDIACENTER); + } + public String getEdu_SharingServiceFolder() throws Throwable { return getOrCreateSystemFolderByName(CCConstants.CCM_VALUE_MAP_TYPE_EDU_SHARING_SYSTEM_SERVICE, CCConstants.I18n_SYSTEMFOLDER_SERVICE); } - public String getEdu_SharingTemplateFolder() throws Throwable{ - return getOrCreateSystemFolderByName(CCConstants.CCM_VALUE_MAP_TYPE_EDU_SHARING_SYSTEM_TEMPLATE,CCConstants.I18n_SYSTEMFOLDER_TEMPLATE); + + public String getEdu_SharingTemplateFolder() throws Throwable { + return getOrCreateSystemFolderByName(CCConstants.CCM_VALUE_MAP_TYPE_EDU_SHARING_SYSTEM_TEMPLATE, CCConstants.I18n_SYSTEMFOLDER_TEMPLATE); /* String systemFolderId = getEdu_SharingSystemFolderBase(); - HashMap edu_SharingSystemFolderTemplate = mcBaseClient.getChild(systemFolderId, CCConstants.CCM_TYPE_MAP, CCConstants.CCM_PROP_MAP_TYPE, CCConstants.CCM_VALUE_MAP_TYPE_EDU_SHARING_SYSTEM_TEMPLATE); + Map< mcBaseClient.getChild(systemFolderId, CCConstants.CCM_TYPE_MAP, CCConstants.CCM_PROP_MAP_TYPE, CCConstants.CCM_VALUE_MAP_TYPE_EDU_SHARING_SYSTEM_TEMPLATE); String result = null; if(edu_SharingSystemFolderTemplate == null){ String systemFolderName = I18nServer.getTranslationDefaultResourcebundle(CCConstants.I18n_SYSTEMFOLDER_TEMPLATE); @@ -237,17 +218,18 @@ public String getEdu_SharingTemplateFolder() throws Throwable{ } return result; */ - } - public String getOrCreateSystemFolderByName(String constantName,String i18nId) throws Throwable { + } + + public String getOrCreateSystemFolderByName(String constantName, String i18nId) throws Throwable { String result; String systemFolderId = getEdu_SharingSystemFolderBase(); - HashMap edu_SharingSystemFolderTemplate = mcBaseClient.getChild(systemFolderId, CCConstants.CCM_TYPE_MAP, CCConstants.CCM_PROP_MAP_TYPE, constantName); - if(edu_SharingSystemFolderTemplate == null){ + Map edu_SharingSystemFolderTemplate = mcBaseClient.getChild(systemFolderId, CCConstants.CCM_TYPE_MAP, CCConstants.CCM_PROP_MAP_TYPE, constantName); + if (edu_SharingSystemFolderTemplate == null) { String systemFolderName = I18nServer.getTranslationDefaultResourcebundle(i18nId); - HashMap newEdu_SharingSysMapProps = new HashMap(); + Map newEdu_SharingSysMapProps = new HashMap<>(); newEdu_SharingSysMapProps.put(CCConstants.CM_NAME, systemFolderName); - HashMap i18nTitle = new HashMap(); + Map i18nTitle = new HashMap<>(); i18nTitle.put("de_DE", I18nServer.getTranslationDefaultResourcebundle(i18nId, "de_DE")); i18nTitle.put("en_EN", I18nServer.getTranslationDefaultResourcebundle(i18nId, "en_EN")); i18nTitle.put("en_US", I18nServer.getTranslationDefaultResourcebundle(i18nId, "en_US")); @@ -255,95 +237,79 @@ public String getOrCreateSystemFolderByName(String constantName,String i18nId) t newEdu_SharingSysMapProps.put(CCConstants.CM_PROP_C_TITLE, i18nTitle); newEdu_SharingSysMapProps.put(CCConstants.CCM_PROP_MAP_TYPE, constantName); result = mcBaseClient.createNode(systemFolderId, CCConstants.CCM_TYPE_MAP, newEdu_SharingSysMapProps); - }else{ - result = (String)edu_SharingSystemFolderTemplate.get(CCConstants.SYS_PROP_NODE_UID); + } else { + result = (String) edu_SharingSystemFolderTemplate.get(CCConstants.SYS_PROP_NODE_UID); } return result; } - - - /** - * returns a folder where notify Objects can be safed - * - * @return - * @throws Throwable - */ - public String getEdu_SharingNotifyFolderToSafe() throws Throwable{ - String notifyFolder = getEdu_SharingNotifyFolder(); - - String year = new Integer(Calendar.getInstance().get(Calendar.YEAR)).toString(); - String yearMapId = getMap(notifyFolder,year,CCConstants.CCM_VALUE_MAP_TYPE_EDU_SHARING_SYSTEM_NOTIFY); - - String month = new Integer(Calendar.getInstance().get(Calendar.MONTH)).toString(); - String monthMapId = getMap(yearMapId,month,CCConstants.CCM_VALUE_MAP_TYPE_EDU_SHARING_SYSTEM_NOTIFY); - - String day = new Integer(Calendar.getInstance().get(Calendar.DAY_OF_MONTH)).toString(); - String dayMapId = getMap(monthMapId,day,CCConstants.CCM_VALUE_MAP_TYPE_EDU_SHARING_SYSTEM_NOTIFY); - - return dayMapId; - } - - public String getEdu_SharingValuespaceFolder() throws Throwable{ - String systemFolderId = getEdu_SharingSystemFolderBase(); - HashMap edu_SharingSystemFolderValuespace = mcBaseClient.getChild(systemFolderId, CCConstants.CCM_TYPE_MAP, CCConstants.CCM_PROP_MAP_TYPE, CCConstants.CCM_VALUE_MAP_TYPE_EDU_SHARING_SYSTEM_VALUESPACE); - String result = null; - if(edu_SharingSystemFolderValuespace == null){ - String systemFolderName = I18nServer.getTranslationDefaultResourcebundle(CCConstants.I18n_SYSTEMFOLDER_VALUESPACE); - HashMap newEdu_SharingSysMapProps = new HashMap(); - newEdu_SharingSysMapProps.put(CCConstants.CM_NAME, systemFolderName); - - HashMap i18nTitle = new HashMap(); - i18nTitle.put("de_DE", I18nServer.getTranslationDefaultResourcebundle(CCConstants.I18n_SYSTEMFOLDER_VALUESPACE, "de_DE")); - i18nTitle.put("en_EN", I18nServer.getTranslationDefaultResourcebundle(CCConstants.I18n_SYSTEMFOLDER_VALUESPACE, "en_EN")); - i18nTitle.put("en_US", I18nServer.getTranslationDefaultResourcebundle(CCConstants.I18n_SYSTEMFOLDER_VALUESPACE, "en_US")); - - newEdu_SharingSysMapProps.put(CCConstants.CM_PROP_C_TITLE, i18nTitle); - newEdu_SharingSysMapProps.put(CCConstants.CCM_PROP_MAP_TYPE, CCConstants.CCM_VALUE_MAP_TYPE_EDU_SHARING_SYSTEM_VALUESPACE); - result = mcBaseClient.createNode(systemFolderId, CCConstants.CCM_TYPE_MAP, newEdu_SharingSysMapProps); - }else{ - result = (String)edu_SharingSystemFolderValuespace.get(CCConstants.SYS_PROP_NODE_UID); - } - return result; - } - - - /** - * returns the child map with name. when it does not exist it will be created - * @param parentId - * @param name - * @return - * @throws Throwable - */ - private String getMap(String parentId, String name, String mapType) throws Throwable{ - NodeRef child = nodeService.getChild(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, parentId, CCConstants.CCM_TYPE_MAP, CCConstants.CM_NAME,name); - if(child == null){ - HashMap props = new HashMap(); - props.put(CCConstants.CM_NAME, name); - props.put(CCConstants.CM_PROP_TITLE, name); - if(mapType != null){ - props.put(CCConstants.CCM_PROP_MAP_TYPE, mapType); - } - return mcBaseClient.createNode(parentId, CCConstants.CCM_TYPE_MAP, props); - } - else{ - return child.getId(); - } - } - - - - - - - - - - - - - - - - - + + + /** + * returns a folder where notify Objects can be safed + * + * @return + * @throws Throwable + */ + public String getEdu_SharingNotifyFolderToSafe() throws Throwable { + String notifyFolder = getEdu_SharingNotifyFolder(); + + String year = new Integer(Calendar.getInstance().get(Calendar.YEAR)).toString(); + String yearMapId = getMap(notifyFolder, year, CCConstants.CCM_VALUE_MAP_TYPE_EDU_SHARING_SYSTEM_NOTIFY); + + String month = new Integer(Calendar.getInstance().get(Calendar.MONTH)).toString(); + String monthMapId = getMap(yearMapId, month, CCConstants.CCM_VALUE_MAP_TYPE_EDU_SHARING_SYSTEM_NOTIFY); + + String day = new Integer(Calendar.getInstance().get(Calendar.DAY_OF_MONTH)).toString(); + String dayMapId = getMap(monthMapId, day, CCConstants.CCM_VALUE_MAP_TYPE_EDU_SHARING_SYSTEM_NOTIFY); + + return dayMapId; + } + + public String getEdu_SharingValuespaceFolder() throws Throwable { + String systemFolderId = getEdu_SharingSystemFolderBase(); + Map edu_SharingSystemFolderValuespace = mcBaseClient.getChild(systemFolderId, CCConstants.CCM_TYPE_MAP, CCConstants.CCM_PROP_MAP_TYPE, CCConstants.CCM_VALUE_MAP_TYPE_EDU_SHARING_SYSTEM_VALUESPACE); + String result = null; + if (edu_SharingSystemFolderValuespace == null) { + String systemFolderName = I18nServer.getTranslationDefaultResourcebundle(CCConstants.I18n_SYSTEMFOLDER_VALUESPACE); + Map newEdu_SharingSysMapProps = new HashMap<>(); + newEdu_SharingSysMapProps.put(CCConstants.CM_NAME, systemFolderName); + + Map i18nTitle = new HashMap<>(); + i18nTitle.put("de_DE", I18nServer.getTranslationDefaultResourcebundle(CCConstants.I18n_SYSTEMFOLDER_VALUESPACE, "de_DE")); + i18nTitle.put("en_EN", I18nServer.getTranslationDefaultResourcebundle(CCConstants.I18n_SYSTEMFOLDER_VALUESPACE, "en_EN")); + i18nTitle.put("en_US", I18nServer.getTranslationDefaultResourcebundle(CCConstants.I18n_SYSTEMFOLDER_VALUESPACE, "en_US")); + + newEdu_SharingSysMapProps.put(CCConstants.CM_PROP_C_TITLE, i18nTitle); + newEdu_SharingSysMapProps.put(CCConstants.CCM_PROP_MAP_TYPE, CCConstants.CCM_VALUE_MAP_TYPE_EDU_SHARING_SYSTEM_VALUESPACE); + result = mcBaseClient.createNode(systemFolderId, CCConstants.CCM_TYPE_MAP, newEdu_SharingSysMapProps); + } else { + result = (String) edu_SharingSystemFolderValuespace.get(CCConstants.SYS_PROP_NODE_UID); + } + return result; + } + + + /** + * returns the child map with name. when it does not exist it will be created + * @param parentId + * @param name + * @return + * @throws Throwable + */ + private String getMap(String parentId, String name, String mapType) throws Throwable { + NodeRef child = nodeService.getChild(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, parentId, CCConstants.CCM_TYPE_MAP, CCConstants.CM_NAME, name); + if (child == null) { + Map props = new HashMap<>(); + props.put(CCConstants.CM_NAME, name); + props.put(CCConstants.CM_PROP_TITLE, name); + if (mapType != null) { + props.put(CCConstants.CCM_PROP_MAP_TYPE, mapType); + } + return mcBaseClient.createNode(parentId, CCConstants.CCM_TYPE_MAP, props); + } else { + return child.getId(); + } + } + + } diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/tools/VCardConverter.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/tools/VCardConverter.java index 6b119d9401..e056c72ffe 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/tools/VCardConverter.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/tools/VCardConverter.java @@ -39,7 +39,6 @@ import org.apache.log4j.Logger; import org.edu_sharing.repository.client.tools.CCConstants; import org.edu_sharing.repository.client.tools.StringTool; -import org.edu_sharing.repository.client.tools.metadata.ValueTool; import java.lang.reflect.Method; import java.util.*; @@ -49,16 +48,16 @@ public class VCardConverter { static Logger logger = Logger.getLogger(VCardConverter.class); - public static ArrayList> vcardToHashMap(String propPrefix, String vcardString){ + public static ArrayList> vcardToMap(String propPrefix, String vcardString){ - ArrayList> result = new ArrayList<>(); + ArrayList> result = new ArrayList<>(); try { VCardEngine engine = new VCardEngine(); // unfortunately, the multi vcard string method is only private, so we need to make it accessible Method method = engine.getClass().getDeclaredMethod("parseManyInOneVCard", String.class); method.setAccessible(true); for(VCard vcard : (List)method.invoke(engine,vcardString)) { - HashMap vcardMap = new HashMap<>(); + Map vcardMap = new HashMap<>(); String fn=vcard.getFN()==null ? null : vcard.getFN().getFormattedName(); String familyName=vcard.getN()==null ? null : vcard.getN().getFamilyName(); String givenName=vcard.getN()==null ? null : vcard.getN().getGivenName(); @@ -128,7 +127,7 @@ public static ArrayList> vcardToHashMap(String propPrefix return result; } - public static String getNameForVCard(String prefix,HashMap data){ + public static String getNameForVCard(String prefix,Map data){ if(isPersonVCard(prefix,data)){ String name=""; if(data.containsKey(prefix+CCConstants.VCARD_TITLE)) @@ -146,7 +145,7 @@ public static String getNameForVCard(String prefix,HashMap data){ } public static String getNameForVCardString(String vcardString) { - ArrayList> vcard = VCardConverter.vcardToHashMap(null, vcardString); + ArrayList> vcard = VCardConverter.vcardToMap(null, vcardString); if (vcard.size() == 0) return null; return StringUtils.join(vcard.stream().map(v -> @@ -195,15 +194,15 @@ public static List cleanupVcard(String vcardString, Function> vcardToHashMap(String vcardString){ - return vcardToHashMap("", vcardString); + public static ArrayList> vcardToMap(String vcardString){ + return vcardToMap("", vcardString); } static ArrayList vcardProps = null; static public boolean isVCardProp(String property) { if(vcardProps == null){ - vcardProps = new ArrayList(); + vcardProps = new ArrayList<>(); vcardProps.add(CCConstants.LOM_PROP_CONTRIBUTE_ENTITY); vcardProps.add(CCConstants.CCM_PROP_IO_REPL_LIFECYCLECONTRIBUTER_AUTHOR); vcardProps.add(CCConstants.CCM_PROP_IO_REPL_LIFECYCLECONTRIBUTER_PUBLISHER); @@ -241,13 +240,13 @@ static public boolean isVCardProp(String property) { * @param value * @return */ - public static HashMap getVCardHashMap(String type, String property, String value) { + public static Map getVCardMap(String type, String property, String value) { if(value == null) { - return new HashMap(); + return new HashMap<>(); } - HashMap result = null; + Map result = null; // VCard if (isVCardProp(property)) { @@ -255,14 +254,14 @@ public static HashMap getVCardHashMap(String type, String proper //split for multivalue vcards: String[] splitted = value.split(StringTool.escape(CCConstants.MULTIVALUE_SEPARATOR)); for(String split:splitted){ - ArrayList> vcards = vcardToHashMap(property, split); + ArrayList> vcards = vcardToMap(property, split); if (vcards != null) { if(vcards.size()==0) - return new HashMap(); + return new HashMap<>(); if(result == null){ result = vcards.get(0); }else{ - HashMap tmpVCardMap = vcards.get(0); + Map tmpVCardMap = vcards.get(0); for(Map.Entry vcardEntry : tmpVCardMap.entrySet()){ //check if vcardprop already has a value in result String vcardValInResult = (String)result.get(vcardEntry.getKey()); @@ -288,19 +287,19 @@ public static HashMap getVCardHashMap(String type, String proper * @return */ public static Map addVCardProperties(String nodeType, Map props) { - HashMap propsNew = new HashMap(); + Map propsNew = new HashMap<>(); propsNew.putAll(props); for(Map.Entry entry : props.entrySet()){ if(entry == null || entry.getKey() == null || entry.getValue() == null) continue; - HashMap vcard = getVCardHashMap(nodeType, entry.getKey(), entry.getValue().toString()); + Map vcard = getVCardMap(nodeType, entry.getKey(), entry.getValue().toString()); if(vcard!=null) propsNew.putAll(vcard); } return propsNew; } - public static boolean isPersonVCard(String prefix, HashMap data) { + public static boolean isPersonVCard(String prefix, Map data) { return data.get(prefix+CCConstants.VCARD_GIVENNAME)!=null && !data.get(prefix+CCConstants.VCARD_GIVENNAME).toString().isEmpty() || data.containsKey(prefix+CCConstants.VCARD_SURNAME) && !data.get(prefix+CCConstants.VCARD_SURNAME).toString().isEmpty(); } -} \ No newline at end of file +} diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/tools/cache/FacetCache.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/tools/cache/FacetCache.java index bd23feaf1b..747ef2fa84 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/tools/cache/FacetCache.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/tools/cache/FacetCache.java @@ -1,28 +1,4 @@ /** - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * * */ package org.edu_sharing.repository.server.tools.cache; @@ -32,44 +8,44 @@ import java.util.concurrent.ConcurrentHashMap; public class FacetCache { - /** - * Map>> - */ - private static Map>> facetCache = new ConcurrentHashMap>>(); - - public void add(String cacheId, String property, String value, Integer count){ - Map> propsToCountMap = facetCache.get(cacheId); - if(propsToCountMap == null){ - propsToCountMap = new ConcurrentHashMap>(); - facetCache.put(cacheId, propsToCountMap); - } - - Map valuesCountmap = propsToCountMap.get(property); - if(valuesCountmap == null){ - valuesCountmap = new ConcurrentHashMap(); - propsToCountMap.put(property, valuesCountmap); - } - valuesCountmap.put(value, count); - } - - public Map get(String cacheId, String property){ - Map> propsToCountMap = facetCache.get(cacheId); - if(propsToCountMap != null){ - Map synchMap = propsToCountMap.get(property); - if(synchMap != null && synchMap.size() > 0){ - //we need a normal hashMap it seems that ConcurrentHashMaps can not be rpc serialized by gwt - HashMap toReturn = new HashMap(); - for(Map.Entry entry:synchMap.entrySet()){ - toReturn.put(entry.getKey(),entry.getValue()); - } - return toReturn; - } - } - return null; - } + /** + * Map>> + */ + private static Map>> facetCache = new ConcurrentHashMap>>(); + + public void add(String cacheId, String property, String value, Integer count) { + Map> propsToCountMap = facetCache.get(cacheId); + if (propsToCountMap == null) { + propsToCountMap = new ConcurrentHashMap<>(); + facetCache.put(cacheId, propsToCountMap); + } + + Map valuesCountmap = propsToCountMap.get(property); + if (valuesCountmap == null) { + valuesCountmap = new ConcurrentHashMap<>(); + propsToCountMap.put(property, valuesCountmap); + } + valuesCountmap.put(value, count); + } + + public Map get(String cacheId, String property) { + Map> propsToCountMap = facetCache.get(cacheId); + if (propsToCountMap != null) { + Map synchMap = propsToCountMap.get(property); + if (synchMap != null && synchMap.size() > 0) { + //we need a normal hashMap it seems that ConcurrentHashMaps can not be rpc serialized by gwt + Map toReturn = new HashMap<>(); + for (Map.Entry entry : synchMap.entrySet()) { + toReturn.put(entry.getKey(), entry.getValue()); + } + return toReturn; + } + } + return null; + } + + public static Map>> getFacetCache() { + return facetCache; + } - public static Map>> getFacetCache() { - return facetCache; - } - } diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/tools/cache/RepositoryCacheTool.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/tools/cache/RepositoryCacheTool.java index b52d318ce4..a49b6a082a 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/tools/cache/RepositoryCacheTool.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/tools/cache/RepositoryCacheTool.java @@ -48,7 +48,7 @@ public class RepositoryCacheTool { * @param rootfolderId * @throws Throwable */ - public void buildNewCache(HashMap authenticationInfo, String rootfolderId) throws Throwable { + public void buildNewCache(Map authenticationInfo, String rootfolderId) throws Throwable { Map> newCache = new ConcurrentHashMap>(); MCBaseClient mcBaseClient = RepoFactory.getInstance(ApplicationInfoList.getHomeRepository().getAppId(), @@ -57,9 +57,9 @@ public void buildNewCache(HashMap authenticationInfo, String rootfolderId) throw MCAlfrescoAPIClient apiClient = (MCAlfrescoAPIClient) mcBaseClient; long startMillies = System.currentTimeMillis(); logger.info("starting getChildrenRecursive"); - Map> childRecursive = buildCache(rootfolderId, CCConstants.CCM_TYPE_IO); + Map> childRecursive = buildCache(rootfolderId, CCConstants.CCM_TYPE_IO); logger.info("getChildrenRecursive returned.starting to copy to cachemap. size:" + childRecursive.size()); - for (Map.Entry> entry : childRecursive.entrySet()) { + for (Map.Entry> entry : childRecursive.entrySet()) { newCache.put(entry.getKey().getId(), entry.getValue()); } @@ -95,7 +95,7 @@ public void buildNewCache(HashMap authenticationInfo, String rootfolderId) throw * @param authenticationInfo * @param rootfolderId */ - public void buildStickyCache(HashMap authenticationInfo, String rootfolderId) throws Throwable { + public void buildStickyCache(Map authenticationInfo, String rootfolderId) throws Throwable { logger.info("preparing first level subfolders for folder: " + nodeService.getProperty(new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE,rootfolderId),ContentModel.PROP_NAME )); @@ -106,12 +106,12 @@ public void buildStickyCache(HashMap authenticationInfo, String rootfolderId) th List> threads = new ArrayList<>(); - List childRefsThread = new ArrayList(); + List childRefsThread = new ArrayList<>(); long time = System.currentTimeMillis(); logger.info("THREAD_COUNT:" + THREAD_COUNT); - int modulo = (childAssocRefs.size() > THREAD_COUNT) ? (int) (childAssocRefs.size() / THREAD_COUNT) : 1; + int modulo = (childAssocRefs.size() > THREAD_COUNT) ? (childAssocRefs.size() / THREAD_COUNT) : 1; List> threadNodes = new ArrayList<>(); @@ -138,39 +138,35 @@ public void buildStickyCache(HashMap authenticationInfo, String rootfolderId) th int nr = j; threads.add(() -> { - RunAsWork runAs = new RunAsWork() { - @Override - public Void doWork() throws Exception { + RunAsWork runAs = () -> { + ApplicationContext applicationContext = AlfAppContextGate.getApplicationContext(); - ApplicationContext applicationContext = AlfAppContextGate.getApplicationContext(); + ServiceRegistry sr = (ServiceRegistry) applicationContext + .getBean(ServiceRegistry.SERVICE_REGISTRY); + NodeService nodeService = sr.getNodeService(); - ServiceRegistry sr = (ServiceRegistry) applicationContext - .getBean(ServiceRegistry.SERVICE_REGISTRY); - NodeService nodeService = sr.getNodeService(); + List childRefPage = new ArrayList<>(threadData); + logger.info("thread nr:" + nr + " got's " + childRefPage.size()); + for (String cr : childRefPage) { + long startMillies = System.currentTimeMillis(); - List childRefPage = new ArrayList<>(threadData); - logger.info("thread nr:" + nr + " got's " + childRefPage.size()); - for (String cr : childRefPage) { - long startMillies = System.currentTimeMillis(); + logger.info("thread nr:" + nr + " starting getChildrenRecursive for folder:" + nodeService + .getProperty(new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, cr), ContentModel.PROP_NAME)); - logger.info("thread nr:" + nr + " starting getChildrenRecursive for folder:" + nodeService - .getProperty(new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, cr), ContentModel.PROP_NAME)); + try { + buildCache(cr, CCConstants.CCM_TYPE_IO); - try { - buildCache(cr, CCConstants.CCM_TYPE_IO); + } catch (Throwable e) { + logger.error("thread nr:" + nr + e.getMessage(), e); + } + long endMillies = System.currentTimeMillis(); + long diff = (endMillies - startMillies) / 1000; + long diffMinutes = diff / 60; + } - } catch (Throwable e) { - logger.error("thread nr:" + nr + e.getMessage(), e); - } - long endMillies = System.currentTimeMillis(); - long diff = (endMillies - startMillies) / 1000; - long diffMinutes = diff / 60; - } + return null; - return null; - - } - }; + }; AuthenticationUtil.runAsSystem(runAs); @@ -208,7 +204,7 @@ public Void doWork() throws Exception { } - private Map> buildCache(String parent, String type) { + private Map> buildCache(String parent, String type) { List refs = NodeServiceFactory.getLocalService().getChildrenRecursive(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, parent, Collections.singletonList(type), RecurseMode.Folders); return refs.stream().collect(Collectors.toMap(ref -> ref, ref -> { diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/tools/forms/DuplicateFinder.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/tools/forms/DuplicateFinder.java index 7fa5662dad..7fba81824b 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/tools/forms/DuplicateFinder.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/tools/forms/DuplicateFinder.java @@ -1,193 +1,167 @@ /** - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * * */ package org.edu_sharing.repository.server.tools.forms; -import java.util.HashMap; import java.util.Map; import org.edu_sharing.repository.client.tools.CCConstants; -import org.edu_sharing.repository.server.RepoFactory; import org.edu_sharing.repository.server.tools.ApplicationInfoList; import org.edu_sharing.service.nodeservice.NodeServiceFactory; import org.edu_sharing.service.nodeservice.NodeServiceHelper; public class DuplicateFinder { - - /** - * finds out if the value for property is taken by another node in nodes - * @param nodes - * @param property - * @param value - * @return - */ - public boolean valueForPropIsTaken(HashMap> nodes, String property, String value){ - for(Map.Entry> entryNode : nodes.entrySet()){ - HashMap properties = entryNode.getValue(); - if(properties.get(property)!=null && properties.get(property) instanceof String && value.equalsIgnoreCase((String)properties.get(property))) - return true; - } - return false; - } - - /** - * finds out if the value for property is taken by another node in nodes. - * the currentNodeId is ignored. use this method for updates - * - * @param nodes - * @param currentNodeId - * @param property - * @param value - * @return - */ - public boolean valueForPropIsTaken(HashMap> nodes, String currentNodeId, String property, String value){ - for(Map.Entry> entryNode : nodes.entrySet()){ - - //ignore yourself ;-) - if(entryNode.getKey().equals(currentNodeId)) continue; - - HashMap properties = entryNode.getValue(); - for(Map.Entry entryProp : properties.entrySet()){ - - if(entryProp.getKey().equals(property) && entryProp.getValue() != null && entryProp.getValue().equals(value)){ - return true; - } - } - } - return false; - } - - /** - * - * @param nodes nodes to check - * @param currentNodeId nodeid to ignore(when its an update) - * @param property the property to check - * @param value the value to check - * @return - */ - public String getUniqueValue(HashMap> nodes, String currentNodeId, String property, String value){ - int cm_name_exists_counter = 2; - - String[] splitted = value.split("\\."); - - String value0 = (splitted.length > 0 )? splitted[0] : value; - String result = value; - - while(valueForPropIsTaken(nodes, currentNodeId, CCConstants.CM_NAME, result)){ - result = value0 + cm_name_exists_counter; - if(splitted.length > 1){ - for(int i = 1; i < splitted.length;i++){ - result = result +"."+splitted[i]; - } - } - cm_name_exists_counter++; - } - - return result; - } - - public String getUniqueValue(String parentId, String property, String value){ - int cm_name_exists_counter = 2; - - String[] splitted = value.split("\\."); - String value0 = (splitted.length > 0 )? splitted[0] : value; - String result = value; - while(NodeServiceFactory.getLocalService().findNodeByName(parentId, result) != null){ - result = value0 + " - " + cm_name_exists_counter; - if(splitted.length > 1){ - for(int i = 1; i < splitted.length;i++){ - result = result +"."+splitted[i]; - } - } - cm_name_exists_counter++; - } - - return result; - } - - /** - * @DEPRECATED - * Do not use this method accepting a HashMap, since the HashMap building is too slow - * @param nodes - * @param property - * @param value - * @return - */ - public String getUniqueValue(HashMap> nodes, String property, String value){ - int cm_name_exists_counter = 2; - - String[] splitted = value.split("\\."); - String value0 = (splitted.length > 0 )? splitted[0] : value; - String result = value; - while(valueForPropIsTaken(nodes, CCConstants.CM_NAME, result)){ - result = value0 + " - " + cm_name_exists_counter; - if(splitted.length > 1){ - for(int i = 1; i < splitted.length;i++){ - result = result +"."+splitted[i]; - } - } - cm_name_exists_counter++; - } - - return result; - } - - /** - * replaces CM_NAME prop with an unique and clean safeable name - * @param currentLevelObjects - * @param propsToSafe - */ - public void transformToSafeName(HashMap> currentLevelObjects, HashMap propsToSafe){ - - String cmNameReadableName = (String) propsToSafe.get(CCConstants.CM_NAME); - - // only when there is an title - if (cmNameReadableName != null) { - - // replace ie fakepath like C:\fakepath\test.png - String replaceFakePathPrefixRegEx = "^[A-Za-z]:\\\\fakepath\\\\"; - String fakePaceCleanedString = cmNameReadableName.replaceFirst(replaceFakePathPrefixRegEx, ""); - if (fakePaceCleanedString.length() > 0) { - cmNameReadableName = fakePaceCleanedString; - } - - // replace chars that can lead to an - // org.alfresco.repo.node.integrity.IntegrityException - cmNameReadableName = cmNameReadableName.replaceAll(ApplicationInfoList.getHomeRepository().getValidatorRegexCMName(), "_"); - - //replace ending dot with nothing - cmNameReadableName = cmNameReadableName.replaceAll("[\\.]*$", ""); - cmNameReadableName = NodeServiceHelper.cleanupCmName(cmNameReadableName); - - cmNameReadableName = new DuplicateFinder().getUniqueValue(currentLevelObjects, CCConstants.CM_NAME, cmNameReadableName); - propsToSafe.put(CCConstants.CM_NAME, cmNameReadableName); - - } - - - } + + /** + * finds out if the value for property is taken by another node in nodes + * @param nodes + * @param property + * @param value + * @return + */ + public boolean valueForPropIsTaken(Map> nodes, String property, String value) { + for (Map.Entry> entryNode : nodes.entrySet()) { + Map properties = entryNode.getValue(); + if (properties.get(property) != null && properties.get(property) instanceof String && value.equalsIgnoreCase((String) properties.get(property))) + return true; + } + return false; + } + + /** + * finds out if the value for property is taken by another node in nodes. + * the currentNodeId is ignored. use this method for updates + * + * @param nodes + * @param currentNodeId + * @param property + * @param value + * @return + */ + public boolean valueForPropIsTaken(Map> nodes, String currentNodeId, String property, String value) { + for (Map.Entry> entryNode : nodes.entrySet()) { + + //ignore yourself ;-) + if (entryNode.getKey().equals(currentNodeId)) continue; + + Map properties = entryNode.getValue(); + for (Map.Entry entryProp : properties.entrySet()) { + + if (entryProp.getKey().equals(property) && entryProp.getValue() != null && entryProp.getValue().equals(value)) { + return true; + } + } + } + return false; + } + + /** + * + * @param nodes nodes to check + * @param currentNodeId nodeid to ignore(when its an update) + * @param property the property to check + * @param value the value to check + * @return + */ + public String getUniqueValue(Map> nodes, String currentNodeId, String property, String value) { + int cm_name_exists_counter = 2; + + String[] splitted = value.split("\\."); + + String value0 = (splitted.length > 0) ? splitted[0] : value; + String result = value; + + while (valueForPropIsTaken(nodes, currentNodeId, CCConstants.CM_NAME, result)) { + result = value0 + cm_name_exists_counter; + if (splitted.length > 1) { + for (int i = 1; i < splitted.length; i++) { + result = result + "." + splitted[i]; + } + } + cm_name_exists_counter++; + } + + return result; + } + + public String getUniqueValue(String parentId, String property, String value) { + int cm_name_exists_counter = 2; + + String[] splitted = value.split("\\."); + String value0 = (splitted.length > 0) ? splitted[0] : value; + String result = value; + while (NodeServiceFactory.getLocalService().findNodeByName(parentId, result) != null) { + result = value0 + " - " + cm_name_exists_counter; + if (splitted.length > 1) { + for (int i = 1; i < splitted.length; i++) { + result = result + "." + splitted[i]; + } + } + cm_name_exists_counter++; + } + + return result; + } + + /** + * @DEPRECATED + * Do not use this method accepting a Map, since the Map building is too slow + * @param nodes + * @param property + * @param value + * @return + */ + public String getUniqueValue(Map> nodes, String property, String value) { + int cm_name_exists_counter = 2; + + String[] splitted = value.split("\\."); + String value0 = (splitted.length > 0) ? splitted[0] : value; + String result = value; + while (valueForPropIsTaken(nodes, CCConstants.CM_NAME, result)) { + result = value0 + " - " + cm_name_exists_counter; + if (splitted.length > 1) { + for (int i = 1; i < splitted.length; i++) { + result = result + "." + splitted[i]; + } + } + cm_name_exists_counter++; + } + + return result; + } + + /** + * replaces CM_NAME prop with an unique and clean safeable name + * @param currentLevelObjects + * @param propsToSafe + */ + public void transformToSafeName(Map> currentLevelObjects, Map propsToSafe) { + + String cmNameReadableName = (String) propsToSafe.get(CCConstants.CM_NAME); + + // only when there is an title + if (cmNameReadableName != null) { + + // replace ie fakepath like C:\fakepath\test.png + String replaceFakePathPrefixRegEx = "^[A-Za-z]:\\\\fakepath\\\\"; + String fakePaceCleanedString = cmNameReadableName.replaceFirst(replaceFakePathPrefixRegEx, ""); + if (fakePaceCleanedString.length() > 0) { + cmNameReadableName = fakePaceCleanedString; + } + + // replace chars that can lead to an + // org.alfresco.repo.node.integrity.IntegrityException + cmNameReadableName = cmNameReadableName.replaceAll(ApplicationInfoList.getHomeRepository().getValidatorRegexCMName(), "_"); + + //replace ending dot with nothing + cmNameReadableName = cmNameReadableName.replaceAll("[\\.]*$", ""); + cmNameReadableName = NodeServiceHelper.cleanupCmName(cmNameReadableName); + + cmNameReadableName = new DuplicateFinder().getUniqueValue(currentLevelObjects, CCConstants.CM_NAME, cmNameReadableName); + propsToSafe.put(CCConstants.CM_NAME, cmNameReadableName); + + } + + + } } diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/tools/security/AllSessions.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/tools/security/AllSessions.java index c8979d308a..a576ec2e10 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/tools/security/AllSessions.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/tools/security/AllSessions.java @@ -25,7 +25,7 @@ static Map getInstance(){ writeLock.lock(); //check for null again to prevent the List is created once mor by a waiter on write lock if(allSessions == null){ - allSessions = Collections.synchronizedMap(new HashMap()); + allSessions = Collections.synchronizedMap(new HashMap<>()); } }finally{ writeLock.unlock(); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/update/UpdaterService.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/update/UpdaterService.java index 1e2896635c..23afd8973e 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/server/update/UpdaterService.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/server/update/UpdaterService.java @@ -177,7 +177,7 @@ private void executeUpdate(UpdateInfo x, boolean isTestRunner) { currentlyRunningUpdates.add(x.getId()); try { Protocol protocol = beanFactory.getBean(Protocol.class); - HashMap updateInfo = protocol.getSysUpdateEntry(x.getId()); + Map updateInfo = protocol.getSysUpdateEntry(x.getId()); if (updateInfo != null) { log.info("Update" + x.getId() + " already done at " + updateInfo.get(CCConstants.CCM_PROP_SYSUPDATE_DATE)); return; diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/tomcat/ClassHelper.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/tomcat/ClassHelper.java index 9b19d2e6b4..02f8dfc6b0 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/tomcat/ClassHelper.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/tomcat/ClassHelper.java @@ -39,7 +39,7 @@ public static List getSubclasses(Class clazz, String packageName){ public static List getStaticFields(Class clazz){ Field[] declaredFields = clazz.getDeclaredFields(); - List staticFields = new ArrayList(); + List staticFields = new ArrayList<>(); for (Field field : declaredFields) { if (java.lang.reflect.Modifier.isStatic(field.getModifiers())) { staticFields.add(field); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/update/ClassificationKWToGeneralKW.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/update/ClassificationKWToGeneralKW.java index de47daf5ef..adcfdc1f20 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/update/ClassificationKWToGeneralKW.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/update/ClassificationKWToGeneralKW.java @@ -87,7 +87,7 @@ private void runFromLevel(boolean test, String parentId) { } private void writeToGeneralKeyword(NodeRef nodeRef, List generalKeyWordList, List classificationKeywordList, boolean test) { - ArrayList newKeywordsList = new ArrayList(); + ArrayList newKeywordsList = new ArrayList<>(); if (generalKeyWordList != null) { newKeywordsList.addAll(generalKeyWordList); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/update/FixMissingUserstoreNode.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/update/FixMissingUserstoreNode.java index 0683e54861..12e984ac10 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/update/FixMissingUserstoreNode.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/update/FixMissingUserstoreNode.java @@ -50,7 +50,7 @@ public void execute(boolean test) { List children = nodeService.getChildAssocs(peopleContainer); - ArrayList missingUsers = new ArrayList(); + ArrayList missingUsers = new ArrayList<>(); for (ChildAssociationRef childref : children) { diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/update/Protocol.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/update/Protocol.java index 490db998ba..8ec6d9285b 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/update/Protocol.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/update/Protocol.java @@ -17,6 +17,7 @@ import java.io.Serializable; import java.util.Date; import java.util.HashMap; +import java.util.Map; @Component @Scope("prototype") @@ -45,13 +46,13 @@ public Protocol(AuthenticationService authenticationService, NodeService nodeSer this.userEnvironmentToolFactory = userEnvironmentToolFactory; } - public HashMap getSysUpdateEntry(String updaterId) throws Throwable{ + public Map getSysUpdateEntry(String updaterId) throws Throwable{ - HashMap authInfo = new HashMap<>(); + Map authInfo = new HashMap<>(); authInfo.put(CCConstants.AUTH_USERNAME, authenticationService.getCurrentUserName()); authInfo.put(CCConstants.AUTH_TICKET, authenticationService.getCurrentTicket()); String eduSystemFolderUpdate; - HashMap updateInfo; + Map updateInfo; eduSystemFolderUpdate = userEnvironmentToolFactory.createEnvironmentTool(ApplicationInfoList.getHomeRepository().getAppId(), authInfo) .getEdu_SharingSystemFolderUpdate(); @@ -62,13 +63,13 @@ public HashMap getSysUpdateEntry(String updaterId) throws Throwab } public void writeSysUpdateEntry(String updaterId) throws Throwable{ - HashMap updateInfoProps = new HashMap<>(); + Map updateInfoProps = new HashMap<>(); updateInfoProps.put(ContentModel.PROP_NAME, updaterId); updateInfoProps.put(QName.createQName(CCConstants.CCM_PROP_SYSUPDATE_ID),updaterId); updateInfoProps.put(QName.createQName(CCConstants.CCM_PROP_SYSUPDATE_DATE),new Date()); - HashMap authInfo = new HashMap<>(); + Map authInfo = new HashMap<>(); authInfo.put(CCConstants.AUTH_USERNAME, authenticationService.getCurrentUserName()); authInfo.put(CCConstants.AUTH_TICKET, authenticationService.getCurrentTicket()); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/update/Release_1_6_SystemFolderNameRename.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/update/Release_1_6_SystemFolderNameRename.java index 8b83a64a43..def529c4e0 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/update/Release_1_6_SystemFolderNameRename.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/update/Release_1_6_SystemFolderNameRename.java @@ -44,8 +44,8 @@ public void execute(boolean test) { for (String user : users) { log.info("processing user:" + user); String homefolderId = mcAlfrescoBaseClient.getHomeFolderID(user); - HashMap> children = mcAlfrescoBaseClient.getChildren(homefolderId); - for (Map.Entry> entry : children.entrySet()) { + Map> children = mcAlfrescoBaseClient.getChildren(homefolderId); + for (Map.Entry> entry : children.entrySet()) { String mapType = (String) entry.getValue().get(CCConstants.CCM_PROP_MAP_TYPE); String folderId = (String) entry.getValue().get(CCConstants.SYS_PROP_NODE_UID); if (mapType != null) { @@ -68,7 +68,7 @@ public void execute(boolean test) { } } - private void updateFolder(String folderId, HashMap suroundingNodes, String i8nKey, boolean test) throws Exception { + private void updateFolder(String folderId, Map> suroundingNodes, String i8nKey, boolean test) throws Exception { HashMap newProps = new HashMap(); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/update/Release_1_7_SubObjectsToFlatObjects.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/update/Release_1_7_SubObjectsToFlatObjects.java index d5f83c81a0..24616fffa3 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/update/Release_1_7_SubObjectsToFlatObjects.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/update/Release_1_7_SubObjectsToFlatObjects.java @@ -185,7 +185,7 @@ private void lomSubTypesTransfering(boolean test, NodeRef ioNodeRef) { List childAssocs = nodeService.getChildAssocs(ioNodeRef); - Map ioPropsToAdd = new HashMap(); + Map ioPropsToAdd = new HashMap<>(); for (ChildAssociationRef childAssoc : childAssocs) { if (nodeService.getType(childAssoc.getChildRef()).equals(QName.createQName(CCConstants.LOM_TYPE_CLASSIFICATION))) { @@ -242,7 +242,7 @@ private void lomSubTypesTransfering(boolean test, NodeRef ioNodeRef) { QName qnameProperty = QName.createQName(contributerProperty); if (allPropertiesInAlf.contains(qnameProperty)) { ArrayList entities = (ArrayList) ioPropsToAdd.get(qnameProperty); - if (entities == null) entities = new ArrayList(); + if (entities == null) entities = new ArrayList<>(); entities.add(entity.getDefaultValue()); ioPropsToAdd.put(qnameProperty, entities); } else { diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/update/Release_3_2_DefaultScope.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/update/Release_3_2_DefaultScope.java index 2746779c1b..0f72949362 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/update/Release_3_2_DefaultScope.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/update/Release_3_2_DefaultScope.java @@ -78,7 +78,7 @@ void setDefautScope(NodeRef parent, boolean test) { log.info("updateing node:" + noderef + " in " + nodeService.getPath(child.getChildRef()) + " processedNodeCounter:" + processedNodeCounter); if (!test) { - Map aspectProps = new HashMap(); + Map aspectProps = new HashMap<>(); aspectProps.put(QName.createQName(CCConstants.CCM_PROP_EDUSCOPE_NAME), null); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/update/Release_5_0_NotifyRefactoring.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/update/Release_5_0_NotifyRefactoring.java index 882ad7ce32..81d9779481 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/update/Release_5_0_NotifyRefactoring.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/update/Release_5_0_NotifyRefactoring.java @@ -140,7 +140,7 @@ private void migrate(NodeRef nodeRef) { log.warn("getPermissions() failed: "+e.getMessage()); throw new RuntimeException(e); } - List directlySetAces = new ArrayList(); + List directlySetAces = new ArrayList<>(); for (ACE ace : acl.getAces()) { if (!ace.isInherited()) { directlySetAces.add(ace); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/update/SchoolContext.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/update/SchoolContext.java index f8c36a726f..e53585be6b 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/update/SchoolContext.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/update/SchoolContext.java @@ -113,7 +113,7 @@ NodeRef getSchoolContextFolder() throws Throwable { sysFolderName); if (sysFolderNodeRef == null) { - Map rootFolderProps = new HashMap(); + Map rootFolderProps = new HashMap<>(); rootFolderProps.put(ContentModel.PROP_NAME, sysFolderName); sysFolderNodeRef = nodeService.createNode(sysFolderParent, ContentModel.ASSOC_CONTAINS, QName.createQName(sysFolderName), QName.createQName(CCConstants.CCM_TYPE_MAP), rootFolderProps) @@ -129,7 +129,7 @@ NodeRef getEntityFolder(String entityFolderName) throws Throwable { NodeRef entityFolderNodeRef = nodeService.getChildByName(sysFolderNodeRef, ContentModel.ASSOC_CONTAINS, entityFolderName); if (entityFolderNodeRef == null) { - Map props = new HashMap(); + Map props = new HashMap<>(); props.put(ContentModel.PROP_NAME, entityFolderName); entityFolderNodeRef = nodeService.createNode(sysFolderNodeRef, ContentModel.ASSOC_CONTAINS, QName.createQName(entityFolderName), QName.createQName(CCConstants.CCM_TYPE_MAP), props) @@ -148,7 +148,7 @@ NodeRef getRelationsFolder() throws Throwable { NodeRef relationsFolderNodeRef = nodeService.getChildByName(sysFolderNodeRef, ContentModel.ASSOC_CONTAINS, relationsFolderName); if (relationsFolderNodeRef == null) { - Map props = new HashMap(); + Map props = new HashMap<>(); props.put(ContentModel.PROP_NAME, relationsFolderName); relationsFolderNodeRef = nodeService.createNode(sysFolderNodeRef, ContentModel.ASSOC_CONTAINS, QName.createQName(relationsFolderName), QName.createQName(CCConstants.CCM_TYPE_MAP), props) @@ -162,7 +162,7 @@ public String createEntities(int exceltab, int keyCol, int nameCol, String type, try { - HashMap keyNamesMap = new HashMap(); + Map keyNamesMap = new HashMap<>(); Sheet sheetBL = workbook.getSheetAt(exceltab); logger.info("nr:" + exceltab + " name:" + sheetBL.getSheetName()); @@ -216,7 +216,7 @@ public String createEntities(int exceltab, int keyCol, int nameCol, String type, for (Map.Entry keyName : keyNamesMap.entrySet()) { - Map props = new HashMap(); + Map props = new HashMap<>(); if (keyProp != null) { props.put(QName.createQName(keyProp), keyName.getKey()); @@ -257,14 +257,14 @@ public String createEntities(int exceltab, int keyCol, int nameCol, String type, public void createRelations(int relationTab, int typeOfSchoolKeyCol, int disciplineKeyCol) { logger.info("start creating relations"); // Prepare - HashMap typeOfSchoolsMap = new HashMap(); + Map typeOfSchoolsMap = new HashMap<>(); List typeOfSchools = getNodeRefs(TYPE_TYPEOFSCHOOL); for (NodeRef nodeRef : typeOfSchools) { typeOfSchoolsMap.put((String) nodeService.getProperty(nodeRef, QName.createQName(PROP_TYPEOFSCHOOL_KEY)), nodeRef); } - HashMap disciplinesMap = new HashMap(); + Map disciplinesMap = new HashMap<>(); List disciplines = getNodeRefs(TYPE_DISCIPLINE); for (NodeRef nodeRef : disciplines) { disciplinesMap.put((String) nodeService.getProperty(nodeRef, QName.createQName(PROP_DISCIPLINE_KEY)), @@ -277,7 +277,7 @@ public void createRelations(int relationTab, int typeOfSchoolKeyCol, int discipl try { NodeRef relationsFolderNodeRef = getRelationsFolder(); - ArrayList processedTosDis = new ArrayList(); + ArrayList processedTosDis = new ArrayList<>(); for (Row row : relationSheet) { // 0 is the header row if (rowCounter == 0){ @@ -312,7 +312,7 @@ public void createRelations(int relationTab, int typeOfSchoolKeyCol, int discipl if (rs.length() == 0 && !processedTosDis.contains(checkProcessed)) { - Map props = new HashMap(); + Map props = new HashMap<>(); props.put(QName.createQName(PROP_REF_TYPEOFSCHOOL), tosNodeRef); props.put(QName.createQName(PROP_REF_DISCIPLINE), dNodeRef); @@ -350,14 +350,14 @@ public void createRelations(int relationTab, int typeOfSchoolKeyCol, int discipl * * @param typeOfSchoolDisciplineInclusion */ - public void combineTypeOfSchool(HashMap typeOfSchoolDisciplineInclusion) { + public void combineTypeOfSchool(Map typeOfSchoolDisciplineInclusion) { logger.info("starting"); try { NodeRef relationsFolderNodeRef = getRelationsFolder(); List typeOfSchools = getNodeRefs(TYPE_TYPEOFSCHOOL); List disciplines = getNodeRefs(TYPE_DISCIPLINE); - ArrayList exclusionsForCommonSchoolTypes = new ArrayList(); + ArrayList exclusionsForCommonSchoolTypes = new ArrayList<>(); for (Map.Entry entry : typeOfSchoolDisciplineInclusion.entrySet()) { exclusionsForCommonSchoolTypes.addAll(Arrays.asList(entry.getValue())); } @@ -380,7 +380,7 @@ public void combineTypeOfSchool(HashMap typeOfSchoolDiscipline continue; } - Map props = new HashMap(); + Map props = new HashMap<>(); props.put(QName.createQName(PROP_REF_TYPEOFSCHOOL), typeOfSchool); props.put(QName.createQName(PROP_REF_DISCIPLINE), discipline); @@ -473,7 +473,7 @@ public void combine(NodeRef[] federalStatesParam) { continue; } - Map props = new HashMap(); + Map props = new HashMap<>(); props.put(QName.createQName(PROP_REF_FEDERALSTATE), federalState); props.put(QName.createQName(PROP_REF_TYPEOFSCHOOL), typeOfSchool); props.put(QName.createQName(PROP_REF_DISCIPLINE), discipline); @@ -533,11 +533,11 @@ public void combine(NodeRef[] federalStatesParam) { NodeRef getRelationContainer(NodeRef relationRoot, int counter) { - String foldername = new Integer((int) counter / 1000).toString(); + String foldername = new Integer(counter / 1000).toString(); NodeRef result = nodeService.getChildByName(relationRoot, ContentModel.ASSOC_CONTAINS, foldername); if (result == null) { - Map props = new HashMap(); + Map props = new HashMap<>(); props.put(ContentModel.PROP_NAME, foldername); result = nodeService.createNode(relationRoot, ContentModel.ASSOC_CONTAINS, diff --git a/Backend/services/core/src/main/java/org/edu_sharing/repository/update/SystemFolderNameToDisplayName.java b/Backend/services/core/src/main/java/org/edu_sharing/repository/update/SystemFolderNameToDisplayName.java index 661c95db89..e2014f98e3 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/repository/update/SystemFolderNameToDisplayName.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/repository/update/SystemFolderNameToDisplayName.java @@ -76,8 +76,8 @@ public void execute(boolean test) { for (String user : users) { String homefolderId = mcAlfrescoBaseClient.getHomeFolderID(user); - HashMap> children = mcAlfrescoBaseClient.getChildren(homefolderId); - for (Map.Entry> entry : children.entrySet()) { + Map> children = mcAlfrescoBaseClient.getChildren(homefolderId); + for (Map.Entry> entry : children.entrySet()) { String name = (String) entry.getValue().get(CCConstants.CM_NAME); String type = (String) entry.getValue().get(CCConstants.NODETYPE); String folderId = (String) entry.getValue().get(CCConstants.SYS_PROP_NODE_UID); @@ -121,9 +121,9 @@ public void execute(boolean test) { log.info("nr of updated objects:" + counter); } - private void updateFolder(String folderId, HashMap suroundingNodes, String mapType, String displayName, boolean test) throws Exception { + private void updateFolder(String folderId, Map> suroundingNodes, String mapType, String displayName, boolean test) throws Exception { - HashMap newProps = new HashMap(); + Map newProps = new HashMap<>(); String uniqueValue = new DuplicateFinder().getUniqueValue(suroundingNodes, folderId, CCConstants.CM_NAME, displayName); newProps.put(CCConstants.CM_NAME, uniqueValue); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/restservices/ApiAuthenticationFilter.java b/Backend/services/core/src/main/java/org/edu_sharing/restservices/ApiAuthenticationFilter.java index 338a048ae6..066609e21b 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/restservices/ApiAuthenticationFilter.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/restservices/ApiAuthenticationFilter.java @@ -2,10 +2,7 @@ import java.io.IOException; import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; +import java.util.*; import jakarta.servlet.FilterChain; import jakarta.servlet.FilterConfig; @@ -34,229 +31,221 @@ public class ApiAuthenticationFilter implements jakarta.servlet.Filter { - Logger logger = Logger.getLogger(ApiAuthenticationFilter.class); - - private TokenService tokenService; - private EduAuthentication eduAuthenticationService; - - private AuthenticationComponent authenticationComponent; - - @Override - public void destroy() { - } - - @Override - public void doFilter(ServletRequest req, ServletResponse resp, - FilterChain chain) throws IOException, ServletException { - - HttpServletRequest httpReq = (HttpServletRequest) req; - HttpServletResponse httpResp = (HttpServletResponse)resp; - - if("OPTIONS".equals(httpReq.getMethod())){ - chain.doFilter(req, resp); - return; - } - - HttpSession session = httpReq.getSession(true); - //session.setMaxInactiveInterval(30); - AuthenticationToolAPI authTool = new AuthenticationToolAPI(); - HashMap validatedAuth = authTool.validateAuthentication(session); - - AuthenticationFilter.handleLocale(true, httpReq.getHeader("locale"), httpReq, httpResp); - - String authHdr = httpReq.getHeader("Authorization"); - - // always take the header so we can auth when a guest is activated - if (authHdr != null) { - - if (authHdr.length() > 5 && authHdr.substring(0, 5).equalsIgnoreCase("BASIC")) { - logger.debug("auth is BASIC"); - validatedAuth = httpBasicAuth(authHdr); - if(validatedAuth != null) { - String succsessfullAuthMethod = SubsystemChainingAuthenticationService.getSuccessFullAuthenticationMethod(); - String authMethod = ("alfrescoNtlm1".equals(succsessfullAuthMethod) || "alfinst".equals(succsessfullAuthMethod)) ? CCConstants.AUTH_TYPE_DEFAULT : CCConstants.AUTH_TYPE + succsessfullAuthMethod; - String username = validatedAuth.get(CCConstants.AUTH_USERNAME); - authTool.storeAuthInfoInSession(username, validatedAuth.get(CCConstants.AUTH_TICKET), authMethod, session); - } - } else if (authHdr.length() > 6 && authHdr.substring(0, 6).equalsIgnoreCase("Bearer")) { - - logger.info("auth is OAuth"); - - String accessToken = authHdr.substring(6).trim(); - - try { - Token token = tokenService.getToken(accessToken); - - if (token != null) { - logger.info("oAuthToken:"+ token.getAccessToken() +" alfresco ticket:"+ token.getTicket()); - - //validate and set current user - authTool.storeAuthInfoInSession( - token.getUsername(), - token.getTicket(), - CCConstants.AUTH_TYPE_OAUTH, - session); - - session.setAttribute(CCConstants.AUTH_ACCESS_TOKEN, token.getAccessToken()); - - validatedAuth = authTool.validateAuthentication(session); - } - } catch (Exception ex) { - - logger.error(ex.getMessage(), ex); - } - }else if (authHdr.length() > 10 && authHdr.substring(0, 10).equalsIgnoreCase(CCConstants.AUTH_HEADER_EDU_TICKET)) { - String ticket = authHdr.substring(10).trim(); - if(ticket != null){ - if(authTool.validateTicket(ticket)){ - // Force a renew of all toolpermissions since they might have now changed! - ToolPermissionServiceFactory.getInstance().getAllAvailableToolPermissions(true); - //if its APIClient username is ignored and is figured out with authentication service - authTool.storeAuthInfoInSession(authTool.getCurrentUser(), ticket, CCConstants.AUTH_TYPE_TICKET, httpReq.getSession()); - validatedAuth = authTool.validateAuthentication(session); - } - } - } - - } - - List AUTHLESS_ENDPOINTS=Arrays.asList(new String[]{"/authentication","/_about","/config","/register","/sharing", - "/lti/v13/oidc/login_initiations", - "/lti/v13/lti13", - "/lti/v13/registration/dynamic", - "/lti/v13/jwks", - "/lti/v13/details", - "/ltiplatform/v13/openid-configuration", - "/ltiplatform/v13/openid-registration", - "/ltiplatform/v13/content"}); - List ADMIN_ENDPOINTS=Arrays.asList(new String[]{"/admin", "/bulk","/lti/v13/registration/static","/lti/v13/registration/url"}); - List DISABLED_ENDPOINTS=new ArrayList<>(); - - try { - if(!ConfigServiceFactory.getCurrentConfig(req).getValue("register.local",true)){ - if(ConfigServiceFactory.getCurrentConfig(req).getValue("register.recoverPassword", false)) { - DISABLED_ENDPOINTS.add("/register/v1/register"); - DISABLED_ENDPOINTS.add("/register/v1/activate"); - } else { - // disable whole api range - DISABLED_ENDPOINTS.add("/register"); - } - } - } catch (Exception e) {} - - boolean noAuthenticationNeeded=false; - for(String endpoint : AUTHLESS_ENDPOINTS){ - String pathInfo = httpReq.getPathInfo(); - if(pathInfo == null){ - continue; - } - - if(pathInfo.startsWith(endpoint)){ - noAuthenticationNeeded=true; - break; - } - } - boolean adminRequired=false; - for(String endpoint : ADMIN_ENDPOINTS){ - String pathInfo = httpReq.getPathInfo(); - if(pathInfo == null){ - continue; - } - - if(pathInfo.startsWith(endpoint)){ - adminRequired=true; - break; - } - } - - for(String endpoint : DISABLED_ENDPOINTS){ - String pathInfo = httpReq.getPathInfo(); - if(pathInfo == null){ - continue; - } - - if(pathInfo.startsWith(endpoint)){ - httpResp.setStatus(HttpServletResponse.SC_UNAUTHORIZED); - httpResp.flushBuffer(); - httpResp.getWriter().print("This endpoint is disabled via config"); - return; - } - } - - if(adminRequired && !AuthorityServiceFactory.getLocalService().isGlobalAdmin()){ - httpResp.setStatus(HttpServletResponse.SC_UNAUTHORIZED); - httpResp.flushBuffer(); - httpResp.getWriter().print("Admin rights are required for this endpoint"); - return; - } - - /** - * allow authless calls with AUTH_SINGLE_USE_NODEID by appauth - */ - boolean trustedAuth = false; - if(ContextManagementFilter.accessTool != null && ContextManagementFilter.accessTool.get() != null){ - trustedAuth = true; - } - - // ignore the auth for the login - if(validatedAuth == null && (!noAuthenticationNeeded && !trustedAuth)){ - String pathInfo = httpReq.getPathInfo(); - if(pathInfo != null && pathInfo.equals("/openapi.json")) - httpResp.setHeader("WWW-Authenticate", "BASIC realm=\""+ "Edu-Sharing Rest API" +"\""); - httpResp.setStatus(HttpServletResponse.SC_UNAUTHORIZED); - httpResp.flushBuffer(); - return; - } - - // Chain other filters - chain.doFilter(req, resp); - } - - public static HashMap httpBasicAuth(String authHdr) { - HashMap validatedAuth = null; - AuthenticationToolAPI authTool = new AuthenticationToolAPI(); - - // Basic authentication details present - - String basicAuth = new String(java.util.Base64.getDecoder().decode(authHdr.substring(6)), StandardCharsets.ISO_8859_1); - - // Split the username and password - - String username = null; - String password = null; - - int pos = basicAuth.indexOf(":"); - if (pos != -1) { - username = basicAuth.substring(0, pos); - password = basicAuth.substring(pos + 1); - } else { - username = basicAuth; - password = ""; - } - - try { - - // Authenticate the user - validatedAuth = authTool.createNewSession(username, password); - } catch (Exception ex) { - Logger.getLogger(ApiAuthenticationFilter.class).error(ex.getMessage(), ex); - } - return validatedAuth; - } - - @Override - public void init(FilterConfig arg0) throws ServletException { - - ApplicationContext eduApplicationContext = - org.edu_sharing.spring.ApplicationContextFactory.getApplicationContext(); - - tokenService = (TokenService) eduApplicationContext.getBean("oauthTokenService"); - eduAuthenticationService = (EduAuthentication) eduApplicationContext.getBean("authenticationService"); - - ApplicationContext alfApplicationContext = AlfAppContextGate.getApplicationContext(); - - authenticationComponent = (AuthenticationComponent) alfApplicationContext.getBean("authenticationComponent"); - - } + Logger logger = Logger.getLogger(ApiAuthenticationFilter.class); + + private TokenService tokenService; + + @Override + public void destroy() { + } + + @Override + public void doFilter(ServletRequest req, ServletResponse resp, + FilterChain chain) throws IOException, ServletException { + + HttpServletRequest httpReq = (HttpServletRequest) req; + HttpServletResponse httpResp = (HttpServletResponse) resp; + + if ("OPTIONS".equals(httpReq.getMethod())) { + chain.doFilter(req, resp); + return; + } + + HttpSession session = httpReq.getSession(true); + //session.setMaxInactiveInterval(30); + AuthenticationToolAPI authTool = new AuthenticationToolAPI(); + Map validatedAuth = authTool.validateAuthentication(session); + + AuthenticationFilter.handleLocale(true, httpReq.getHeader("locale"), httpReq, httpResp); + + String authHdr = httpReq.getHeader("Authorization"); + + // always take the header so we can auth when a guest is activated + if (authHdr != null) { + + if (authHdr.length() > 5 && authHdr.substring(0, 5).equalsIgnoreCase("BASIC")) { + logger.debug("auth is BASIC"); + validatedAuth = httpBasicAuth(authHdr); + if (validatedAuth != null) { + String succsessfullAuthMethod = SubsystemChainingAuthenticationService.getSuccessFullAuthenticationMethod(); + String authMethod = ("alfrescoNtlm1".equals(succsessfullAuthMethod) || "alfinst".equals(succsessfullAuthMethod)) ? CCConstants.AUTH_TYPE_DEFAULT : CCConstants.AUTH_TYPE + succsessfullAuthMethod; + String username = validatedAuth.get(CCConstants.AUTH_USERNAME); + authTool.storeAuthInfoInSession(username, validatedAuth.get(CCConstants.AUTH_TICKET), authMethod, session); + } + } else if (authHdr.length() > 6 && authHdr.substring(0, 6).equalsIgnoreCase("Bearer")) { + + logger.info("auth is OAuth"); + + String accessToken = authHdr.substring(6).trim(); + + try { + Token token = tokenService.getToken(accessToken); + + if (token != null) { + logger.info("oAuthToken:" + token.getAccessToken() + " alfresco ticket:" + token.getTicket()); + + //validate and set current user + authTool.storeAuthInfoInSession( + token.getUsername(), + token.getTicket(), + CCConstants.AUTH_TYPE_OAUTH, + session); + + session.setAttribute(CCConstants.AUTH_ACCESS_TOKEN, token.getAccessToken()); + + validatedAuth = authTool.validateAuthentication(session); + } + } catch (Exception ex) { + + logger.error(ex.getMessage(), ex); + } + } else if (authHdr.length() > 10 && authHdr.substring(0, 10).equalsIgnoreCase(CCConstants.AUTH_HEADER_EDU_TICKET)) { + String ticket = authHdr.substring(10).trim(); + if (ticket != null) { + if (authTool.validateTicket(ticket)) { + // Force a renew of all toolpermissions since they might have now changed! + ToolPermissionServiceFactory.getInstance().getAllAvailableToolPermissions(true); + //if its APIClient username is ignored and is figured out with authentication service + authTool.storeAuthInfoInSession(authTool.getCurrentUser(), ticket, CCConstants.AUTH_TYPE_TICKET, httpReq.getSession()); + validatedAuth = authTool.validateAuthentication(session); + } + } + } + + } + + List AUTHLESS_ENDPOINTS = Arrays.asList(new String[]{"/authentication", "/_about", "/config", "/register", "/sharing", + "/lti/v13/oidc/login_initiations", + "/lti/v13/lti13", + "/lti/v13/registration/dynamic", + "/lti/v13/jwks", + "/lti/v13/details", + "/ltiplatform/v13/openid-configuration", + "/ltiplatform/v13/openid-registration", + "/ltiplatform/v13/content"}); + List ADMIN_ENDPOINTS = Arrays.asList(new String[]{"/admin", "/bulk", "/lti/v13/registration/static", "/lti/v13/registration/url"}); + List DISABLED_ENDPOINTS = new ArrayList<>(); + + try { + if (!ConfigServiceFactory.getCurrentConfig(req).getValue("register.local", true)) { + if (ConfigServiceFactory.getCurrentConfig(req).getValue("register.recoverPassword", false)) { + DISABLED_ENDPOINTS.add("/register/v1/register"); + DISABLED_ENDPOINTS.add("/register/v1/activate"); + } else { + // disable whole api range + DISABLED_ENDPOINTS.add("/register"); + } + } + } catch (Exception e) { + } + + boolean noAuthenticationNeeded = false; + for (String endpoint : AUTHLESS_ENDPOINTS) { + String pathInfo = httpReq.getPathInfo(); + if (pathInfo == null) { + continue; + } + + if (pathInfo.startsWith(endpoint)) { + noAuthenticationNeeded = true; + break; + } + } + boolean adminRequired = false; + for (String endpoint : ADMIN_ENDPOINTS) { + String pathInfo = httpReq.getPathInfo(); + if (pathInfo == null) { + continue; + } + + if (pathInfo.startsWith(endpoint)) { + adminRequired = true; + break; + } + } + + for (String endpoint : DISABLED_ENDPOINTS) { + String pathInfo = httpReq.getPathInfo(); + if (pathInfo == null) { + continue; + } + + if (pathInfo.startsWith(endpoint)) { + httpResp.setStatus(HttpServletResponse.SC_UNAUTHORIZED); + httpResp.flushBuffer(); + httpResp.getWriter().print("This endpoint is disabled via config"); + return; + } + } + + if (adminRequired && !AuthorityServiceFactory.getLocalService().isGlobalAdmin()) { + httpResp.setStatus(HttpServletResponse.SC_UNAUTHORIZED); + httpResp.flushBuffer(); + httpResp.getWriter().print("Admin rights are required for this endpoint"); + return; + } + + /** + * allow authless calls with AUTH_SINGLE_USE_NODEID by appauth + */ + boolean trustedAuth = false; + if (ContextManagementFilter.accessTool != null && ContextManagementFilter.accessTool.get() != null) { + trustedAuth = true; + } + + // ignore the auth for the login + if (validatedAuth == null && (!noAuthenticationNeeded && !trustedAuth)) { + String pathInfo = httpReq.getPathInfo(); + if (pathInfo != null && pathInfo.equals("/openapi.json")) + httpResp.setHeader("WWW-Authenticate", "BASIC realm=\"" + "Edu-Sharing Rest API" + "\""); + httpResp.setStatus(HttpServletResponse.SC_UNAUTHORIZED); + httpResp.flushBuffer(); + return; + } + + // Chain other filters + chain.doFilter(req, resp); + } + + public static Map httpBasicAuth(String authHdr) { + Map validatedAuth = null; + AuthenticationToolAPI authTool = new AuthenticationToolAPI(); + + // Basic authentication details present + + String basicAuth = new String(java.util.Base64.getDecoder().decode(authHdr.substring(6)), StandardCharsets.ISO_8859_1); + + // Split the username and password + + String username = null; + String password = null; + + int pos = basicAuth.indexOf(":"); + if (pos != -1) { + username = basicAuth.substring(0, pos); + password = basicAuth.substring(pos + 1); + } else { + username = basicAuth; + password = ""; + } + + try { + + // Authenticate the user + validatedAuth = authTool.createNewSession(username, password); + } catch (Exception ex) { + Logger.getLogger(ApiAuthenticationFilter.class).error(ex.getMessage(), ex); + } + return validatedAuth; + } + + @Override + public void init(FilterConfig arg0) throws ServletException { + + ApplicationContext eduApplicationContext = + org.edu_sharing.spring.ApplicationContextFactory.getApplicationContext(); + + tokenService = (TokenService) eduApplicationContext.getBean("oauthTokenService"); + } } diff --git a/Backend/services/core/src/main/java/org/edu_sharing/restservices/ConnectorDAO.java b/Backend/services/core/src/main/java/org/edu_sharing/restservices/ConnectorDAO.java index 7babf04de2..9b594263eb 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/restservices/ConnectorDAO.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/restservices/ConnectorDAO.java @@ -47,7 +47,7 @@ public static ConnectorList getConnectorList() throws DAOException{ fileTypes = new ConnectorFileType[]{cftResult}; resultConnector.setFiletypes(fileTypes); }else{ - ArrayList list = new ArrayList(Arrays.asList(fileTypes)); + ArrayList list = new ArrayList<>(Arrays.asList(fileTypes)); list.add(cftResult); resultConnector.setFiletypes(list.toArray(new ConnectorFileType[list.size()])); } @@ -66,7 +66,7 @@ public static ConnectorList getConnectorList() throws DAOException{ if(connectors == null || connectors.length == 0){ result.setConnectors(new Connector[]{resultConnector}); }else{ - ArrayList resultConnectorList = new ArrayList(Arrays.asList(connectors)); + ArrayList resultConnectorList = new ArrayList<>(Arrays.asList(connectors)); resultConnectorList.add(resultConnector); result.setConnectors(resultConnectorList.toArray(new Connector[0])); } diff --git a/Backend/services/core/src/main/java/org/edu_sharing/restservices/GroupDao.java b/Backend/services/core/src/main/java/org/edu_sharing/restservices/GroupDao.java index 2c02c0e085..deeacbeaca 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/restservices/GroupDao.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/restservices/GroupDao.java @@ -40,7 +40,7 @@ public class GroupDao { static Logger logger = Logger.getLogger(GroupDao.class); - private final HashMap properties; + private final Map properties; private final String[] aspects; private final ArrayList parentOrganizations; private String userEmail; @@ -83,7 +83,7 @@ public static List search(RepositoryDao repoDao, String pattern) throw try { - List resultset = new ArrayList(); + List resultset = new ArrayList<>(); for (String groupName : ((MCAlfrescoAPIClient) repoDao.getBaseClient()).searchGroupNames(pattern)) { resultset.add(new GroupDao(repoDao, groupName)); @@ -537,7 +537,7 @@ public void rejectSignup(String user) throws DAOException { } private void notifyGroupSignup(String groupName, NodeRef userRef, String receiver, String messageType) throws Exception { - HashMap replace = new HashMap<>(); + Map replace = new HashMap<>(); replace.put("group", groupName); replace.put("firstName", NodeServiceHelper.getProperty(userRef, CCConstants.CM_PROP_PERSON_FIRSTNAME)); replace.put("lastName", NodeServiceHelper.getProperty(userRef, CCConstants.CM_PROP_PERSON_LASTNAME)); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/restservices/MdsDao.java b/Backend/services/core/src/main/java/org/edu_sharing/restservices/MdsDao.java index e92e15e49f..fcb2ef55e5 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/restservices/MdsDao.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/restservices/MdsDao.java @@ -93,7 +93,7 @@ public Mds asMds() { } private List getWidgets() { - List result = new ArrayList(); + List result = new ArrayList<>(); for (MetadataWidget type : this.mds.getWidgets()) { result.add(new MdsWidget(type)); } @@ -101,7 +101,7 @@ private List getWidgets() { } private List getViews() { - List result = new ArrayList(); + List result = new ArrayList<>(); for (MetadataTemplate type : this.mds.getTemplates()) { result.add(new MdsView(type)); } @@ -109,7 +109,7 @@ private List getViews() { } private List getGroups() { - List result = new ArrayList(); + List result = new ArrayList<>(); for (MetadataGroup type : this.mds.getGroups()) { result.add(new MdsGroup(type)); } diff --git a/Backend/services/core/src/main/java/org/edu_sharing/restservices/NodeDao.java b/Backend/services/core/src/main/java/org/edu_sharing/restservices/NodeDao.java index ba30242b9d..3ab3b56c33 100755 --- a/Backend/services/core/src/main/java/org/edu_sharing/restservices/NodeDao.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/restservices/NodeDao.java @@ -189,7 +189,7 @@ public static NodeDao getNodeWithVersion(RepositoryDao repoDao, String nodeId, S } public NodeDao copyProperties(NodeDao fromDao) throws DAOException { - HashMap props = fromDao.getAllProperties(); + Map props = fromDao.getAllProperties(); props.remove(CCConstants.getValidLocalName(CCConstants.CM_NAME)); return changeProperties(props); } @@ -420,8 +420,8 @@ public static NodeSearch transform(RepositoryDao repoDao, SearchResultNodeRef se NodeSearch result = new NodeSearch(); - List data = new ArrayList(); - List nodes = new ArrayList(); + List data = new ArrayList<>(); + List nodes = new ArrayList<>(); result.setResult(data); result.setNodes(nodes); @@ -491,8 +491,8 @@ public static void delete(String protocol, String store, String nodeId) { private final RepositoryDao repoDao; private final String nodeId; - private HashMap nodeProps; - private HashMap> nodeHistory; + private Map nodeProps; + private Map> nodeHistory; private Map hasPermissions; @@ -601,7 +601,7 @@ public SearchResult runSavedSearch(int skipCount, int maxItems, SearchServ if (!CCConstants.getValidLocalName(CCConstants.CCM_TYPE_SAVED_SEARCH).equals(getType())) { throw new IllegalArgumentException("The given node must be of type " + CCConstants.CCM_TYPE_SAVED_SEARCH); } - HashMap props = getNativeProperties(); + Map props = getNativeProperties(); RepositoryDao repoDao = RepositoryDao .getRepository((String) props.get(CCConstants.CCM_PROP_SAVED_SEARCH_REPOSITORY)); MdsDao mdsDao = MdsDao.getMds(repoDao, (String) props.get(CCConstants.CCM_PROP_SAVED_SEARCH_MDS)); @@ -713,10 +713,10 @@ private NodeDao(RepositoryDao repoDao, org.edu_sharing.service.model.NodeRef nod if (key.matches("ccm:[a-zA-Z]*contributer_[a-zA-Z_-]*")) { String value = (String) this.nodeProps.get(prop); for (String v : ValueTool.getMultivalue(value)) { - ArrayList> vcds = VCardConverter.vcardToHashMap(v); + ArrayList> vcds = VCardConverter.vcardToMap(v); if (vcds.size() > 0) { Contributor contributor = new Contributor(); - HashMap vcd = vcds.get(0); + Map vcd = vcds.get(0); contributor.setFirstname((String) vcd.get(CCConstants.VCARD_GIVENNAME)); contributor.setLastname((String) vcd.get(CCConstants.VCARD_SURNAME)); contributor.setProperty(key); @@ -739,7 +739,7 @@ private NodeDao(RepositoryDao repoDao, org.edu_sharing.service.model.NodeRef nod } if (nodeRef.getAspects() == null) { String[] aspects = nodeService.getAspects(this.storeProtocol, this.storeId, nodeId); - this.aspects = (aspects != null) ? Arrays.asList(aspects) : new ArrayList(); + this.aspects = (aspects != null) ? Arrays.asList(aspects) : new ArrayList<>(); } else { this.aspects = nodeRef.getAspects(); } @@ -755,18 +755,18 @@ private NodeDao(RepositoryDao repoDao, org.edu_sharing.service.model.NodeRef nod } else if (this.aspects.contains(CCConstants.CCM_ASPECT_REMOTEREPOSITORY)) { // just fetch dynamic data which needs to be fetched, because the local io already has metadata String originalNodeId = this.getReferenceOriginalId(); - HashMap> history = AuthenticationUtil.runAsSystem(() -> { + Map> history = AuthenticationUtil.runAsSystem(() -> { try { return this.nodeService.getVersionHistory(originalNodeId); } catch (Throwable t) { throw new RuntimeException(t); } }); - Optional>> entry = history == null ? Optional.empty() : history.entrySet().stream().findFirst(); + Optional>> entry = history == null ? Optional.empty() : history.entrySet().stream().findFirst(); if (!entry.isPresent() || CCConstants.VERSION_COMMENT_REMOTE_OBJECT_INIT.equals(entry.get().getValue().get(CCConstants.CCM_PROP_IO_VERSION_COMMENT))) { try { NodeService nodeServiceRemote = NodeServiceFactory.getNodeService((String) this.nodeProps.get(CCConstants.CCM_PROP_REMOTEOBJECT_REPOSITORYID)); - HashMap nodePropsReplace = nodeServiceRemote.getPropertiesDynamic( + Map nodePropsReplace = nodeServiceRemote.getPropertiesDynamic( null, null, (String) this.nodeProps.get(CCConstants.CCM_PROP_REMOTEOBJECT_NODEID)); nodePropsReplace.remove(CCConstants.SYS_PROP_NODE_UID); nodePropsReplace.remove(CCConstants.CCM_PROP_REMOTEOBJECT_REPOSITORYID); @@ -938,19 +938,19 @@ public static List sortApiNodeRefs(RepositoryDao repoDao, List } public NodeDao createChild(String type, List aspects, - HashMap properties, boolean renameIfExists) throws DAOException { + Map properties, boolean renameIfExists) throws DAOException { return this.createChild(type, aspects, properties, renameIfExists, null); } public NodeDao createChild(String type, List aspects, - HashMap properties, boolean renameIfExists, String childAssoc) throws DAOException { + Map properties, boolean renameIfExists, String childAssoc) throws DAOException { try { NameSpaceTool nameSpaceTool = new NameSpaceTool(); type = nameSpaceTool.transformToLongQName(type); if (childAssoc != null) childAssoc = CCConstants.getValidGlobalName(childAssoc); - HashMap props = transformProperties(properties); + Map props = transformProperties(properties); String childId; String originalNameArr[] = props.get(CCConstants.CM_NAME); @@ -1043,7 +1043,7 @@ public List getChildren() throws DAOException { public List getChildren(String assocName, List filter, SortDefinition sortDefinition) throws DAOException { try { - List result = new ArrayList(); + List result = new ArrayList<>(); if (assocName != null && !assocName.isEmpty()) { @@ -1075,7 +1075,7 @@ public List getChildren(String assocName, List filter, SortDefi public List getAssocs(AssocInfo assoc, List filter, SortDefinition sortDefinition) throws DAOException { try { - List result = new ArrayList(); + List result = new ArrayList<>(); assoc.setAssocName(CCConstants.getValidGlobalName(assoc.getAssocName())); List assocs = nodeService.getNodesByAssoc(getId(), assoc); assocs = ((NodeServiceImpl) NodeServiceFactory.getLocalService()).sortNodeRefList(assocs, filter, sortDefinition); @@ -1102,7 +1102,7 @@ public List getAssocs(AssocInfo assoc, List filter, SortDefinit } } - public NodeDao changeProperties(HashMap properties) + public NodeDao changeProperties(Map properties) throws DAOException { try { @@ -1118,7 +1118,7 @@ public NodeDao changeProperties(HashMap properties) } public NodeDao changePropertiesWithVersioning( - HashMap properties, String comment) throws DAOException { + Map properties, String comment) throws DAOException { // Throws ConcurrencyFailureException if the previous call changes the preview (DESP-851) ApplicationContext applicationContext = AlfAppContextGate.getApplicationContext(); @@ -1152,7 +1152,7 @@ public NodeDao changePreview(InputStream is, String mimetype, boolean version) t try { ImageTool.VerifyResult result = ImageTool.verifyAndPreprocessImage(is, ImageTool.MAX_THUMB_SIZE); - HashMap props = new HashMap<>(); + Map props = new HashMap<>(); if (version) { props.put(CCConstants.CCM_PROP_IO_VERSION_COMMENT, new String[]{CCConstants.VERSION_COMMENT_PREVIEW_CHANGED}); //mergeVersionComment(props, versionComment); @@ -1185,7 +1185,7 @@ public NodeDao changeContent(InputStream is, String mimetype, String versionComment) throws DAOException { try { - HashMap props = new HashMap<>(); + Map props = new HashMap<>(); boolean version = versionComment != null && !versionComment.isEmpty(); // 1. update @@ -1209,7 +1209,7 @@ public NodeDao changeContent(InputStream is, String mimetype, } } - private void mergeVersionComment(HashMap properties, + private void mergeVersionComment(Map properties, String versionComment) { properties.remove(CCConstants.getValidLocalName(CCConstants.CCM_PROP_IO_VERSION_COMMENT)); @@ -1226,8 +1226,8 @@ public void delete(boolean recycle) throws DAOException { } public List getHistory() throws DAOException { - List history = new ArrayList(); - for (Entry> version : getNodeHistory().entrySet()) { + List history = new ArrayList<>(); + for (Entry> version : getNodeHistory().entrySet()) { NodeVersion nodeVersion = convertVersionProps(version.getKey(), version.getValue()); history.add(nodeVersion); } @@ -1263,7 +1263,7 @@ public NodeDao revertHistory(int major, int minor) throws DAOException { String versionLabel = getVersionLabel(major, minor); - HashMap versionProps = getNodeHistory().get(versionLabel); + Map versionProps = getNodeHistory().get(versionLabel); if (versionProps == null) { return null; @@ -1559,17 +1559,17 @@ public NodePermissions getPermissions() throws DAOException { ACL local = new ACL(); local.setInherited(permissions.isInherited()); - local.setPermissions(new ArrayList()); + local.setPermissions(new ArrayList<>()); result.setLocalPermissions(local); - result.setInheritedPermissions(new ArrayList()); + result.setInheritedPermissions(new ArrayList<>()); org.edu_sharing.repository.client.rpc.ACE[] aces = permissions.getAces(); if (aces != null) { - HashMap> authPerm = new HashMap>(); - HashMap> authPermInherited = new HashMap>(); + Map> authPerm = new HashMap<>(); + Map> authPermInherited = new HashMap<>(); for (org.edu_sharing.repository.client.rpc.ACE ace : aces) { if ("acepted".equals(ace.getAccessStatus())) { @@ -1590,7 +1590,7 @@ public NodePermissions getPermissions() throws DAOException { List tmpPerms = authPermInherited.get(authority); if (tmpPerms == null) { - tmpPerms = new ArrayList(); + tmpPerms = new ArrayList<>(); } // do not duplicate existing permissions if (!tmpPerms.contains(ace.getPermission())) @@ -1600,7 +1600,7 @@ public NodePermissions getPermissions() throws DAOException { } else { List tmpPerms = authPerm.get(authority); if (tmpPerms == null) { - tmpPerms = new ArrayList(); + tmpPerms = new ArrayList<>(); } // do not duplicate existing permissions if (!tmpPerms.contains(ace.getPermission())) @@ -1698,8 +1698,8 @@ public void setPermissions(ACL permissions, String mailText, Boolean sendMail, B } } - private HashMap transformProperties( - HashMap properties) { + private Map transformProperties( + Map properties) { return NodeServiceHelper.transformShortToLongProperties(properties); } @@ -1979,13 +1979,12 @@ public String getDownloadUrl() { public NodeVersion getVersion(int major, int minor) throws DAOException { String versionLabel = getVersionLabel(major, minor); - - HashMap versionProps = getNodeHistory().get(versionLabel); + Map versionProps = getNodeHistory().get(versionLabel); return convertVersionProps(versionLabel, versionProps); } - private NodeVersion convertVersionProps(String versionLabel, HashMap versionProps) throws DAOException { + private NodeVersion convertVersionProps(String versionLabel, Map versionProps) throws DAOException { if (versionProps == null) { return null; } @@ -2033,33 +2032,33 @@ private NodeVersionRef transformVersion(String versionLabel) { return version; } - public HashMap getNativeProperties() { + public Map getNativeProperties() { return nodeProps; } - public void setNativeProperties(HashMap nodeProps) { + public void setNativeProperties(Map nodeProps) { this.nodeProps = nodeProps; } - public HashMap getAllProperties() throws DAOException { + public Map getAllProperties() throws DAOException { return getProperties(null, Filter.createShowAllFilter()); } - private HashMap getProperties() throws DAOException { + private Map getProperties() throws DAOException { return getProperties(null); } - private HashMap getProperties(String versionLabel) throws DAOException { + private Map getProperties(String versionLabel) throws DAOException { return getProperties(versionLabel, filter); } - public HashMap getNativeProperties(String versionLabel) throws DAOException { + public Map getNativeProperties(String versionLabel) throws DAOException { return versionLabel != null ? getNodeHistory() .get(versionLabel) : nodeProps; } public void addWorkflowHistory(WorkflowHistory history, boolean sendMail) throws DAOException { - HashMap properties = getNativeProperties(); + Map properties = getNativeProperties(); String nodeType = nodeService.getType(StoreRef.PROTOCOL_WORKSPACE, StoreRef.STORE_REF_WORKSPACE_SPACESSTORE.getIdentifier(), nodeId); List aspects = Arrays.asList(nodeService.getAspects(StoreRef.PROTOCOL_WORKSPACE, StoreRef.STORE_REF_WORKSPACE_SPACESSTORE.getIdentifier(), nodeId)); @@ -2145,21 +2144,21 @@ public List getWorkflowHistory() throws DAOException { } } - private HashMap getProperties(String versionLabel, Filter filter) throws DAOException { - HashMap props = getNativeProperties(versionLabel); + private Map getProperties(String versionLabel, Filter filter) throws DAOException { + Map props = getNativeProperties(versionLabel); return convertProperties(filter, props); } - private HashMap convertProperties(Filter filter, HashMap props) { + private Map convertProperties(Filter filter, Map props) { if (props == null) { return null; } if (filter.getProperties().size() == 0) { - return new HashMap(); + return new HashMap<>(); } - HashMap properties = new HashMap(); + Map properties = new HashMap<>(); if (LightbendConfigCache.getBoolean("repository.privacy.filterVCardEmail")) { List cleanup = new ArrayList<>(); for (Entry entry : props.entrySet()) { @@ -2203,7 +2202,7 @@ private HashMap convertProperties(Filter filter, HashMap getPropertyValues(Object value) { - List values = new ArrayList(); + List values = new ArrayList<>(); if (value != null) { if (value instanceof Date) { values.add(String.valueOf(((Date) value).getTime())); @@ -2261,17 +2260,17 @@ private String getPreviewImage() { return new MimeTypesV2(repoDao.getApplicationInfo()).getPreview(type, nodeProps, aspects); } - public HashMap> getNodeHistory() throws DAOException { + public Map> getNodeHistory() throws DAOException { try { if (nodeHistory == null) { this.nodeHistory = new HashMap<>(); - HashMap> versionHistory = nodeService + Map> versionHistory = nodeService .getVersionHistory(nodeId); if (versionHistory != null) { - for (HashMap version : versionHistory.values()) { + for (Map version : versionHistory.values()) { nodeHistory.put((String) version .get(CCConstants.CM_PROP_VERSIONABLELABEL), version); } @@ -2484,7 +2483,7 @@ public static List convertAlfrescoNodeRef(RepositoryDao repoDao, List properties = nodeService.getProperties(StoreRef.PROTOCOL_WORKSPACE, StoreRef.STORE_REF_WORKSPACE_SPACESSTORE.getIdentifier(), nodeId); + Map properties = nodeService.getProperties(StoreRef.PROTOCOL_WORKSPACE, StoreRef.STORE_REF_WORKSPACE_SPACESSTORE.getIdentifier(), nodeId); List aspects = Arrays.asList(nodeService.getAspects(StoreRef.PROTOCOL_WORKSPACE, StoreRef.STORE_REF_WORKSPACE_SPACESSTORE.getIdentifier(), nodeId)); NotificationServiceFactoryUtility.getLocalService() .notifyNodeIssue(nodeId, reason, type, aspects, properties, userEmail, userComment); @@ -2504,7 +2503,7 @@ public static NodeDao saveSearch(String repoId, String mdsId, String query, Stri try { String parent = RepositoryDao.getHomeRepository().getUserSavedSearch(true); NodeDao parentDao = new NodeDao(RepositoryDao.getHomeRepository(), parent); - HashMap props = new HashMap(); + Map props = new HashMap<>(); props.put(CCConstants.CM_NAME, new String[]{NodeServiceHelper.cleanupCmName(name)}); props.put(CCConstants.LOM_PROP_GENERAL_TITLE, new String[]{name}); props.put(CCConstants.CCM_PROP_SAVED_SEARCH_REPOSITORY, new String[]{repoId}); @@ -2567,7 +2566,7 @@ public NodeDao getTemplateNode() throws DAOException { } } - public NodeDao changeTemplateProperties(Boolean enable, HashMap properties) throws DAOException { + public NodeDao changeTemplateProperties(Boolean enable, Map properties) throws DAOException { try { nodeService.setTemplateStatus(nodeId, enable); if (enable) { @@ -2680,11 +2679,11 @@ public static SearchResult getFrontpageNodes(RepositoryDao repoDao) thr * If the NodeDao is a child, then all properties including inherited are returned * otherwise, the own properties are returned */ - public HashMap getInheritedPropertiesFromParent() throws Throwable { + public Map getInheritedPropertiesFromParent() throws Throwable { if (getAspectsNative().contains(CCConstants.CCM_ASPECT_IO_CHILDOBJECT)) { Map propsChild = getNativeProperties(); String parentRef = NodeServiceFactory.getLocalService().getPrimaryParent(getRef().getId()); - HashMap propsParent = + Map propsParent = NodeServiceHelper.getProperties(new org.alfresco.service.cmr.repository.NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, parentRef)); // ignore some technical properties, like mimetypes etc. (configured via lightbend) for (String prop : LightbendConfigLoader.get().getStringList("repository.childobjects.ignoredInheritMetadata")) { diff --git a/Backend/services/core/src/main/java/org/edu_sharing/restservices/PersonDao.java b/Backend/services/core/src/main/java/org/edu_sharing/restservices/PersonDao.java index 65e6e66ccd..1e23b17cfd 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/restservices/PersonDao.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/restservices/PersonDao.java @@ -110,7 +110,7 @@ public static PersonDao createPerson(RepositoryDao repoDao, String userName,Stri } catch (NoSuchPersonException e) { - HashMap userInfo = profileToMap(profile); + Map userInfo = profileToMap(profile); userInfo.put(CCConstants.PROP_USERNAME, userName); AuthorityServiceFactory.getAuthorityService(repoDao.getId()).createOrUpdateUser(userInfo); @@ -184,7 +184,7 @@ private void initGroupFolders() { String groupFolderId = ((MCAlfrescoAPIClient)baseClient).getGroupFolderId(getUserName()); if (groupFolderId != null) { - HashMap> children = baseClient.getChildren(groupFolderId); + Map> children = baseClient.getChildren(groupFolderId); for (Object key : children.keySet()) { @@ -201,7 +201,7 @@ public void changeProfile(UserProfileEdit profile) throws DAOException { try { - HashMap newUserInfo = profileToMap(profile); + Map newUserInfo = profileToMap(profile); newUserInfo.put(CCConstants.PROP_USERNAME, getUserName()); authorityService.createOrUpdateUser(newUserInfo); } catch (Throwable t) { @@ -211,8 +211,8 @@ public void changeProfile(UserProfileEdit profile) throws DAOException { } - private static HashMap profileToMap(UserProfileEdit profile) { - HashMap newUserInfo = new HashMap<>(); + private static Map profileToMap(UserProfileEdit profile) { + Map newUserInfo = new HashMap<>(); newUserInfo.put(CCConstants.PROP_USER_FIRSTNAME, profile.getFirstName()); newUserInfo.put(CCConstants.PROP_USER_LASTNAME, profile.getLastName()); newUserInfo.put(CCConstants.PROP_USER_EMAIL, profile.getEmail()); @@ -320,7 +320,7 @@ public User asPerson() throws DAOException { initGroupFolders(); - List sharedFolderRefs = new ArrayList(); + List sharedFolderRefs = new ArrayList<>(); for (String sharedFolderId : sharedFolderIds) { NodeRef sharedFolderRef = new NodeRef(); @@ -592,7 +592,7 @@ public String getPreferences() { public void setPreferences(String preferences) throws Exception{ // validate json new JSONObject(preferences); - HashMap newUserInfo = new HashMap(); + Map newUserInfo = new HashMap<>(); newUserInfo.put(CCConstants.PROP_USERNAME, getUserName()); newUserInfo.put(CCConstants.CCM_PROP_PERSON_PREFERENCES, preferences); ((MCAlfrescoAPIClient)this.baseClient).updateUser(newUserInfo); @@ -617,7 +617,7 @@ public ProfileSettings getProfileSettings() { * @param profileSettings (Object) */ public void setProfileSettings(ProfileSettings profileSettings) throws Exception{ - HashMap newUserInfo = new HashMap<>(); + Map newUserInfo = new HashMap<>(); newUserInfo.put(CCConstants.PROP_USERNAME, getUserName()); newUserInfo.put(CCConstants.CCM_PROP_PERSON_SHOW_EMAIL, profileSettings.getShowEmail()); ((MCAlfrescoAPIClient)this.baseClient).updateUser(newUserInfo); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/restservices/RepositoryDao.java b/Backend/services/core/src/main/java/org/edu_sharing/restservices/RepositoryDao.java index f4336c6349..798effc073 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/restservices/RepositoryDao.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/restservices/RepositoryDao.java @@ -89,7 +89,7 @@ public static List getRepositories() throws DAOException { try { - List result = new ArrayList(); + List result = new ArrayList<>(); for (ApplicationInfo appInfo : ApplicationInfoList.getRepositoryInfosOrdered()) { ToolPermissionService tp = ToolPermissionServiceFactory.getInstance(); if (ApplicationInfo.TYPE_REPOSITORY.equals(appInfo.getType()) && appInfo.getSearchable()) { diff --git a/Backend/services/core/src/main/java/org/edu_sharing/restservices/StatisticDao.java b/Backend/services/core/src/main/java/org/edu_sharing/restservices/StatisticDao.java index 9a47729d5f..a0a634f3bd 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/restservices/StatisticDao.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/restservices/StatisticDao.java @@ -207,7 +207,7 @@ public Statistics get(String context, List properties, Filter filter) th for (org.edu_sharing.service.statistic.StatisticEntry entry : statisticsBackend.getEntries()) { StatisticEntry statEntry = new StatisticEntry(); statEntry.setProperty(entry.getProperty()); - List entities = new ArrayList(); + List entities = new ArrayList<>(); for (Map.Entry statEntity : entry.getStatistic().entrySet()) { StatisticEntity entity = new StatisticEntity(); entity.setValue(statEntity.getKey()); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/restservices/ToolDao.java b/Backend/services/core/src/main/java/org/edu_sharing/restservices/ToolDao.java index bb9472bcb7..af7bea0ee8 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/restservices/ToolDao.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/restservices/ToolDao.java @@ -45,7 +45,7 @@ public String doWork() throws Exception { try { NodeService nodeService = NodeServiceFactory.getNodeService(repoDao.getApplicationInfo().getAppId()); String nodeId = nodeService.createNode(companyHomeId, CCConstants.CCM_TYPE_MAP, nodeService.getNameProperty( CCConstants.TOOL_HOMEFOLDER)); - PermissionServiceFactory.getPermissionService(null).setPermissions(nodeId, new ArrayList(), false, null,null, false); + PermissionServiceFactory.getPermissionService(null).setPermissions(nodeId, new ArrayList<>(), false, null,null, false); return nodeId; }catch(Throwable e) { throw new Exception(e); @@ -88,7 +88,7 @@ public NodeDao create(String repository, String node, Boolean renameIfExists, St NodeDao nodeDao = NodeDao.getNode(repoDao, node); new NodeApi().resolveURLTitle(properties); - List aspects = new ArrayList(); + List aspects = new ArrayList<>(); if (aspect != null && !aspect.trim().equals("")) { aspects.add(aspect); } @@ -118,7 +118,7 @@ public List getInstances(String repository, String toolDefinition) throws } List childRefs = nodeDao.getChildren(); - List result = new ArrayList(); + List result = new ArrayList<>(); for (NodeRef nodeRef : childRefs) { Node node = NodeDao.getNode(repoDao, nodeRef.getId()).asNode(); if (node.getType().equals(NameSpaceTool.transformToShortQName(CCConstants.CCM_TYPE_TOOL_INSTANCE))) { @@ -138,7 +138,7 @@ public List getAllToolDefinitions(String repositoryId) throws DAOException String toolFolderId = getToolFolder(repositoryId); List children = nodeService.getChildrenChildAssociationRef(toolFolderId); - List result = new ArrayList(); + List result = new ArrayList<>(); for(ChildAssociationRef child : children) { String[] aspects = nodeService.getAspects(child.getChildRef().getStoreRef().getProtocol(), child.getChildRef().getStoreRef().getIdentifier(), child.getChildRef().getId()); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/restservices/UsageDao.java b/Backend/services/core/src/main/java/org/edu_sharing/restservices/UsageDao.java index 8fa437f10c..8033e93306 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/restservices/UsageDao.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/restservices/UsageDao.java @@ -44,7 +44,7 @@ public UsageDao(RepositoryDao repoDao) { public List getUsages(String appId) throws DAOException { try { - List result = new ArrayList(); + List result = new ArrayList<>(); for (org.edu_sharing.service.usage.Usage usage : new Usage2Service().getUsages(appId)) { Usage usageResult = convertUsage(usage, Usage.class); @@ -114,7 +114,7 @@ public boolean handleEvent(ValidationEvent event) { public List getUsagesByCourse(String appId, String courseId) throws DAOException { try { - List result = new ArrayList(); + List result = new ArrayList<>(); for (org.edu_sharing.service.usage.Usage usage : new Usage2Service().getUsagesByCourse(appId, courseId)) { Usage usageResult = convertUsage(usage, Usage.class); result.add(usageResult); @@ -178,7 +178,7 @@ public void deleteUsage(String nodeId, String usageId) throws DAOException { public List getUsagesByNode(String nodeId) throws DAOException { try { - List result = new ArrayList(); + List result = new ArrayList<>(); for (org.edu_sharing.service.usage.Usage usage : new Usage2Service().getUsageByParentNodeId(null, null, nodeId)) { Usage usageResult = convertUsage(usage, Usage.class); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/restservices/about/v1/AboutApi.java b/Backend/services/core/src/main/java/org/edu_sharing/restservices/about/v1/AboutApi.java index 7368d6cca1..af1da433cb 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/restservices/about/v1/AboutApi.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/restservices/about/v1/AboutApi.java @@ -68,7 +68,7 @@ public Response about() { about.setThemesUrl(new MimeTypesV2(ApplicationInfoList.getHomeRepository()).getThemePath()); - Map services = new HashMap(); + Map services = new HashMap<>(); for (Class clazz : ApiApplication.SERVICES) { ApiService rest = clazz.getAnnotation(ApiService.class); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/restservices/about/v1/model/About.java b/Backend/services/core/src/main/java/org/edu_sharing/restservices/about/v1/model/About.java index b14a8a98e6..3fd544b472 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/restservices/about/v1/model/About.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/restservices/about/v1/model/About.java @@ -13,7 +13,7 @@ public class About { private ServiceVersion version = null; - private List services = new ArrayList(); + private List services = new ArrayList<>(); private List plugins = new ArrayList<>(); private String themesUrl; private long lastCacheUpdate; diff --git a/Backend/services/core/src/main/java/org/edu_sharing/restservices/about/v1/model/AboutService.java b/Backend/services/core/src/main/java/org/edu_sharing/restservices/about/v1/model/AboutService.java index 3087d8a335..99edbaba6a 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/restservices/about/v1/model/AboutService.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/restservices/about/v1/model/AboutService.java @@ -13,7 +13,7 @@ public class AboutService { private String name = null; - private List instances = new ArrayList(); + private List instances = new ArrayList<>(); /** diff --git a/Backend/services/core/src/main/java/org/edu_sharing/restservices/admin/v1/AdminApi.java b/Backend/services/core/src/main/java/org/edu_sharing/restservices/admin/v1/AdminApi.java index 043cf47dd0..4a6444c009 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/restservices/admin/v1/AdminApi.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/restservices/admin/v1/AdminApi.java @@ -240,7 +240,7 @@ public Response options() { @ApiResponse(responseCode="500", description=RestConstants.HTTP_500, content = @Content(schema = @Schema(implementation = ErrorResponse.class))) }) public Response getApplications(@Context HttpServletRequest req) { try { - List result = new ArrayList(); + List result = new ArrayList<>(); for (ApplicationInfo appInfo : ApplicationInfoList.getRepositoryInfosOrdered()) { if (appInfo.ishomeNode()) continue; @@ -345,7 +345,7 @@ public Response getStatistics(@Context HttpServletRequest req) { AdminStatistics statistics = new AdminStatistics(); AdminService service = AdminServiceFactory.getInstance(); statistics.setActiveSessions(service.getActiveSessions()); - List locks = new ArrayList(); + List locks = new ArrayList<>(); for (NodeRef lock : service.getActiveNodeLocks()) { locks.add(NodeDao.getNode(RepositoryDao.getRepository(RepositoryDao.HOME), lock.getId()).asNode()); } @@ -377,7 +377,7 @@ public Response getApplicationXML(@Context HttpServletRequest req, @Parameter(description = "Properties Filename (*.xml)", required = true) @PathParam("xml") String xml) { try { Set> set = AdminServiceFactory.getInstance().getPropertiesXML(xml).entrySet(); - Map map = new HashMap(); + Map map = new HashMap<>(); String[] filter = XML_FILTER.get(xml); for (Entry entry : set) { if (filter != null && Arrays.asList(filter).contains(entry.getKey())) @@ -451,7 +451,7 @@ public Response addApplication( @Parameter(description = "XML file for app to register", required = true) @FormDataParam("xml") InputStream is, @Context HttpServletRequest req) { try { - HashMap result = AdminServiceFactory.getInstance().addApplicationFromStream(is); + Map result = AdminServiceFactory.getInstance().addApplicationFromStream(is); return Response.ok().entity(result).build(); } catch (Throwable t) { return ErrorResponse.createResponse(t); @@ -473,7 +473,7 @@ public Response addApplication( @Parameter(description = "Remote application metadata url", required = true) @QueryParam("url") String url, @Context HttpServletRequest req) { try { - HashMap result = AdminServiceFactory.getInstance().addApplication(url); + Map result = AdminServiceFactory.getInstance().addApplication(url); return Response.ok().entity(result).build(); } catch (Throwable t) { return ErrorResponse.createResponse(t); @@ -1137,10 +1137,10 @@ public Response options13() { public Response startJob( @Parameter(description = "jobClass", required = true) @PathParam("jobClass") String jobClass, - @Parameter(description = "params", required = true) HashMap params, + @Parameter(description = "params", required = true) Map params, @Context HttpServletRequest req) { try { - AdminServiceFactory.getInstance().startJob(jobClass, new HashMap(params)); + AdminServiceFactory.getInstance().startJob(jobClass, new HashMap<>(params)); return Response.ok().build(); } catch (NotAnAdminException e) { return ErrorResponse.createResponse(e); @@ -1162,7 +1162,7 @@ public Response startJob( public Response startJobSync( @Parameter(description = "jobClass", required = true) @PathParam("jobClass") String jobClass, - @Parameter(description = "params", required = true) HashMap params, + @Parameter(description = "params", required = true) Map params, @Context HttpServletRequest req) { try { Object result = AdminServiceFactory.getInstance().startJobSync(jobClass, new HashMap<>(params)); @@ -1208,7 +1208,7 @@ public Response searchByElasticDSL( SearchServiceElastic elastic = new SearchServiceElastic(ApplicationInfoList.getHomeRepository().getAppId()); SearchResultNodeRefElastic search = elastic.searchDSL(dsl); RepositoryDao repoDao = RepositoryDao.getHomeRepository(); - List data = new ArrayList(); + List data = new ArrayList<>(); for (org.edu_sharing.service.model.NodeRef ref : search.getData()) { try { data.add(NodeDao.getNode(repoDao, ref).asNode()); @@ -1281,7 +1281,7 @@ public Response searchByLucene( token.setAuthorityScope(authorityScope); NodeSearch search = NodeDao.search(repoDao, token, false); - List data = new ArrayList(); + List data = new ArrayList<>(); for (org.edu_sharing.restservices.shared.NodeRef ref : search.getResult()) { data.add(NodeDao.getNode(repoDao, storeRef.getProtocol(), storeRef.getIdentifier(), ref.getId(), filter).asNode()); } diff --git a/Backend/services/core/src/main/java/org/edu_sharing/restservices/archive/v1/ArchiveApi.java b/Backend/services/core/src/main/java/org/edu_sharing/restservices/archive/v1/ArchiveApi.java index 5ede84f9ef..3e1cf84855 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/restservices/archive/v1/ArchiveApi.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/restservices/archive/v1/ArchiveApi.java @@ -127,7 +127,7 @@ private Response search(String repository, ArchiveDao.search(repoDao, pattern, skipCount, maxItems, sortProperties, sortAscending) : ArchiveDao.search(repoDao, pattern,user, skipCount, maxItems, sortProperties, sortAscending); - List data = new ArrayList(); + List data = new ArrayList<>(); for (NodeRef ref : search.getResult()) { if(ref.isArchived()){ diff --git a/Backend/services/core/src/main/java/org/edu_sharing/restservices/collection/v1/model/ReferenceEntries.java b/Backend/services/core/src/main/java/org/edu_sharing/restservices/collection/v1/model/ReferenceEntries.java index a374cfaf8b..8f99830fbe 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/restservices/collection/v1/model/ReferenceEntries.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/restservices/collection/v1/model/ReferenceEntries.java @@ -8,7 +8,7 @@ import java.util.List; public class ReferenceEntries { - private List references = new ArrayList(); + private List references = new ArrayList<>(); private Pagination pagination; diff --git a/Backend/services/core/src/main/java/org/edu_sharing/restservices/config/v1/ConfigApi.java b/Backend/services/core/src/main/java/org/edu_sharing/restservices/config/v1/ConfigApi.java index b8552abc7f..aec6e00c31 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/restservices/config/v1/ConfigApi.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/restservices/config/v1/ConfigApi.java @@ -190,7 +190,7 @@ private Map convertVariables(org.edu_sharing.alfresco.service.co private Map convertKeyValue(List pairs) { if(pairs==null) return null; - Map map=new HashMap(); + Map map=new HashMap<>(); for(org.edu_sharing.alfresco.service.config.model.KeyValuePair pair : pairs) { map.put(pair.key, pair.value); } diff --git a/Backend/services/core/src/main/java/org/edu_sharing/restservices/iam/v1/IamApi.java b/Backend/services/core/src/main/java/org/edu_sharing/restservices/iam/v1/IamApi.java index 9d0f2fc204..f28c88c92e 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/restservices/iam/v1/IamApi.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/restservices/iam/v1/IamApi.java @@ -92,7 +92,7 @@ public Response searchUser( filter ); - List result = new ArrayList(); + List result = new ArrayList<>(); for (String user: search.getData()) { result.add(new PersonDao(repoDao,user).asPersonSimple(true)); } @@ -760,7 +760,7 @@ public Response searchGroups( @Context HttpServletRequest req) { try { - HashMap props = new HashMap(); + Map props = new HashMap<>(); if(groupType!=null && !groupType.isEmpty()){ props.put(CCConstants.getValidLocalName(CCConstants.CCM_PROP_GROUPEXTENSION_GROUPTYPE), groupType); } @@ -778,7 +778,7 @@ public Response searchGroups( props ); - List result = new ArrayList(); + List result = new ArrayList<>(); for (String group: search.getData()) { try { result.add(new GroupDao(repoDao, group).asGroup()); @@ -1246,7 +1246,7 @@ public Response getMembership( new SortDefinition(sortProperties,sortAscending) ); AuthorityEntries response = new AuthorityEntries(); - List result = new ArrayList(); + List result = new ArrayList<>(); for (String member: search.getData()) { result.add( member.startsWith(PermissionService.GROUP_PREFIX) ? @@ -1409,7 +1409,7 @@ public Response searchAuthorities( @Context HttpServletRequest req) { try { - HashMap props = new HashMap<>(); + Map props = new HashMap<>(); if(groupType!=null && !groupType.isEmpty()){ props.put(CCConstants.getValidLocalName(CCConstants.CCM_PROP_GROUPEXTENSION_GROUPTYPE), groupType); } @@ -1428,7 +1428,7 @@ public Response searchAuthorities( ); - List result = new ArrayList(); + List result = new ArrayList<>(); for (String user: search.getData()) { result.add(getUserOrGroup(repoDao, user)); } @@ -1467,7 +1467,7 @@ public Response getRecentlyInvited( try { RepositoryDao repoDao = RepositoryDao.getRepository(repository); List recent = PermissionServiceFactory.getPermissionService(repoDao.getId()).getRecentlyInvited(); - List result = new ArrayList(); + List result = new ArrayList<>(); for (String user: recent) { result.add(getUserOrGroup(repoDao, user)); } diff --git a/Backend/services/core/src/main/java/org/edu_sharing/restservices/login/v1/LoginApi.java b/Backend/services/core/src/main/java/org/edu_sharing/restservices/login/v1/LoginApi.java index b0846e248d..5eb2b248ab 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/restservices/login/v1/LoginApi.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/restservices/login/v1/LoginApi.java @@ -108,7 +108,7 @@ public Response loginToScope(@Parameter(description = "credentials, example: tes AuthenticationToolAPI authTool = new AuthenticationToolAPI(); ScopeAuthenticationService service = ScopeAuthenticationServiceFactory.getScopeAuthenticationService(); - HashMap auth = authTool.validateAuthentication(req.getSession()); + Map auth = authTool.validateAuthentication(req.getSession()); if(auth == null){ return Response.ok(new Login(false,null, null,req.getSession(),Login.STATUS_CODE_PREVIOUS_SESSION_REQUIRED)).build(); } @@ -239,7 +239,7 @@ public Response authenticate(@Parameter(description = "User Id", required=true ) return Response.status(Response.Status.PRECONDITION_FAILED).entity(msg).build(); } - HashMap ssoDataMap = new HashMap<>(); + Map ssoDataMap = new HashMap<>(); ssoDataMap.put(ssoMapper.getSSOUsernameProp(), userId); //add authByAppData diff --git a/Backend/services/core/src/main/java/org/edu_sharing/restservices/lti/v13/LTIApi.java b/Backend/services/core/src/main/java/org/edu_sharing/restservices/lti/v13/LTIApi.java index 2e6fa5a961..93abb7b998 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/restservices/lti/v13/LTIApi.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/restservices/lti/v13/LTIApi.java @@ -763,7 +763,7 @@ public Response getDetailsSnippet( try{ Jws claims = new LTIJWTUtil().validateForInitialToolSession(jwt); String token = claims.getBody().get(LTIPlatformConstants.CUSTOM_CLAIM_TOKEN, String.class); - HashMap tokenData = new Gson().fromJson(ApiTool.decrpt(token), HashMap.class); + Map tokenData = (Map)new Gson().fromJson(ApiTool.decrpt(token), Map.class); String user = tokenData.get(LTIPlatformConstants.CUSTOM_CLAIM_USER); //context is the embedding node String contextId = tokenData.get(LTIPlatformConstants.CUSTOM_CLAIM_NODEID); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/restservices/ltiplatform/v13/LTIPlatformApi.java b/Backend/services/core/src/main/java/org/edu_sharing/restservices/ltiplatform/v13/LTIPlatformApi.java index e8d8f55fad..a49df539be 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/restservices/ltiplatform/v13/LTIPlatformApi.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/restservices/ltiplatform/v13/LTIPlatformApi.java @@ -289,7 +289,7 @@ public Response auth( * @TODO build id_token and send it to redirect_uri */ - HashMap formParams = new HashMap<>(); + Map formParams = new HashMap<>(); formParams.put("id_token", jwt); formParams.put("state", state); return Response.ok(ApiTool.getHTML(redirect_uri, formParams)).build(); @@ -900,7 +900,7 @@ public Response deepLinkingResponse( List nodeIds = new ArrayList<>(); List titles = new ArrayList<>(); for (Map contentItem : contentItems) { - HashMap properties = new HashMap<>(); + Map properties = new HashMap<>(); String type = (String) contentItem.get("type"); if (!LTIConstants.DEEP_LINK_LTIRESOURCELINK.equals(type)) { throw new Exception("unsupported lti type:" + type); @@ -1247,7 +1247,7 @@ public Response getContent( }) public Response testToken( - @Parameter(description = "properties", required = true) HashMap properties, + @Parameter(description = "properties", required = true) Map properties, @Context HttpServletRequest req) { diff --git a/Backend/services/core/src/main/java/org/edu_sharing/restservices/mds/v1/model/MdsWidget.java b/Backend/services/core/src/main/java/org/edu_sharing/restservices/mds/v1/model/MdsWidget.java index 53a61f2cda..2e473d96f0 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/restservices/mds/v1/model/MdsWidget.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/restservices/mds/v1/model/MdsWidget.java @@ -155,14 +155,14 @@ public MdsWidget(MetadataWidget widget) { if(widget.getValues()!=null){ this.hasValues = true; if(widget.isValuespaceClient()) { - values = new ArrayList(); + values = new ArrayList<>(); for (MetadataKey key : widget.getValues()) { values.add(new MdsValue(key)); } } } if(widget.getSubwidgets()!=null){ - mdsSubwidgets =new ArrayList(); + mdsSubwidgets =new ArrayList<>(); for(MetadataWidget.Subwidget key : widget.getSubwidgets()){ mdsSubwidgets.add(new MdsSubwidget(key)); } diff --git a/Backend/services/core/src/main/java/org/edu_sharing/restservices/network/v1/NetworkApi.java b/Backend/services/core/src/main/java/org/edu_sharing/restservices/network/v1/NetworkApi.java index c351b3dbeb..cb652692e4 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/restservices/network/v1/NetworkApi.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/restservices/network/v1/NetworkApi.java @@ -54,7 +54,7 @@ public Response getRepositories( try { - List repos = new ArrayList(); + List repos = new ArrayList<>(); for (RepositoryDao repository : RepositoryDao.getRepositories()) { repos.add(repository.asRepo()); } diff --git a/Backend/services/core/src/main/java/org/edu_sharing/restservices/node/v1/NodeApi.java b/Backend/services/core/src/main/java/org/edu_sharing/restservices/node/v1/NodeApi.java index 959287741f..53d9d7b4a4 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/restservices/node/v1/NodeApi.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/restservices/node/v1/NodeApi.java @@ -1159,7 +1159,7 @@ public static NodeEntries createResponseFromNodeList(List sorted, Integer int min = (skipCount != null) ? Math.min(sorted.size(), skipCount) : 0; int max = (maxItems != null) ? Math.min(sorted.size(), min + maxItems) : sorted.size(); - List data = new ArrayList(); + List data = new ArrayList<>(); for (Node child : sorted.subList(min, max)) { data.add(child); } @@ -1887,7 +1887,7 @@ public Response getNodes( searchToken.setFacets(facets); searchToken.setSortDefinition(new SortDefinition(sortProperties, sortAscending)); NodeSearch search = NodeDao.search(repoDao,searchToken); - List data = new ArrayList(); + List data = new ArrayList<>(); for (NodeRef ref : search.getResult()) { data.add(NodeDao.getNode(repoDao, ref.getId(),filter).asNode()); } diff --git a/Backend/services/core/src/main/java/org/edu_sharing/restservices/node/v1/model/SearchResult.java b/Backend/services/core/src/main/java/org/edu_sharing/restservices/node/v1/model/SearchResult.java index 3de56fef8d..8a52c5a3ce 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/restservices/node/v1/model/SearchResult.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/restservices/node/v1/model/SearchResult.java @@ -13,7 +13,7 @@ public class SearchResult { - private List nodes = new ArrayList(); + private List nodes = new ArrayList<>(); private Pagination pagination = null; private List facets = null; diff --git a/Backend/services/core/src/main/java/org/edu_sharing/restservices/organization/v1/OrganizationApi.java b/Backend/services/core/src/main/java/org/edu_sharing/restservices/organization/v1/OrganizationApi.java index e9b14750cf..4f7746019c 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/restservices/organization/v1/OrganizationApi.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/restservices/organization/v1/OrganizationApi.java @@ -74,7 +74,7 @@ public Response getOrganizations( OrganizationEntries response = new OrganizationEntries(); response.setCanCreate(AuthorityServiceFactory.getAuthorityService(repoDao.getId()).isGlobalAdmin()); - List data = new ArrayList(); + List data = new ArrayList<>(); SearchResult result=SearchServiceFactory.getSearchService(repoDao.getId()).searchOrganizations( pattern, skipCount!=null ? skipCount : 0, diff --git a/Backend/services/core/src/main/java/org/edu_sharing/restservices/search/v1/SearchApi.java b/Backend/services/core/src/main/java/org/edu_sharing/restservices/search/v1/SearchApi.java index ecb7b8e73f..289b0178ea 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/restservices/search/v1/SearchApi.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/restservices/search/v1/SearchApi.java @@ -102,7 +102,7 @@ public Response search( token.setExcludes(parameters.getExcludes()); NodeSearch search = NodeDao.search(repoDao, mdsDao, query, parameters.getCriteria(), token, filter, parametersToDaoTransformer(parameters)); - List data = null;//new ArrayList(); + List data = null;//new ArrayList<>(); if(search.getNodes().isEmpty()){ //searched repo deliveres only nodeRefs by query time data = NodeDao.convertToRest(repoDao, search.getResult(), filter, parametersToDaoTransformer(parameters)); @@ -195,7 +195,7 @@ public Response searchLrmi( token.setExcludes(parameters.getExcludes()); NodeSearch search = NodeDao.search(repoDao, mdsDao, query, parameters.getCriteria(), token, filter, parametersToDaoTransformer(parameters)); - List nodes = null;//new ArrayList(); + List nodes = null;//new ArrayList<>(); if(search.getNodes().size() == 0){ //searched repo deliveres only nodeRefs by query time nodes = NodeDao.convertToRest(repoDao, search.getResult(), filter, null); @@ -401,7 +401,7 @@ public Response searchFingerprint( NodeSearch nodeSearch = NodeDao.searchFingerprint(repoDao, nodeId, filter); SearchResultNode response = new SearchResultNode(); - List data = new ArrayList(); + List data = new ArrayList<>(); for (org.edu_sharing.restservices.shared.NodeRef ref : nodeSearch.getResult()) { data.add(NodeDao.getNode(repoDao, ref.getId(), filter).asNode()); } @@ -499,7 +499,7 @@ public Response searchByProperty( token.setLuceneString(query); NodeSearch search = NodeDao.search(repoDao, token); - List data = new ArrayList(); + List data = new ArrayList<>(); for (NodeRef ref : search.getResult()) { data.add(NodeDao.getNode(repoDao, ref.getId(),filter).asNode()); } @@ -626,7 +626,7 @@ public Response getMetdata( Filter filter = new Filter(propertyFilter); NodeSearch search = NodeDao.getMetadata(repoDao, nodeIds, filter); - List data = null;//new ArrayList(); + List data = null;//new ArrayList<>(); if(search.getNodes().size() < search.getResult().size()){ //searched repo deliveres only nodeRefs by query time data = NodeDao.convertToRest(repoDao, search.getResult(), null, null); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/restservices/shared/Filter.java b/Backend/services/core/src/main/java/org/edu_sharing/restservices/shared/Filter.java index fda65be367..54ba4a8e36 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/restservices/shared/Filter.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/restservices/shared/Filter.java @@ -7,13 +7,13 @@ public class Filter { public static final String ALL="-all-"; - List properties = new ArrayList(); + List properties = new ArrayList<>(); public Filter() { } public static Filter createShowAllFilter(){ - List list=new ArrayList(); + List list=new ArrayList<>(); list.add(ALL); return new Filter(list); } diff --git a/Backend/services/core/src/main/java/org/edu_sharing/restservices/shared/Node.java b/Backend/services/core/src/main/java/org/edu_sharing/restservices/shared/Node.java index 2b9ea98ddf..153b1fd128 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/restservices/shared/Node.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/restservices/shared/Node.java @@ -19,7 +19,7 @@ public class Node implements Serializable { private NodeLTIDeepLink nodeLTIDeepLink = null; private Remote remote = null; private String type = null; - private List aspects = new ArrayList(); + private List aspects = new ArrayList<>(); private String name = null; private String title = null; private String metadataset = null; @@ -30,7 +30,7 @@ public class Node implements Serializable { private Person modifiedBy = null; private List access = null; private String downloadUrl = null; - private HashMap properties = null; + private Map properties = null; private String mimetype = null; private String mediatype = null; private String size = null; @@ -243,11 +243,11 @@ public void setAccess(List access) { **/ @Schema(description = "") @JsonProperty("properties") - public HashMap getProperties() { + public Map getProperties() { return properties; } - public void setProperties(HashMap properties) { + public void setProperties(Map properties) { this.properties = properties; } diff --git a/Backend/services/core/src/main/java/org/edu_sharing/restservices/shared/NodeVersion.java b/Backend/services/core/src/main/java/org/edu_sharing/restservices/shared/NodeVersion.java index af79407198..fcc23649fa 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/restservices/shared/NodeVersion.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/restservices/shared/NodeVersion.java @@ -3,6 +3,7 @@ import java.util.Date; import java.util.HashMap; import java.util.List; +import java.util.Map; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonProperty; @@ -19,7 +20,7 @@ public class NodeVersion { private String modifiedAt = null; private Person modifiedBy = null; private String contentUrl = null; - private HashMap properties = null; + private Map properties = null; /** @@ -85,10 +86,10 @@ public void setContentUrl(String contentUrl) { **/ @Schema(description = "") @JsonProperty(value = "properties") - public HashMap getMetadata() { + public Map getMetadata() { return properties; } - public void setProperties(HashMap metadata) { + public void setProperties(Map metadata) { this.properties = metadata; } diff --git a/Backend/services/core/src/main/java/org/edu_sharing/restservices/shared/Preview.java b/Backend/services/core/src/main/java/org/edu_sharing/restservices/shared/Preview.java index 7fb465b0bd..afdea8f09e 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/restservices/shared/Preview.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/restservices/shared/Preview.java @@ -5,8 +5,7 @@ ; import java.io.Serializable; -import java.util.HashMap; -import java.util.List; +import java.util.Map; import org.apache.log4j.Logger; import org.edu_sharing.repository.client.tools.CCConstants; @@ -34,7 +33,7 @@ public class Preview implements Serializable { public Preview(){ } - public Preview(NodeService nodeService, String storeProtocol, String storeIdentifier, String nodeId, String version, String type, HashMap nodeProps) { + public Preview(NodeService nodeService, String storeProtocol, String storeIdentifier, String nodeId, String version, String type, Map nodeProps) { GetPreviewResult preview = nodeService.getPreview(storeProtocol, storeIdentifier, nodeId ,nodeProps, version); PreviewServlet.PreviewDetail detail = null; try { diff --git a/Backend/services/core/src/main/java/org/edu_sharing/restservices/shared/User.java b/Backend/services/core/src/main/java/org/edu_sharing/restservices/shared/User.java index 3bcc945b03..ca638e3329 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/restservices/shared/User.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/restservices/shared/User.java @@ -15,7 +15,7 @@ public class User extends UserSimple { private NodeRef homeFolder = null; - private List sharedFolders = new ArrayList(); + private List sharedFolders = new ArrayList<>(); private UserQuota quota; public User(){super();} diff --git a/Backend/services/core/src/main/java/org/edu_sharing/restservices/shared/UserProfileAppAuth.java b/Backend/services/core/src/main/java/org/edu_sharing/restservices/shared/UserProfileAppAuth.java index 7904478d10..5bbb5d0461 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/restservices/shared/UserProfileAppAuth.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/restservices/shared/UserProfileAppAuth.java @@ -3,12 +3,13 @@ import org.codehaus.jackson.annotate.JsonProperty; import java.util.HashMap; +import java.util.Map; public class UserProfileAppAuth extends UserProfile { - HashMap extendedAttributes = new HashMap<>(); + Map extendedAttributes = new HashMap<>(); @JsonProperty - public HashMap getExtendedAttributes() { + public Map getExtendedAttributes() { return extendedAttributes; } } diff --git a/Backend/services/core/src/main/java/org/edu_sharing/restservices/statistic/v1/model/StatisticEntry.java b/Backend/services/core/src/main/java/org/edu_sharing/restservices/statistic/v1/model/StatisticEntry.java index 8906ccb386..6a706386a9 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/restservices/statistic/v1/model/StatisticEntry.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/restservices/statistic/v1/model/StatisticEntry.java @@ -11,7 +11,7 @@ public class StatisticEntry { String property; - List entities = new ArrayList(); + List entities = new ArrayList<>(); @Schema(required = true, description = "") @JsonProperty("property") diff --git a/Backend/services/core/src/main/java/org/edu_sharing/restservices/statistic/v1/model/StatisticRequest.java b/Backend/services/core/src/main/java/org/edu_sharing/restservices/statistic/v1/model/StatisticRequest.java index 975b6eaf75..c7e0f6e28d 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/restservices/statistic/v1/model/StatisticRequest.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/restservices/statistic/v1/model/StatisticRequest.java @@ -13,7 +13,7 @@ public class StatisticRequest { Filter filter; - List properties = new ArrayList(); + List properties = new ArrayList<>(); @Schema(required = true, description = "") @JsonProperty("filter") diff --git a/Backend/services/core/src/main/java/org/edu_sharing/restservices/statistic/v1/model/Statistics.java b/Backend/services/core/src/main/java/org/edu_sharing/restservices/statistic/v1/model/Statistics.java index f02ba752bf..cf13368b79 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/restservices/statistic/v1/model/Statistics.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/restservices/statistic/v1/model/Statistics.java @@ -9,7 +9,7 @@ public class Statistics { - List entries = new ArrayList(); + List entries = new ArrayList<>(); public void setEntries(List entries) { this.entries = entries; diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/admin/AdminService.java b/Backend/services/core/src/main/java/org/edu_sharing/service/admin/AdminService.java index 7ecfe2fe95..2349f98a60 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/admin/AdminService.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/admin/AdminService.java @@ -4,7 +4,6 @@ import java.io.InputStream; import java.io.Serializable; import java.util.Collection; -import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; @@ -32,7 +31,7 @@ public interface AdminService { void refreshApplicationInfo(); - HashMap addApplication(String appMetadataUrl) throws Exception; + Map addApplication(String appMetadataUrl) throws Exception; List getServerUpdateInfos(); @@ -44,11 +43,11 @@ public interface AdminService { Map getCacheEntries(String beanName); - public void removeCacheEntry(Integer index, String beanName); + void removeCacheEntry(Integer index, String beanName); - public CacheCluster getCacheCluster(); + CacheCluster getCacheCluster(); - public List getCacheClusters(); + List getCacheClusters(); List getGlobalGroups() throws Throwable; @@ -57,7 +56,7 @@ void importOai(String set, String fileUrl, String oaiBaseUrl, String metadataSet String importerJobClassName, String importerClassName, String recordHandlerClassName, String binaryHandlerClassName, String persistentHandlerClassName, String oaiIds, boolean forceUpdate, String from, String until, String periodInDays) throws Exception; - List getImporterClasses() throws Exception; + List> getImporterClasses() throws Exception; void startCacheRefreshingJob(String folderId, boolean sticky) throws Exception; @@ -66,15 +65,15 @@ void importOai(String set, String fileUrl, String oaiBaseUrl, String metadataSet String getPropertyToMDSXml(List properties) throws Throwable; void writePublisherToMDSXml(String vcardProps, String valueSpaceProp, String ignoreValues, String filePath, - HashMap authInfo) throws Throwable; + Map authInfo) throws Throwable; Collection getAllValuesFor(String property) throws Throwable; void removeApplication(ApplicationInfo info) throws Exception; - HashMap addApplicationFromStream(InputStream is) throws Exception; + Map addApplicationFromStream(InputStream is) throws Exception; - public HashMap addApplication(Map properties) throws Exception; + public Map addApplication(Map properties) throws Exception; int importExcel(String parent, InputStream csv, Boolean addToCollection) throws Exception; @@ -98,9 +97,9 @@ void writePublisherToMDSXml(String vcardProps, String valueSpaceProp, String ign String uploadTemp(String name, InputStream is) throws Exception; - ImmediateJobListener startJob(String jobClass, HashMap params) throws Exception; + ImmediateJobListener startJob(String jobClass, Map params) throws Exception; - Object startJobSync(String jobClass, HashMap stringObjectHashMap) throws Throwable; + Object startJobSync(String jobClass, Map stringObjectMap) throws Throwable; RepositoryConfig getConfig(); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/admin/AdminServiceImpl.java b/Backend/services/core/src/main/java/org/edu_sharing/service/admin/AdminServiceImpl.java index a8a93c5059..b6ab266921 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/admin/AdminServiceImpl.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/admin/AdminServiceImpl.java @@ -22,7 +22,6 @@ import lombok.RequiredArgsConstructor; import org.alfresco.repo.cache.SimpleCache; import org.alfresco.repo.security.authentication.AuthenticationUtil; -import org.alfresco.service.ServiceRegistry; import org.alfresco.service.cmr.module.ModuleInstallState; import org.alfresco.service.cmr.module.ModuleService; import org.alfresco.service.cmr.repository.NodeRef; @@ -83,7 +82,6 @@ import org.edu_sharing.service.version.VersionService; import org.edu_sharing.spring.ApplicationContextFactory; import org.edu_sharing.spring.scope.refresh.ContextRefreshUtils; -import org.springframework.context.ApplicationContext; import org.springframework.stereotype.Component; import org.springframework.util.StreamUtils; import org.w3c.dom.Document; @@ -133,7 +131,7 @@ public Collection getAllValuesFor(String property) throws Throwable { RecurseMode.Folders ); - /*HashMap importFolderProps = mcAlfrescoBaseClient.getChild(companyHomeId, CCConstants.CCM_TYPE_MAP, CCConstants.CM_NAME, + /*Map importFolderProps = mcAlfrescoBaseClient.getChild(companyHomeId, CCConstants.CCM_TYPE_MAP, CCConstants.CM_NAME, OAIPMHLOMImporter.FOLDER_NAME_IMPORTED_OBJECTS);*/ for (NodeRef childEntry : children) { Serializable value = NodeServiceHelper.getPropertyNative(childEntry, property); @@ -224,7 +222,7 @@ private List getEffectiveSource(String nodeId, String authority, String p @Override public String addToolpermission(String name) throws Throwable { ToolPermissionService tpService = ToolPermissionServiceFactory.getInstance(); - HashMap props = new HashMap<>(); + Map props = new HashMap<>(); props.put(CCConstants.CM_NAME, name); String nodeId = NodeServiceFactory.getLocalService().createNodeBasic(tpService.getEdu_SharingToolPermissionsFolder().getId(), CCConstants.CCM_TYPE_TOOLPERMISSION, props); PermissionServiceFactory.getLocalService().setPermissionInherit(nodeId, false); @@ -275,13 +273,13 @@ public void setToolpermissions(String authority, Map authInfo) throws Throwable { File file = new File(filePath); Result result = new StreamResult(file); writePublisherToMDSXml(result,vcardProps,valueSpaceProp,ignoreValues,authInfo); } - public String getPublisherToMDSXml(List vcardProps, String valueSpaceProp, String ignoreValues, HashMap authInfo) throws Throwable { + public String getPublisherToMDSXml(List vcardProps, String valueSpaceProp, String ignoreValues, Map authInfo) throws Throwable { StringWriter writer=new StringWriter(); Result result = new StreamResult(writer); writePublisherToMDSXml(result,StringUtils.join(vcardProps,","),valueSpaceProp,ignoreValues,authInfo); @@ -325,16 +323,16 @@ public void writePropertyToMDSXml(Result result, String property) throws Throwab xformer.transform(source, result); } - public void writePublisherToMDSXml(Result result, String vcardProps, String valueSpaceProp, String ignoreValues, HashMap authInfo) throws Throwable { + public void writePublisherToMDSXml(Result result, String vcardProps, String valueSpaceProp, String ignoreValues, Map authInfo) throws Throwable { List ignoreValuesList = null; if (ignoreValues != null && !ignoreValues.trim().equals("")) { ignoreValuesList = Arrays.asList(ignoreValues.split(",")); } else { - ignoreValuesList = new ArrayList(); + ignoreValuesList = new ArrayList<>(); } - ArrayList allValues = new ArrayList(); + ArrayList allValues = new ArrayList<>(); String[] splittedVCardProp = vcardProps.split(","); for (String oneVCardProp : splittedVCardProp) { allValues.addAll(getAllValuesFor(oneVCardProp)); @@ -352,7 +350,7 @@ public void writePublisherToMDSXml(Result result, String vcardProps, String valu valueSpace.setAttribute("property", valueSpaceProp != null ? valueSpaceProp : splittedVCardProp[0]); rootElement.appendChild(valueSpace); - ArrayList toSort = new ArrayList(); + ArrayList toSort = new ArrayList<>(); for (String vcardString : allValues) { //multivalue @@ -362,7 +360,7 @@ public void writePublisherToMDSXml(Result result, String vcardProps, String valu if (!toSort.contains(splittedVCardString)) toSort.add(splittedVCardString); } else { - ArrayList> vcardList = VCardConverter.vcardToHashMap(splittedVCardString); + ArrayList> vcardList = VCardConverter.vcardToMap(splittedVCardString); if (vcardList != null && vcardList.size() > 0) { Map map = vcardList.get(0); String publisherString = (String) map.get(CCConstants.VCARD_T_FN); @@ -463,7 +461,7 @@ public void removeApplication(ApplicationInfo info) throws Exception { } @Override - public HashMap addApplication(String appMetadataUrl) throws Exception { + public Map addApplication(String appMetadataUrl) throws Exception { HttpQueryTool httpQuery = new HttpQueryTool(); String httpQueryResult = httpQuery.query(appMetadataUrl); @@ -476,7 +474,7 @@ public HashMap addApplication(String appMetadataUrl) throws Exce } @Override - public HashMap addApplicationFromStream(InputStream is) throws Exception { + public Map addApplicationFromStream(InputStream is) throws Exception { Properties props = new SortedProperties(); props.loadFromXML(is); @@ -489,7 +487,7 @@ public HashMap addApplicationFromStream(InputStream is) throws E return storeProperties(appId, props); } - public HashMap addApplication(Map properties) throws Exception { + public Map addApplication(Map properties) throws Exception { if (properties == null) { throw new Exception("no properties provided"); } @@ -528,7 +526,7 @@ public HashMap addApplication(Map properties) th return storeProperties(appId, props); } - private HashMap storeProperties(String appId, Properties props) throws Exception { + private Map storeProperties(String appId, Properties props) throws Exception { String fileNamePart = appId.replaceAll("[/:]", ""); String filename = "app-" + fileNamePart + ".properties.xml"; @@ -595,12 +593,12 @@ private HashMap storeProperties(String appId, Properties props) //homeAppProps.setProperty(ApplicationInfo.KEY_PREVIEWURL, previewUrl); //overwrite - homeAppProps.storeToXML(new FileOutputStream(new File(homeAppPath)), " added contenturl and preview url"); + homeAppProps.storeToXML(new FileOutputStream(homeAppPath), " added contenturl and preview url"); } ContextRefreshUtils.refreshContext(); - HashMap result = new HashMap(); + Map result = new HashMap<>(); for (Object key : props.keySet()) { result.put((String) key, props.getProperty((String) key)); } @@ -625,7 +623,7 @@ public List getServerUpdateInfos() { .peek((r) -> { try { Protocol protocol = ApplicationContextFactory.getApplicationContext().getBean(Protocol.class); - HashMap entry = protocol.getSysUpdateEntry(r.getId()); + Map entry = protocol.getSysUpdateEntry(r.getId()); String date = (String) entry.get(CCConstants.CCM_PROP_SYSUPDATE_DATE); r.setExecutedAt(Long.parseLong(date)); } catch (Throwable ignored) { @@ -683,7 +681,7 @@ public void refreshEduGroupCache(boolean keepExisting) { @Override public void testMail(String receiver, String template) { try { - HashMap dummy = new HashMap<>(); + Map dummy = new HashMap<>(); dummy.put("link", URLTool.getNgComponentsUrl(true) + "admin"); dummy.put("link.static", URLTool.getNgComponentsUrl(false) + "admin"); MailTemplate.sendMail(receiver, template, dummy); @@ -786,12 +784,12 @@ public Collection getActiveNodeLocks() { @Override public List getGlobalGroups() throws Throwable { - ArrayList result = new ArrayList(); + ArrayList result = new ArrayList<>(); MCAlfrescoBaseClient mcAlfrescoBaseClient = new MCAlfrescoAPIClient(); - HashMap> raw = mcAlfrescoBaseClient.search("TYPE:cm\\:authorityContainer AND @ccm\\:scopetype:\"global\""); + Map> raw = mcAlfrescoBaseClient.search("TYPE:cm\\:authorityContainer AND @ccm\\:scopetype:\"global\""); - for (Map.Entry> entry : raw.entrySet()) { + for (Map.Entry> entry : raw.entrySet()) { GlobalGroup group = new GlobalGroup(); group.setName((String) entry.getValue().get(CCConstants.CM_PROP_AUTHORITY_AUTHORITYNAME)); group.setDisplayName((String) entry.getValue().get(CCConstants.CM_PROP_AUTHORITY_AUTHORITYDISPLAYNAME)); @@ -804,13 +802,13 @@ public List getGlobalGroups() throws Throwable { return result; } - private HashMap getAuthInfo() { + private Map getAuthInfo() { return new AuthenticationToolAPI().getAuthentication(Context.getCurrentInstance().getRequest().getSession()); } @Override - public List getImporterClasses() throws Exception { - Class[] importerBaseClass = new Class[]{ + public List> getImporterClasses() throws Exception { + Class[] importerBaseClass = new Class[]{ org.edu_sharing.repository.server.jobs.quartz.ImporterJob.class, org.edu_sharing.repository.server.jobs.quartz.OAIXMLValidatorJob.class, org.edu_sharing.repository.server.jobs.quartz.ImporterJobSAX.class @@ -834,7 +832,7 @@ public int importExcel(String parent, InputStream csv, Boolean addToCollection) @Override public String importOaiXml(InputStream xml, String recordHandlerClassName, String binaryHandlerClassName) throws Exception { - HashMap paramsMap = new HashMap<>(); + Map paramsMap = new HashMap<>(); if (recordHandlerClassName != null && !recordHandlerClassName.trim().equals("")) { paramsMap.put(OAIConst.PARAM_RECORDHANDLER, recordHandlerClassName); } @@ -876,7 +874,7 @@ private String mapConfigFile(String filename, PropertiesHelper.Config.PathPrefix public void importOai(String set, String fileUrl, String oaiBaseUrl, String metadataSetId, String metadataPrefix, String importerJobClassName, String importerClassName, String recordHandlerClassName, String binaryHandlerClassName, String persistentHandlerClassName, String oaiIds, boolean forceUpdate, String from, String until, String periodInDays) throws Exception { //new JobExecuter().start(ImporterJob.class, authInfo, setsParam.toArray(new String[setsParam.size()])); - HashMap paramsMap = new HashMap(); + Map paramsMap = new HashMap<>(); List sets = new ArrayList(Arrays.asList(set.split(","))); if (fileUrl != null && !fileUrl.isEmpty() && !(fileUrl.startsWith("http://") || fileUrl.startsWith("https://"))) throw new Exception("file url " + fileUrl + " is not a valid url"); @@ -943,7 +941,7 @@ public void importOai(String set, String fileUrl, String oaiBaseUrl, String meta } @Override - public ImmediateJobListener startJob(String jobClass, HashMap params) throws Exception { + public ImmediateJobListener startJob(String jobClass, Map params) throws Exception { if (params == null) { params = new HashMap<>(); @@ -963,7 +961,7 @@ public ImmediateJobListener startJob(String jobClass, HashMap pa } @Override - public Object startJobSync(String jobClass, HashMap params) throws Throwable { + public Object startJobSync(String jobClass, Map params) throws Throwable { ImmediateJobListener listener = startJob(jobClass, params); while(true) { if(listener.wasExecuted()) { @@ -982,7 +980,7 @@ public Object startJobSync(String jobClass, HashMap params) throw @Override public void startCacheRefreshingJob(String folderId, boolean sticky) throws Exception { - HashMap paramsMap = new HashMap(); + Map paramsMap = new HashMap<>(); paramsMap.put("rootFolderId", folderId); paramsMap.put("sticky", sticky + ""); paramsMap.put(JobHandler.AUTH_INFO_KEY, getAuthInfo()); @@ -995,7 +993,7 @@ public void startCacheRefreshingJob(String folderId, boolean sticky) throws Exce @Override public void removeDeletedImports(String oaiBaseUrl, String cataloges, String oaiMetadataPrefix) throws Exception { - HashMap paramsMap = new HashMap(); + Map paramsMap = new HashMap<>(); paramsMap.put(JobHandler.AUTH_INFO_KEY, getAuthInfo()); paramsMap.put(OAIConst.PARAM_OAI_BASE_URL, oaiBaseUrl); paramsMap.put(OAIConst.PARAM_OAI_SETS, cataloges); @@ -1028,7 +1026,7 @@ public void updatePropertiesXML(String xmlFile, Map properties) } public void exportLom(String filterQuery, String targetDir, boolean subobjectHandler) throws Exception { - HashMap paramsMap = new HashMap(); + Map paramsMap = new HashMap<>(); paramsMap.put(ExporterJob.PARAM_LUCENE_FILTER, filterQuery); paramsMap.put(ExporterJob.PARAM_OUTPUT_DIR, targetDir); paramsMap.put(ExporterJob.PARAM_WITH_SUBOBJECTS, Boolean.toString(subobjectHandler)); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/admin/SystemFolder.java b/Backend/services/core/src/main/java/org/edu_sharing/service/admin/SystemFolder.java index 8c7b26296b..89e6cad74e 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/admin/SystemFolder.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/admin/SystemFolder.java @@ -22,6 +22,7 @@ import java.io.InputStream; import java.io.InputStreamReader; import java.util.HashMap; +import java.util.Map; public class SystemFolder { @@ -36,7 +37,7 @@ public static NodeRef getSystemObject(String name) throws Throwable { NodeService nodeService = NodeServiceFactory.getLocalService(); String node = nodeService.findNodeByName(folder, name); if (node == null) { - HashMap props = new HashMap<>(); + Map props = new HashMap<>(); props.put(CCConstants.CM_NAME, name); node = nodeService.createNodeBasic(folder, CCConstants.CCM_TYPE_IO, props); } diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/admin/SystemStatistic.java b/Backend/services/core/src/main/java/org/edu_sharing/service/admin/SystemStatistic.java index 6ebd1ab786..ed49c8247a 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/admin/SystemStatistic.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/admin/SystemStatistic.java @@ -21,7 +21,7 @@ public static void addRepoState(CacheCluster cacheCluster) { public static List getAllRepoStates(){ - List cacheCluster = new ArrayList(); + List cacheCluster = new ArrayList<>(); Iterator iter = bufferRepoState.iterator(); while(iter.hasNext()) { @@ -33,7 +33,7 @@ public static List getAllRepoStates(){ public static List getRepoStates(Date since){ - List cacheCluster = new ArrayList(); + List cacheCluster = new ArrayList<>(); Iterator iter = bufferRepoState.iterator(); while(iter.hasNext()) { diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/archive/ArchiveServiceImpl.java b/Backend/services/core/src/main/java/org/edu_sharing/service/archive/ArchiveServiceImpl.java index d79c1f77d9..ccdbcd1dc7 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/archive/ArchiveServiceImpl.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/archive/ArchiveServiceImpl.java @@ -87,7 +87,7 @@ public void purge(List archivedNodeIds) { @Override public List restore(List archivedNodeIds, String toFolder) { - List result = new ArrayList(); + List result = new ArrayList<>(); for(String archivedNodeId : archivedNodeIds){ result.add(this.restoreNode(archivedNodeId, toFolder)); } diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/authentication/AuthMethodCAS.java b/Backend/services/core/src/main/java/org/edu_sharing/service/authentication/AuthMethodCAS.java index 0eb10b2cd8..26752e809d 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/authentication/AuthMethodCAS.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/authentication/AuthMethodCAS.java @@ -79,7 +79,7 @@ public void init(){ this.serviceRegistry = (ServiceRegistry) applicationContext.getBean("ServiceRegistry"); } - public String authenticate(HashMap params) throws AuthenticationException{ + public String authenticate(Map params) throws AuthenticationException{ String result = null; String proxyValidate = null; String proxyservice = null; @@ -155,7 +155,7 @@ public Object execute() throws Exception { authenticationService.authenticate(homeRepository.getUsername(), homeRepository.getPassword().toCharArray()); authenticationDao.createUser(userName, "liferay".toCharArray()); - Map persProps = new HashMap(); + Map persProps = new HashMap<>(); persProps.put(QName.createQName(CCConstants.PROP_USERNAME), userName); persProps.put(QName.createQName(CCConstants.PROP_USER_EMAIL), userName); personService.setPersonProperties(userName, persProps); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/authentication/AuthMethodInterface.java b/Backend/services/core/src/main/java/org/edu_sharing/service/authentication/AuthMethodInterface.java index 92c1e0b222..1f70b44be3 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/authentication/AuthMethodInterface.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/authentication/AuthMethodInterface.java @@ -27,11 +27,11 @@ */ package org.edu_sharing.service.authentication; -import java.util.HashMap; +import java.util.Map; import org.alfresco.repo.security.authentication.AuthenticationException; public interface AuthMethodInterface { - public String authenticate(HashMap params) throws AuthenticationException; + String authenticate(Map params) throws AuthenticationException; } diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/authentication/AuthMethodSSO.java b/Backend/services/core/src/main/java/org/edu_sharing/service/authentication/AuthMethodSSO.java index a12c4c7551..a8f10b7e12 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/authentication/AuthMethodSSO.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/authentication/AuthMethodSSO.java @@ -31,11 +31,8 @@ import org.alfresco.repo.security.authentication.AuthenticationException; import org.apache.log4j.Logger; import org.edu_sharing.alfresco.lightbend.LightbendConfigLoader; -import org.edu_sharing.repository.server.tools.ApplicationInfo; -import org.edu_sharing.repository.server.tools.ApplicationInfoList; -import java.util.Arrays; -import java.util.HashMap; +import java.util.Map; /** @@ -56,7 +53,7 @@ public class AuthMethodSSO implements AuthMethodInterface { @Override - public String authenticate(HashMap params) throws AuthenticationException { + public String authenticate(Map params) throws AuthenticationException { //for security reasons: sso auth should be explicit activated in config //so that we don't get an open gate when someone forgets to remove the shibboleth servlet from web.xml and don't protects this url //(shibboleth header usage) diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/authentication/AuthMethodTrustedApplication.java b/Backend/services/core/src/main/java/org/edu_sharing/service/authentication/AuthMethodTrustedApplication.java index 7c4d8dddb9..41f8919a3e 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/authentication/AuthMethodTrustedApplication.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/authentication/AuthMethodTrustedApplication.java @@ -1,9 +1,6 @@ package org.edu_sharing.service.authentication; -import java.rmi.RemoteException; -import java.util.HashMap; - -import javax.xml.rpc.ServiceException; +import java.util.Map; import org.alfresco.repo.security.authentication.AuthenticationException; import org.apache.log4j.Logger; @@ -17,7 +14,7 @@ public class AuthMethodTrustedApplication implements AuthMethodInterface { SSOAuthorityMapper ssoAuthorityMapper; - public String authenticate(HashMap params) throws AuthenticationException { + public String authenticate(Map params) throws AuthenticationException { String userName = params.get(ssoAuthorityMapper.getSSOUsernameProp()); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/authentication/AuthMethodTrustedRepository.java b/Backend/services/core/src/main/java/org/edu_sharing/service/authentication/AuthMethodTrustedRepository.java index a614d0b3cf..7747094802 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/authentication/AuthMethodTrustedRepository.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/authentication/AuthMethodTrustedRepository.java @@ -27,36 +27,22 @@ */ package org.edu_sharing.service.authentication; -import java.io.Serializable; -import java.rmi.RemoteException; -import java.util.HashMap; -import java.util.List; import java.util.Map; -import javax.xml.rpc.ServiceException; - import org.alfresco.repo.security.authentication.AuthenticationException; import org.alfresco.repo.security.authentication.MutableAuthenticationDao; -import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback; import org.alfresco.service.ServiceRegistry; -import org.alfresco.service.cmr.repository.ChildAssociationRef; import org.alfresco.service.cmr.repository.NodeRef; import org.alfresco.service.cmr.repository.NodeService; -import org.alfresco.service.cmr.repository.StoreRef; import org.alfresco.service.cmr.search.SearchService; import org.alfresco.service.cmr.security.AuthenticationService; -import org.alfresco.service.cmr.security.NoSuchPersonException; import org.alfresco.service.cmr.security.PersonService; -import org.alfresco.service.namespace.QName; -import org.alfresco.service.namespace.RegexQNamePattern; -import org.alfresco.service.transaction.TransactionService; import org.apache.commons.mail2.core.EmailException; import org.apache.log4j.Logger; import org.edu_sharing.alfrescocontext.gate.AlfAppContextGate; import org.edu_sharing.repository.client.tools.CCConstants; import org.edu_sharing.repository.server.tools.ApplicationInfo; import org.edu_sharing.repository.server.tools.ApplicationInfoList; -import org.edu_sharing.repository.server.tools.KeyTool; import org.edu_sharing.service.usage.AlfServicesWrapper; import org.springframework.context.ApplicationContext; @@ -117,7 +103,7 @@ public void init(){ } - public String authenticate(HashMap params) throws AuthenticationException { + public String authenticate(Map params) throws AuthenticationException { throw new RuntimeException("old soap method should not be used"); } diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/authentication/EduAuthentication.java b/Backend/services/core/src/main/java/org/edu_sharing/service/authentication/EduAuthentication.java index 26fc07198f..44181b7f91 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/authentication/EduAuthentication.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/authentication/EduAuthentication.java @@ -71,7 +71,7 @@ public void setCcauthenticationComponent(EduAuthenticationComponent ccauthentica public void authenticateByApp(String applicationId, String userName, String email, String ticket,String host, Boolean createUser) throws AuthenticationException{ - HashMap params = new HashMap(); + Map params = new HashMap<>(); params.put(AuthMethodTrustedRepository.PARAM_EMAIL, email); params.put(AuthMethodTrustedRepository.PARAM_APPLICATIONID, applicationId); params.put(AuthMethodTrustedRepository.PARAM_USERNAME, userName); @@ -83,7 +83,7 @@ public void authenticateByApp(String applicationId, String userName, String emai } - public void authenticateByTrustedApp(HashMap params){ + public void authenticateByTrustedApp(Map params){ ccauthenticationComponent.authenticate(AuthMethodTrustedApplication.class.getName(), params); } @@ -96,7 +96,7 @@ public void authenticateByTrustedApp(HashMap params){ */ public void authenticateByCAS(String userName, String proxyTicket){ - HashMap params = new HashMap(); + Map params = new HashMap<>(); params.put(AuthMethodCAS.PARAM_USERNAME, userName); params.put(AuthMethodCAS.PARAM_PROXYTICKET, proxyTicket); ccauthenticationComponent.authenticate(AuthMethodCAS.class.getName(), params); @@ -109,7 +109,7 @@ public void authenticateByCAS(String userName, String proxyTicket){ * @param authType * @param params */ - public void authenticateBySSO(String authType, HashMap params){ + public void authenticateBySSO(String authType, Map params){ params.put(SSOAuthorityMapper.PARAM_SSO_TYPE, authType); ccauthenticationComponent.authenticate(AuthMethodSSO.class.getName(),params); } @@ -174,8 +174,8 @@ public void authenticate(String userName, char[] password) throws Authentication - public HashMap getPersonProperties(String username){ - HashMap result = new HashMap(); + public Map getPersonProperties(String username){ + Map result = new HashMap<>(); /** * Attention if you put an username that does not exist, alfresco creates a ne person object without an user object in user store * watch out for Alfresco class PersonServiceImpl diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/authentication/EduAuthenticationComponent.java b/Backend/services/core/src/main/java/org/edu_sharing/service/authentication/EduAuthenticationComponent.java index c4ec7ad2ac..c40b11622c 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/authentication/EduAuthenticationComponent.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/authentication/EduAuthenticationComponent.java @@ -27,8 +27,8 @@ */ package org.edu_sharing.service.authentication; -import java.util.HashMap; import java.util.List; +import java.util.Map; import org.alfresco.model.ContentModel; import org.alfresco.repo.security.authentication.AuthenticationComponent; @@ -77,7 +77,7 @@ public void init(){ * @param authClassName * @param params */ - public String authenticate(String authClassName, HashMap params) throws AuthenticationException{ + public String authenticate(String authClassName, Map params) throws AuthenticationException{ String username = null; //only allow classes that are in ccAuthMethod List diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/authentication/SSOAuthorityMapper.java b/Backend/services/core/src/main/java/org/edu_sharing/service/authentication/SSOAuthorityMapper.java index e55b4f2bd9..5f761e0848 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/authentication/SSOAuthorityMapper.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/authentication/SSOAuthorityMapper.java @@ -119,7 +119,7 @@ public class SSOAuthorityMapper { CustomGroupMapping customGroupMapping; - List additionalAttributes = new ArrayList(); + List additionalAttributes = new ArrayList<>(); public void init(){ ApplicationContext applicationContext = AlfAppContextGate.getApplicationContext(); @@ -169,7 +169,7 @@ else if (authority.trim().equals(ApplicationInfoList.getHomeRepository().getUser * @return username: means the user exists(before or was created) null when * user does not exist and can not be created */ - public String mapAuthority(final HashMap ssoAttributes) { + public String mapAuthority(final Map ssoAttributes) { RunAsWork runAs = new RunAsWork() { @Override public String doWork() throws Exception { @@ -185,7 +185,7 @@ public String execute() throws Exception { } - private String mapAuthorityInternal(final HashMap ssoAttributes) { + private String mapAuthorityInternal(final Map ssoAttributes) { if(isDebug()){ for(Map.Entry ssoAttribute : ssoAttributes.entrySet()){ @@ -292,8 +292,8 @@ private String mapAuthorityInternal(final HashMap ssoAttributes) } // person - HashMap personMapping = mappingConfig.getPersonMapping(); - HashMap personProperties = new HashMap(); + Map personMapping = mappingConfig.getPersonMapping(); + Map personProperties = new HashMap<>(); for (Map.Entry ssoAttribute : ssoAttributes.entrySet()) { @@ -385,7 +385,7 @@ private String mapAuthorityInternal(final HashMap ssoAttributes) authenticationService.createAuthentication(existentUserName, new KeyTool().getRandomPassword().toCharArray()); } // group memberships - List mappingGroups = new ArrayList(mappingConfig.getGroupMapping()); + List mappingGroups = new ArrayList<>(mappingConfig.getGroupMapping()); /** * add moodle global groups @@ -462,9 +462,9 @@ private String mapAuthorityInternal(final HashMap ssoAttributes) if(lmsGlobalGroups != null && !organisationName.trim().equals("")){ JSONArray globalGroupsJA = new JSONArray(lmsGlobalGroups); - HashMap alfrescoNameLmsIdMap = new HashMap(); + Map alfrescoNameLmsIdMap = new HashMap<>(); - List lmsGlobalGroupsList = new ArrayList(); + List lmsGlobalGroupsList = new ArrayList<>(); for(int i = 0; i < globalGroupsJA.length(); i++){ JSONObject globalGroupJO = (JSONObject)globalGroupsJA.get(i); @@ -498,7 +498,7 @@ public boolean isTrue(Map ssoAttributes) { if (mappingGroups != null) { - List currentGroupsForUser = new ArrayList(); + List currentGroupsForUser = new ArrayList<>(); for (MappingGroup mappingGroup : mappingGroups) { String groupName = mappingGroup.getMapTo(); @@ -520,7 +520,7 @@ public boolean isTrue(Map ssoAttributes) { String newGroupName = authorityService.createAuthority(AuthorityType.GROUP, mappingGroup.getMapTo(), mappingGroup.getMapToDisplayName(), authorityService.getDefaultZones()); NodeRef nodeRef = authorityService.getAuthorityNodeRef(newGroupName); - Map aspectProperties = new HashMap(); + Map aspectProperties = new HashMap<>(); aspectProperties.put(QName.createQName(CCConstants.CCM_PROP_GROUPEXTENSION_GROUPSOURCE), appId); nodeService.addAspect(nodeRef, QName.createQName(CCConstants.CCM_ASPECT_GROUPEXTENSION), aspectProperties); } @@ -610,7 +610,7 @@ public boolean isTrue(Map ssoAttributes) { //edu-sharing federated global groups String gg = ssoAttributes.get(CCConstants.EDU_SHARING_GLOBAL_GROUPS); - List globalGroupsMembership = (gg != null && !gg.trim().equals("")) ? Arrays.asList(gg.split(";")) : new ArrayList(); + List globalGroupsMembership = (gg != null && !gg.trim().equals("")) ? Arrays.asList(gg.split(";")) : new ArrayList<>(); //remove user from global group Set authoritiesForUser = authorityService.getAuthoritiesForUser(userName); @@ -691,7 +691,7 @@ public String getUserAttribute(String alfrescoUserAtt){ return result; } - private void logErrorParams(String missing, HashMap ssoAttributes) { + private void logErrorParams(String missing, Map ssoAttributes) { String logString = ""; for (Map.Entry entry : ssoAttributes.entrySet()) { logString += entry.getKey() + ": " + entry.getValue() + "; "; diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/authentication/ScopeUserHomeServiceImpl.java b/Backend/services/core/src/main/java/org/edu_sharing/service/authentication/ScopeUserHomeServiceImpl.java index e0eba8a8c2..892574f23e 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/authentication/ScopeUserHomeServiceImpl.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/authentication/ScopeUserHomeServiceImpl.java @@ -108,7 +108,7 @@ public NodeRef doWork() throws Exception { serviceRegistry.getPermissionService().setPermission(parentNodeRef, PermissionService.OWNER_AUTHORITY, PermissionService.ALL_PERMISSIONS, true); serviceRegistry.getPermissionService().setPermission(parentNodeRef, username, PermissionService.ALL_PERMISSIONS, true); - Map personScopeProps = new HashMap(); + Map personScopeProps = new HashMap<>(); personScopeProps.put(PROP_PERSON_SCOPE_HOMEFOLDER, parentNodeRef); personScopeProps.put(PROP_PERSON_SCOPE_NAME, scope); ChildAssociationRef childRef = nodeService.createNode(personNodeRef, @@ -160,7 +160,7 @@ public NodeRef getRootNodeRef(String scope){ NodeRef scopeRootNodeRef = getOrCreateMap(companyHome,SCOPE_ROOT,null); NodeServiceInterceptor.setEduSharingScope(currentScope); - Map scopeProperties = new HashMap(); + Map scopeProperties = new HashMap<>(); scopeProperties.put(QName.createQName(CCConstants.CCM_PROP_EDUSCOPE_NAME), scope); scopeProperties.put(ContentModel.PROP_NAME, scope); NodeRef scopeNodeRef = getOrCreateMap(scopeRootNodeRef,scope,scopeProperties); @@ -174,7 +174,7 @@ private NodeRef getOrCreateMap(NodeRef parent, String name, Map(); + properties = new HashMap<>(); properties.put(ContentModel.PROP_NAME, name); } diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/authentication/UserDataServiceLDAPImpl.java b/Backend/services/core/src/main/java/org/edu_sharing/service/authentication/UserDataServiceLDAPImpl.java index f350ec6d9d..0ecb218233 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/authentication/UserDataServiceLDAPImpl.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/authentication/UserDataServiceLDAPImpl.java @@ -84,7 +84,7 @@ public Map getRepositoryUserProperties(String directoryUser String[] propsToReturn = attMap.keySet().toArray(new String[attMap.keySet().size()]); Map userDirectoryRequestResult = getDirectoryUserProperties(directoryUsernameProp, directoryUsernameValue, propsToReturn); - Map result = new HashMap(); + Map result = new HashMap<>(); for (String ldapProp : propsToReturn) { String repProp = attMap.get(ldapProp); @@ -127,7 +127,7 @@ public Map getDirectoryUserProperties(String directoryUsernamePr , "(" + directoryUsernameProp + "=" + directoryUsernameValue + ")" // query , ctls); // - Map result = new HashMap(); + Map result = new HashMap<>(); while (rs.hasMore()) { @@ -168,7 +168,7 @@ public Map getDirectoryUserProperties(String directoryUsernamePr Map getAttributeMapping() { if (attributMapping == null) { - attributMapping = new HashMap(); + attributMapping = new HashMap<>(); attributMapping.put(firstNameProp, CCConstants.CM_PROP_PERSON_FIRSTNAME); attributMapping.put(lastNameProp, CCConstants.CM_PROP_PERSON_LASTNAME); attributMapping.put(emailProp, CCConstants.CM_PROP_PERSON_EMAIL); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/authentication/cas/PGTStack.java b/Backend/services/core/src/main/java/org/edu_sharing/service/authentication/cas/PGTStack.java index 11bbd0378c..d7fe5b3b92 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/authentication/cas/PGTStack.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/authentication/cas/PGTStack.java @@ -28,6 +28,7 @@ package org.edu_sharing.service.authentication.cas; import java.util.HashMap; +import java.util.Map; import java.util.Set; /** @@ -37,7 +38,7 @@ */ public class PGTStack { - private static HashMap map = new HashMap(); + private static Map map = new HashMap<>(); /** * diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/authentication/cas/PTValidation.java b/Backend/services/core/src/main/java/org/edu_sharing/service/authentication/cas/PTValidation.java index 13a53facd4..f01a2099ad 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/authentication/cas/PTValidation.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/authentication/cas/PTValidation.java @@ -72,7 +72,7 @@ public PTValidation(String validatePTURL, String _serviceUrl, String validCallba * if one callbackurl equals the construktorParam validCallbackUrl than this callbackurl is packed in the reultMap */ public Map getCredentials(String proxyTicket){ - HashMap resultMap = null; + Map resultMap = null; try{ url = url+"?ticket="+proxyTicket+"&service="+serviceUrl; logger.info("url:"+url); @@ -93,7 +93,7 @@ public Map getCredentials(String proxyTicket){ if (rootEle.getName().equals("serviceResponse")) { Element succEle = rootEle.getChild("authenticationSuccess", ns); if (succEle != null) { - resultMap = new HashMap(); + resultMap = new HashMap<>(); System.out.println(" succEle :" + succEle.getName()); Element eleUser = succEle.getChild("user", ns); resultMap.put(PTValidation.USER, eleUser.getValue()); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/authentication/sso/config/CustomGroupMapping.java b/Backend/services/core/src/main/java/org/edu_sharing/service/authentication/sso/config/CustomGroupMapping.java index f968fe008c..91fdeb92e7 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/authentication/sso/config/CustomGroupMapping.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/authentication/sso/config/CustomGroupMapping.java @@ -1,13 +1,13 @@ package org.edu_sharing.service.authentication.sso.config; -import java.util.HashMap; +import java.util.Map; import org.edu_sharing.service.authentication.SSOAuthorityMapper; public interface CustomGroupMapping { - public void map(HashMap ssoAttributes); + public void map(Map ssoAttributes); public void setSSOAuthorityMapper(SSOAuthorityMapper ssoAuthorityMapper); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/authentication/sso/config/IDPDomainMappingTool.java b/Backend/services/core/src/main/java/org/edu_sharing/service/authentication/sso/config/IDPDomainMappingTool.java index b94115c142..d679941fc1 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/authentication/sso/config/IDPDomainMappingTool.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/authentication/sso/config/IDPDomainMappingTool.java @@ -3,6 +3,7 @@ import java.io.IOException; import java.net.URL; import java.util.HashMap; +import java.util.Map; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; @@ -29,7 +30,7 @@ public class IDPDomainMappingTool { Document docMdSets = null; - HashMap mapper = new HashMap(); + Map mapper = new HashMap<>(); public IDPDomainMappingTool() { URL url = IDPDomainMappingTool.class.getResource(file); @@ -100,7 +101,7 @@ private void initMap(){ } } - public HashMap getMapper() { + public Map getMapper() { return mapper; } } diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/authentication/sso/config/MappingRoot.java b/Backend/services/core/src/main/java/org/edu_sharing/service/authentication/sso/config/MappingRoot.java index 07052fe1bc..bdd284461c 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/authentication/sso/config/MappingRoot.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/authentication/sso/config/MappingRoot.java @@ -3,13 +3,14 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; +import java.util.Map; public class MappingRoot { - HashMap personMapping; + Map personMapping; Condition personMappingCondition; - List groupMappings = new ArrayList(); + List groupMappings = new ArrayList<>(); public MappingRoot() { } @@ -18,7 +19,7 @@ public void setGroupMapping(List groupMapping) { this.groupMappings = groupMapping; } - public void setPersonMapping(HashMap personMapping) { + public void setPersonMapping(Map personMapping) { this.personMapping = personMapping; } @@ -26,12 +27,12 @@ public List getGroupMapping() { return groupMappings; } - public HashMap getPersonMapping() { + public Map getPersonMapping() { return personMapping; } public List getSSOGroupAttributes(){ - List ssoGroupAttributes = new ArrayList(); + List ssoGroupAttributes = new ArrayList<>(); for(MappingGroup groupMapping : groupMappings){ getSSOGroupAttributes(ssoGroupAttributes,groupMapping.getCondition()); } @@ -39,11 +40,11 @@ public List getSSOGroupAttributes(){ } public List getSSOPersonAttributes(){ - return new ArrayList(personMapping.keySet()); + return new ArrayList<>(personMapping.keySet()); } public List getAllSSOAttributes(){ - List result = new ArrayList(); + List result = new ArrayList<>(); result.addAll(getSSOPersonAttributes()); result.addAll(getSSOGroupAttributes()); return result; diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/authority/AuthorityServiceImpl.java b/Backend/services/core/src/main/java/org/edu_sharing/service/authority/AuthorityServiceImpl.java index ec130fc3db..131b1d8ffa 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/authority/AuthorityServiceImpl.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/authority/AuthorityServiceImpl.java @@ -244,7 +244,7 @@ public ArrayList getAllEduGroups(String authority) { - ArrayList result = new ArrayList(); + ArrayList result = new ArrayList<>(); for (String a : authoritiesForUser) { EduGroup eg = getEduGroup(a); @@ -298,7 +298,7 @@ public ArrayList getEduGroups() { @Override public ArrayList getEduGroups(String authority,String scope) { - ArrayList result = new ArrayList(); + ArrayList result = new ArrayList<>(); for (EduGroup eduGroup : getAllEduGroups(authority)) { if ((eduGroup.getScope() == null && scope == null) @@ -369,7 +369,7 @@ public EduGroup doWork() throws Exception { eduGroup.getGroupDisplayName()); // scope - Map propsAspectEduScope = new HashMap(); + Map propsAspectEduScope = new HashMap<>(); propsAspectEduScope.put(QName.createQName(CCConstants.CCM_PROP_EDUSCOPE_NAME), eduGroup.getScope()); nodeService.addAspect(nodeRef, QName.createQName(CCConstants.CCM_ASPECT_EDUSCOPE), @@ -385,7 +385,7 @@ public EduGroup doWork() throws Exception { } } folderName = NodeServiceHelper.cleanupCmName(folderName); - Map folderProps = new HashMap(); + Map folderProps = new HashMap<>(); folderProps.put(ContentModel.PROP_NAME, folderName); String assocName = "{" + CCConstants.NAMESPACE_CCM + "}" + folderName; @@ -402,7 +402,7 @@ public EduGroup doWork() throws Exception { } // edugroup aspect - Map propsAspectEduGroup = new HashMap(); + Map propsAspectEduGroup = new HashMap<>(); propsAspectEduGroup.put(QName.createQName(CCConstants.CCM_PROP_EDUGROUP_EDU_HOMEDIR), new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, eduGroupHomeFolderId)); nodeService.addAspect(nodeRef, QName.createQName(CCConstants.CCM_ASPECT_EDUGROUP), @@ -576,7 +576,7 @@ private void addUserExtensionAspect(String userName) { nodeService.addAspect(personService.getPerson(userName),QName.createQName(CCConstants.CCM_ASPECT_USER_EXTENSION),null); } private Map transformQName(Map data) { - Map transformed = new HashMap(); + Map transformed = new HashMap<>(); for(String key : data.keySet()) { transformed.put(QName.createQName(key), data.get(key)); } @@ -664,7 +664,7 @@ public Map getProfileSettingsProperties(String userName, S userCache.put(user,userObj); } - Map result = new HashMap(); + Map result = new HashMap<>(); List properties = new ArrayList<>();// ProfileSettings property to return // If profileSettingsProperty==null than Get all Properties for ProfileSettings @@ -700,7 +700,7 @@ public void createProxyUser(){ return; } - HashMap properties = new HashMap(); + Map properties = new HashMap<>(); properties.put(ContentModel.PROP_USERNAME, CCConstants.PROXY_USER); personService.createPerson(properties); serviceRegistry.getAuthenticationService() diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/bulk/BulkService.java b/Backend/services/core/src/main/java/org/edu_sharing/service/bulk/BulkService.java index dd653b627e..5249906283 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/bulk/BulkService.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/bulk/BulkService.java @@ -6,14 +6,15 @@ import java.util.HashMap; import java.util.List; +import java.util.Map; public interface BulkService { NodeRef getPrimaryFolder(); - NodeRef sync(String group, List match, List groupBy, String type, List aspects, HashMap properties, boolean forceUpdate) throws Throwable; + NodeRef sync(String group, List match, List groupBy, String type, List aspects, Map properties, boolean forceUpdate) throws Throwable; - NodeRef find(HashMap properties) throws Exception; + NodeRef find(Map properties) throws Exception; List runs(String replicationsource, BulkRun.RunState filterByState) throws DAOException; } diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/bulk/BulkServiceImpl.java b/Backend/services/core/src/main/java/org/edu_sharing/service/bulk/BulkServiceImpl.java index d32da9878b..2441be765e 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/bulk/BulkServiceImpl.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/bulk/BulkServiceImpl.java @@ -71,7 +71,7 @@ public class BulkServiceImpl implements BulkService, ApplicationListener propertiesNative){ + public NodeRef getOrCreate(NodeRef parent, String name, Map propertiesNative){ name = NodeServiceHelper.cleanupCmName(name); NodeRef replicationFolder = getOrCreateFolderInternal(parent, name, propertiesNative); BulkUpdateBehaviour behaviour = getBehaviourConfig(replicationFolder); @@ -94,7 +94,7 @@ private void copyPermissions(NodeRef fromFolder, NodeRef toFolder) { permissions.forEach(p -> permissionService.setPermission(toFolder, p.getAuthority(), p.getPermission(), p.getAccessStatus().equals(AccessStatus.ALLOWED))); } - private static NodeRef getOrCreateFolderInternal(NodeRef parent, String name, HashMap propertiesNative) { + private static NodeRef getOrCreateFolderInternal(NodeRef parent, String name, Map propertiesNative) { NodeRef node = nodeServiceAlfresco.getChildByName(parent, ContentModel.ASSOC_CONTAINS, name); if (node == null) { return createFolder(parent, name, propertiesNative); @@ -102,7 +102,7 @@ private static NodeRef getOrCreateFolderInternal(NodeRef parent, String name, Ha return node; } - private static NodeRef createFolder(NodeRef parent, String name, HashMap propertiesNative) { + private static NodeRef createFolder(NodeRef parent, String name, Map propertiesNative) { Map props = new HashMap<>(); props.put(ContentModel.PROP_NAME, name); if (propertiesNative != null) { @@ -170,25 +170,25 @@ private void refresh() { @Override - public NodeRef sync(String group, List match, List groupBy, String type, List aspects, HashMap properties, boolean resetVersion) throws Throwable { + public NodeRef sync(String group, List match, List groupBy, String type, List aspects, Map properties, boolean resetVersion) throws Throwable { if(match == null || match.size() == 0){ throw new IllegalArgumentException("match should contain at least 1 property"); } - HashMap propertiesFiltered = properties.entrySet().stream().filter((e) -> match.contains(e.getKey())). + Map propertiesFiltered = properties.entrySet().stream().filter((e) -> match.contains(e.getKey())). collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (a, b) -> b, HashMap::new)); if(propertiesFiltered.size() != match.size()){ throw new IllegalArgumentException("match contained property names that did not exist in the properties section. Please check that you provide data for all match properties."); } properties = NodeServiceHelper.transformShortToLongProperties(properties); - HashMap propertiesNative = NodeServiceHelper.getPropertiesSinglevalue(properties); + Map propertiesNative = NodeServiceHelper.getPropertiesSinglevalue(properties); propertiesNative.put(CCConstants.CM_NAME, NodeServiceHelper.cleanupCmName((String)(propertiesNative.get(CCConstants.CM_NAME))) + "_" + System.currentTimeMillis()); propertiesNative.remove(CCConstants.CCM_PROP_IO_VERSION_COMMENT); for (BulkServiceInterceptorInterface interceptor : interceptors) { propertiesNative = interceptor.preprocessProperties(propertiesNative); } // filter for valid/declared properties to store - HashMap rawProperties = new HashMap<>(propertiesNative); + Map rawProperties = new HashMap<>(propertiesNative); propertiesNative = propertiesNative.entrySet().stream().filter(property -> { QName prop = QName.createQName(property.getKey()); return serviceRegistry.getDictionaryService().getProperty(prop) != null; @@ -198,12 +198,12 @@ public NodeRef sync(String group, List match, List groupBy, Stri Map::putAll ); String lockId = propertiesFiltered.values().stream().filter(Objects::nonNull).map(v -> v[0]).collect(Collectors.joining(",")); - HashMap finalPropertiesNative = propertiesNative; + Map finalPropertiesNative = propertiesNative; NodeRef result = EduSharingLockHelper.runSingleton(BulkServiceImpl.class,"sync_" + lockId, () -> { NodeRef existing = null; try { existing = find(propertiesFiltered); - HashMap propertiesNativeMapped = finalPropertiesNative; + Map propertiesNativeMapped = finalPropertiesNative; if (existing == null) { NodeRef groupFolder = getOrCreate(primaryFolder, group, finalPropertiesNative); if (groupBy != null && groupBy.size() > 0) { @@ -230,7 +230,7 @@ public NodeRef sync(String group, List match, List groupBy, Stri if (Boolean.parseBoolean(blocked)) { throw new IllegalStateException("The given node was blocked for any updates and should not be reimported"); } - HashMap propertiesKeep = checkInternalOverrides(propertiesNativeMapped, existing); + Map propertiesKeep = checkInternalOverrides(propertiesNativeMapped, existing); if (resetVersion) { versionServiceAlfresco.deleteVersionHistory(existing); } @@ -263,7 +263,7 @@ public NodeRef sync(String group, List match, List groupBy, Stri } private List getAllAvailableProperties(NodeRef nodeRef) throws Exception { - /*HashMap cleanProps = new HashMap<>(); + /*Map cleanProps = new HashMap<>(); propsToClean.forEach((k) -> cleanProps.put(k, null)); return cleanProps;*/ return Stream.concat(MetadataHelper.getWidgetsByNode(nodeRef, false).stream().map((w) -> CCConstants.getValidGlobalName(w.getId())). @@ -277,8 +277,8 @@ private List getAllAvailableProperties(NodeRef nodeRef) throws Exception * alfresco will not override "removed" props, so we try to clean up via the mds * @return */ - private HashMap getCleanProps(NodeRef nodeRef, HashMap props) throws Exception { - HashMap mergedProps = new HashMap<>(); + private Map getCleanProps(NodeRef nodeRef, Map props) throws Exception { + Map mergedProps = new HashMap<>(); getAllAvailableProperties(nodeRef).forEach((k) -> mergedProps.put(k, null)); mergedProps.putAll(props); mergedProps.put(CCConstants.CCM_PROP_IO_CREATE_VERSION, false); @@ -291,7 +291,7 @@ private HashMap getCleanProps(NodeRef nodeRef, HashMap checkInternalOverrides(HashMap propertiesIn, NodeRef nodeRef) throws Exception { + private Map checkInternalOverrides(Map propertiesIn, NodeRef nodeRef) throws Exception { VersionHistory history = versionServiceAlfresco.getVersionHistory(nodeRef); if(history == null){ return null; @@ -300,7 +300,7 @@ private HashMap checkInternalOverrides(HashMap p Collections.reverse(versions); logger.debug(propertiesIn.get(CCConstants.CM_NAME)); Map importerProps = null; - HashMap modifiedProps = new HashMap<>(); + Map modifiedProps = new HashMap<>(); boolean changed = false; for(Version version : versions){ Map currentProps = version.getVersionProperties(); @@ -322,7 +322,7 @@ private HashMap checkInternalOverrides(HashMap p } } } - HashMap returnProps = new HashMap<>(propertiesIn); + Map returnProps = new HashMap<>(propertiesIn); if(importerProps!=null) { Collection widgets = getAllAvailableProperties(nodeRef); // copy all new props which are untouched @@ -344,8 +344,8 @@ private HashMap checkInternalOverrides(HashMap p /** * Return all props that have a different value inside the "diff" map */ - private HashMap getPropDiffs(Map base, Map diff) { - HashMap diffs = new HashMap<>(); + private Map getPropDiffs(Map base, Map diff) { + Map diffs = new HashMap<>(); //diffs.putAll(getPropDiffsOneWay(base,diff)); //diffs.putAll(getPropDiffsOneWay(diff,base)); for(Map.Entry entry : diff.entrySet()){ @@ -359,7 +359,7 @@ private HashMap getPropDiffs(Map base, Map } @Override - public NodeRef find(HashMap properties) throws Exception { + public NodeRef find(Map properties) throws Exception { CMISSearchHelper.CMISSearchData data = new CMISSearchHelper.CMISSearchData(); // this uses SOLR and is not synchronized! // data.inTree = primaryFolder.getId(); @@ -429,4 +429,4 @@ public static List filterCMISResult(List result, NodeRef prima }).collect(Collectors.toList()); } -} \ No newline at end of file +} diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/bulk/BulkServiceInterceptorInterface.java b/Backend/services/core/src/main/java/org/edu_sharing/service/bulk/BulkServiceInterceptorInterface.java index aa7a6b8ac5..226a5d7ce8 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/bulk/BulkServiceInterceptorInterface.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/bulk/BulkServiceInterceptorInterface.java @@ -3,13 +3,14 @@ import org.alfresco.service.cmr.repository.NodeRef; import java.util.HashMap; +import java.util.Map; public interface BulkServiceInterceptorInterface { /** * Preprocess properties before they get stored and post-processed by the bulk service */ - default HashMap preprocessProperties(HashMap properties) { + default Map preprocessProperties(Map properties) { return properties; } @@ -17,5 +18,5 @@ default HashMap preprocessProperties(HashMap pro * Called after the node has been created * Useful to apply additional permissions or changes to the node itself */ - default void onNodeCreated(NodeRef nodeRef, HashMap properties) {} + default void onNodeCreated(NodeRef nodeRef, Map properties) {} } diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/bulk/BulkServiceInterceptorSKOSToLocal.java b/Backend/services/core/src/main/java/org/edu_sharing/service/bulk/BulkServiceInterceptorSKOSToLocal.java index 0f59d33443..f583a686a4 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/bulk/BulkServiceInterceptorSKOSToLocal.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/bulk/BulkServiceInterceptorSKOSToLocal.java @@ -21,7 +21,7 @@ public class BulkServiceInterceptorSKOSToLocal implements BulkServiceInterceptor /** * Preprocess properties before they get stored and post-processed by the bulk service */ - public HashMap preprocessProperties(HashMap properties) { + public Map preprocessProperties(Map properties) { String mdsId = (String) properties.getOrDefault(CCConstants.CM_PROP_METADATASET_EDU_METADATASET, CCConstants.metadatasetdefault_id); try { MetadataSet mds = MetadataHelper.getMetadataset(ApplicationInfoList.getHomeRepository(), mdsId); @@ -48,7 +48,7 @@ public HashMap preprocessProperties(HashMap prop return properties; } - protected List getPropertyValue(HashMap properties, String key){ + protected List getPropertyValue(Map properties, String key){ Object values = properties.get(key); if(values != null) { if (values instanceof String) { diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/collection/CollectionServiceImpl.java b/Backend/services/core/src/main/java/org/edu_sharing/service/collection/CollectionServiceImpl.java index 92354e3a91..fb7c7216bf 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/collection/CollectionServiceImpl.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/collection/CollectionServiceImpl.java @@ -98,7 +98,7 @@ public static CollectionService build(String appId) { BehaviourFilter policyBehaviourFilter; - HashMap authInfo; + Map authInfo; SearchService searchService; NodeService nodeService; @@ -128,7 +128,7 @@ public CollectionServiceImpl(String appId, String pattern, String path) { || (guestUn != null && guestUn.equals(AuthenticationUtil.getFullyAuthenticatedUser()) )) { logger.debug("starting in runas user mode"); - this.authInfo = new HashMap(); + this.authInfo = new HashMap<>(); this.authInfo.put(CCConstants.AUTH_USERNAME, AuthenticationUtil.getRunAsUser()); } else { this.authInfo = this.authTool.validateAuthentication(Context.getCurrentInstance().getCurrentInstance().getRequest().getSession()); @@ -210,9 +210,9 @@ private String addToCollection(String collectionId, String refNodeId, boolean al } //NodeRef child = nodeService.getChild(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, collectionId, CCConstants.CCM_TYPE_IO, CCConstants.CCM_PROP_IO_ORIGINAL, originalNodeId); if(!allowDuplicate) { - List child = CMISSearchHelper.fetchNodesByTypeAndFilters(CCConstants.CCM_TYPE_IO, new HashMap() {{ - put(CCConstants.CCM_PROP_IO_ORIGINAL, originalNodeId); - }}, + List child = CMISSearchHelper.fetchNodesByTypeAndFilters(CCConstants.CCM_TYPE_IO, new HashMap<>() {{ + put(CCConstants.CCM_PROP_IO_ORIGINAL, originalNodeId); + }}, CMISSearchHelper.CMISSearchData.builder().inFolder(collectionId).build() ); if (!child.isEmpty()) { @@ -363,7 +363,7 @@ public void proposeForCollection(String collectionId, String originalNodeId, Str if (getChildrenProposal(collectionId).stream().anyMatch((assoc) -> assoc.getTargetRef().equals(nodeRef))) { throw new DuplicateNodeException("Node id " + nodeRef.getId() + " is already proposed for this collection"); } - HashMap props = new HashMap<>(); + Map props = new HashMap<>(); props.put(CCConstants.CM_NAME, NodeServiceHelper.getProperty(nodeRef, CCConstants.CM_NAME)); props.put(CCConstants.CCM_PROP_COLLECTION_PROPOSAL_TARGET, new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, finalId)); props.put(CCConstants.CCM_PROP_COLLECTION_PROPOSAL_STATUS, CCConstants.PROPOSAL_STATUS.PENDING); @@ -447,7 +447,7 @@ public Collection doWork() throws Exception { parentIdLocal = getHomePath(); } - HashMap props = asProps(collection); + Map props = asProps(collection); try { new DuplicateFinder().transformToSafeName(client.getChildren(parentIdLocal), props); } catch (Throwable e) { @@ -511,7 +511,7 @@ public void move(String toCollection, String toMove) { String parent = client.getParents(toMove, true).keySet().iterator().next(); client.moveNode(toCollection, CCConstants.CM_ASSOC_FOLDER_CONTAINS, toMove); - HashMap assocNode = client.getAssocNode(toMove, CCConstants.CM_ASSOC_ORIGINAL); + Map> assocNode = client.getAssocNode(toMove, CCConstants.CM_ASSOC_ORIGINAL); String originalNodeId = (String) assocNode.entrySet().iterator().next().getValue().get(CCConstants.SYS_PROP_NODE_UID); /** @@ -531,7 +531,7 @@ public void move(String toCollection, String toMove) { /** * handle level0 */ - HashMap properties = client.getProperties(toMove); + Map properties = client.getProperties(toMove); if (Boolean.parseBoolean((String) properties.get(CCConstants.CCM_PROP_MAP_COLLECTIONLEVEL0))) { if (Arrays.asList(client.getAspects(toCollection)).contains(CCConstants.CCM_ASPECT_COLLECTION)) { client.setProperty(toMove, CCConstants.CCM_PROP_MAP_COLLECTIONLEVEL0, "false"); @@ -605,7 +605,7 @@ public void removeFromCollection(String collectionId, String nodeId) { @Override public void update(Collection collection) { - HashMap props = asProps(collection); + Map props = asProps(collection); props.remove(CCConstants.CCM_PROP_MAP_COLLECTIONLEVEL0); client.updateNode(collection.getNodeId(), props); } @@ -623,8 +623,8 @@ public void updateAndSetScope(Collection collection) throws Exception { } } - public HashMap asProps(Collection collection) { - HashMap props = new HashMap(); + public Map asProps(Collection collection) { + Map props = new HashMap<>(); if (collection.getNodeId() != null) { props.put(CCConstants.SYS_PROP_NODE_UID, collection.getNodeId()); } @@ -647,7 +647,7 @@ public HashMap asProps(Collection collection) { return props; } - public Collection asCollection(HashMap props) { + public Collection asCollection(Map props) { Collection collection = new Collection(); collection.setNodeId((String) props.get(CCConstants.SYS_PROP_NODE_UID)); @@ -699,7 +699,7 @@ protected void addCollectionCountProperties(NodeRef nodeRef, Collection collecti @Override public Collection get(org.edu_sharing.service.model.NodeRef nodeRef, boolean fetchCounts) { try { - HashMap props = nodeRef.getProperties() == null ? nodeService.getProperties(nodeRef.getStoreProtocol(),nodeRef.getStoreId(),nodeRef.getNodeId()) : nodeRef.getProperties(); + Map props = nodeRef.getProperties() == null ? nodeService.getProperties(nodeRef.getStoreProtocol(),nodeRef.getStoreId(),nodeRef.getNodeId()) : nodeRef.getProperties(); throwIfNotACollection(nodeRef.getStoreProtocol(),nodeRef.getStoreId(),nodeRef.getNodeId()); Collection collection = asCollection(props); @@ -858,7 +858,7 @@ public List getChildren(String parentId, String scope, SortDefinition s return returnVal; } else { List children = nodeService.getChildrenChildAssociationRefAssoc(parentId, null, filter, sortDefinition); - List returnVal = new ArrayList(); + List returnVal = new ArrayList<>(); for (ChildAssociationRef child : children) { returnVal.add(child.getChildRef()); } @@ -997,7 +997,7 @@ public void setPinned(String[] collections) { throwIfNotACollection(StoreRef.PROTOCOL_WORKSPACE, StoreRef.STORE_REF_WORKSPACE_SPACESSTORE.getIdentifier(), collection); nodeService.addAspect(collection, CCConstants.CCM_ASPECT_COLLECTION_PINNED); - HashMap props = new HashMap(); + Map props = new HashMap<>(); props.put(CCConstants.CCM_PROP_COLLECTION_PINNED_STATUS, true); props.put(CCConstants.CCM_PROP_COLLECTION_PINNED_ORDER, order); nodeService.updateNodeNative(collection, props); @@ -1034,7 +1034,7 @@ public void setOrder(String parentId, String[] nodes) { List refs=getChildren(parentId, null, new SortDefinition(),Arrays.asList("files", "folders")); AtomicInteger order=new AtomicInteger(0); - HashMap collectionProps = new HashMap<>(); + Map collectionProps = new HashMap<>(); nodeService.updateNodeNative(parentId, collectionProps); if(nodes == null) @@ -1047,7 +1047,7 @@ public void setOrder(String parentId, String[] nodes) { throw new IllegalArgumentException("Node id " + node + " is not a children of the collection " + parentId); nodeService.addAspect(node, CCConstants.CCM_ASPECT_COLLECTION_ORDERED); - HashMap props = new HashMap<>(); + Map props = new HashMap<>(); props.put(CCConstants.CCM_PROP_COLLECTION_ORDERED_POSITION, order.get()); nodeService.updateNodeNative(node, props); policyBehaviourFilter.enableBehaviour(ref, ContentModel.ASPECT_AUDITABLE); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/comment/CommentServiceImpl.java b/Backend/services/core/src/main/java/org/edu_sharing/service/comment/CommentServiceImpl.java index 949928b820..fc07d525a2 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/comment/CommentServiceImpl.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/comment/CommentServiceImpl.java @@ -1,9 +1,6 @@ package org.edu_sharing.service.comment; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; +import java.util.*; import org.alfresco.repo.security.authentication.AuthenticationUtil; import org.alfresco.service.cmr.repository.ChildAssociationRef; @@ -38,7 +35,7 @@ public CommentServiceImpl() { @Override public String addComment(String node,String commentReference, String comment) throws Exception { ToolPermissionHelper.throwIfToolpermissionMissing(CCConstants.CCM_VALUE_TOOLPERMISSION_COMMENT_WRITE); - HashMap props = new HashMap<>(); + Map props = new HashMap<>(); if(StringUtils.isNotBlank(commentReference)) { props.put(CCConstants.CCM_PROP_COMMENT_REPLY,new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, commentReference)); } @@ -68,7 +65,7 @@ public List getComments(String node) { @Override public void editComment(String commentId, String comment) { throwIfNoComment(commentId); - HashMap props = new HashMap(); + Map props = new HashMap<>(); props.put(CCConstants.CCM_PROP_COMMENT_CONTENT,comment); NodeRef replyTo = new NodeRef(nodeService.getProperty(StoreRef.PROTOCOL_WORKSPACE, StoreRef.STORE_REF_WORKSPACE_SPACESSTORE.getIdentifier(), commentId, CCConstants.CCM_PROP_COMMENT_REPLY)); nodeService.updateNodeNative(commentId, props); @@ -99,7 +96,7 @@ public void deleteComment(String commentId) { private void notify(String node, String comment, String commentReference, Status status) { String nodeType = null; List aspects; - HashMap nodeProps; + Map nodeProps; try { nodeType = nodeService.getType(StoreRef.PROTOCOL_WORKSPACE, StoreRef.STORE_REF_WORKSPACE_SPACESSTORE.getIdentifier(), node); aspects = Arrays.asList(nodeService.getAspects(StoreRef.PROTOCOL_WORKSPACE, StoreRef.STORE_REF_WORKSPACE_SPACESSTORE.getIdentifier(), node)); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/config/ConfigServiceImpl.java b/Backend/services/core/src/main/java/org/edu_sharing/service/config/ConfigServiceImpl.java index f791282bba..52558d95de 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/config/ConfigServiceImpl.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/config/ConfigServiceImpl.java @@ -5,6 +5,7 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; +import java.util.Map; import jakarta.xml.bind.JAXBContext; import jakarta.xml.bind.JAXBException; @@ -195,12 +196,12 @@ public DynamicConfig setDynamicValue(String key, boolean readPublic, JSONObject nodeId = child.getId(); }catch(Throwable t){ // does not exists -> we will create a new node - HashMap props=new HashMap<>(); + Map props=new HashMap<>(); props.put(CCConstants.CM_NAME,new String[]{key}); nodeId=nodeService.createNode(folder,CCConstants.CCM_TYPE_CONFIGOBJECT,props); } - HashMap props=new HashMap<>(); + Map props=new HashMap<>(); props.put(CCConstants.CCM_PROP_CONFIGOBJECT_VALUE,object.toString()); nodeService.updateNodeNative(nodeId,props); DynamicConfig result=new DynamicConfig(); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/connector/ConnectorServiceFactory.java b/Backend/services/core/src/main/java/org/edu_sharing/service/connector/ConnectorServiceFactory.java index 4f7c000b8a..9e29930ad7 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/connector/ConnectorServiceFactory.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/connector/ConnectorServiceFactory.java @@ -36,7 +36,7 @@ public static ConnectorList getConnectorList(ToolPermissionService toolPermissio ConnectorList filteredList = new ConnectorList(); - List filteredConnectors = new ArrayList(); + List filteredConnectors = new ArrayList<>(); for(Connector connector : getConnectorService().getConnectorList().getConnectors()){ if(toolPermissionService.hasToolPermissionForConnector(connector.getId())){ filteredConnectors.add(connector); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/editlock/EditLockServiceImpl.java b/Backend/services/core/src/main/java/org/edu_sharing/service/editlock/EditLockServiceImpl.java index 704d2ceca6..89a7b4f71c 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/editlock/EditLockServiceImpl.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/editlock/EditLockServiceImpl.java @@ -139,7 +139,7 @@ public void unlockBySession(String sessionId) { logger.debug("clearing session for sessionId:" + sessionId); synchronized (EditLockCache.cache) { - List toRemove = new ArrayList(); + List toRemove = new ArrayList<>(); for (NodeRef nodeRef : EditLockCache.getKeys()) { LockBy lockBy = EditLockCache.get(nodeRef); if (sessionId.equals(lockBy.getSessionId())) { diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/feedback/FeedbackServiceImpl.java b/Backend/services/core/src/main/java/org/edu_sharing/service/feedback/FeedbackServiceImpl.java index 08d4322b73..515da3581e 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/feedback/FeedbackServiceImpl.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/feedback/FeedbackServiceImpl.java @@ -102,7 +102,7 @@ private FeedbackData toFeedback(NodeRef nodeRef) throws Throwable { nodeRef.getStoreRef().getProtocol(), nodeRef.getStoreRef().getIdentifier(), nodeRef.getId(), CCConstants.CCM_PROP_MATERIAL_FEEDBACK_DATA ); - HashMap> mapData = new Gson().fromJson(data, new TypeToken() { + Map> mapData = new Gson().fromJson(data, new TypeToken>() { }.getType()); feedbackData.setData(mapData); return feedbackData; @@ -126,7 +126,7 @@ public FeedbackResult addFeedback( try { // will reset after runAs automatically AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.SYSTEM_USER_NAME); - HashMap props = new HashMap<>(); + Map props = new HashMap<>(); props.put( CCConstants.CCM_PROP_MATERIAL_FEEDBACK_AUTHORITY, getHashedAuthority(userId) diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/feedback/model/FeedbackData.java b/Backend/services/core/src/main/java/org/edu_sharing/service/feedback/model/FeedbackData.java index c99ac94397..64fb87f01e 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/feedback/model/FeedbackData.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/feedback/model/FeedbackData.java @@ -31,7 +31,7 @@ public Map> getData() { return data; } - public void setData(HashMap> data) { + public void setData(Map> data) { this.data = data; } diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/foldertemplates/FolderTemplatesImpl.java b/Backend/services/core/src/main/java/org/edu_sharing/service/foldertemplates/FolderTemplatesImpl.java index 34aab39d57..49c682beb8 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/foldertemplates/FolderTemplatesImpl.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/foldertemplates/FolderTemplatesImpl.java @@ -7,6 +7,7 @@ import java.net.URL; import java.util.HashMap; import java.util.List; +import java.util.Map; import java.util.Properties; import javax.xml.parsers.DocumentBuilder; @@ -42,7 +43,7 @@ public class FolderTemplatesImpl implements FolderTemplates { String templatePropertiesFile; Properties properties; Logger logger = Logger.getLogger(FolderTemplatesImpl.class); - HashMap subGroupList = new HashMap(); + Map subGroupList = new HashMap<>(); LoggingErrorHandler loggingErrorHandler = new LoggingErrorHandler(); @@ -181,7 +182,7 @@ public void setTemplate(String templateName, String eduGroupname, String folder) this.repoClient.getAuthenticationInfo()); String Sysf = uit.getEdu_SharingTemplateFolder(); - HashMap> templatelist = this.repoClient.getChildren(Sysf); + Map> templatelist = this.repoClient.getChildren(Sysf); if (templatelist.isEmpty()) { logger.fatal("no Templates found"); loggingErrorHandler.getMessage().add("no Templates found"); @@ -191,7 +192,7 @@ public void setTemplate(String templateName, String eduGroupname, String folder) String fileformat = ""; String fileNodeId = ""; - for (HashMap tl : templatelist.values()) { + for (Map tl : templatelist.values()) { filename = (String) tl.get(CCConstants.CM_NAME); fileformat = (String) tl.get(CCConstants.LOM_PROP_TECHNICAL_FORMAT); @@ -215,14 +216,14 @@ public void setTemplate(String templateName, String eduGroupname, String folder) } // get SubGroups - HashMap> subList = this.repoClient.getChildren(groupNodeId); + Map> subList = this.repoClient.getChildren(groupNodeId); if (subList.isEmpty()) { logger.fatal("no Subgroups for eduGroup found"); this.loggingErrorHandler.getMessage().add("no Subgroups for eduGroup found"); return; } - for (HashMap gd : subList.values()) { + for (Map gd : subList.values()) { String nodeType = (String) gd.get("NodeType"); if (nodeType.equals("{http://www.alfresco.org/model/content/1.0}authorityContainer")) { @@ -363,13 +364,13 @@ private void createFolder(Node node, String parentid) { System.out.println(node.getNodeName() + " " + fname); logger.info(node.getNodeName() + " " + fname); - HashMap eduProps = new HashMap(); + Map eduProps = new HashMap<>(); String name = fname; eduProps.put(CCConstants.CM_NAME, name); eduProps.put(CCConstants.CM_PROP_C_TITLE, name); uid = ""; try { - HashMap d = this.repoClient.getChild(parentid, CCConstants.CCM_TYPE_MAP, + Map d = this.repoClient.getChild(parentid, CCConstants.CCM_TYPE_MAP, CCConstants.CM_NAME, name); if (d != null) { diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/foldertemplates/LoggingErrorHandler.java b/Backend/services/core/src/main/java/org/edu_sharing/service/foldertemplates/LoggingErrorHandler.java index a0b6ace93c..ba91916e15 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/foldertemplates/LoggingErrorHandler.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/foldertemplates/LoggingErrorHandler.java @@ -10,7 +10,7 @@ public class LoggingErrorHandler implements ErrorHandler { private boolean isValid = true; - List message = new ArrayList(); + List message = new ArrayList<>(); public boolean isValid() { return this.isValid; @@ -45,4 +45,4 @@ public void fatalError(SAXParseException exc) throws SAXParseException { public List getMessage() { return message; } -} \ No newline at end of file +} diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/foldertemplates/TmplGroup.java b/Backend/services/core/src/main/java/org/edu_sharing/service/foldertemplates/TmplGroup.java index 5112cbec85..b70ca9923d 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/foldertemplates/TmplGroup.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/foldertemplates/TmplGroup.java @@ -9,7 +9,7 @@ public class TmplGroup { - List GroupList = new ArrayList(); + List GroupList = new ArrayList<>(); public TmplGroup (){}; diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/license/AssignedLicenseDAOSubTypeImpl.java b/Backend/services/core/src/main/java/org/edu_sharing/service/license/AssignedLicenseDAOSubTypeImpl.java index 8cecd404e4..d321037cfe 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/license/AssignedLicenseDAOSubTypeImpl.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/license/AssignedLicenseDAOSubTypeImpl.java @@ -19,17 +19,17 @@ public class AssignedLicenseDAOSubTypeImpl implements AssignedLicenseDAO { public List getAssignedLicenses(String repositoryId, String nodeId) throws Throwable { //remote repositories need a valid homeAuth to make the AuthByApp - HashMap homeAuthInfo = null; + Map homeAuthInfo = null; if(!ApplicationInfoList.getRepositoryInfoById(repositoryId).ishomeNode()){ homeAuthInfo = new AuthenticationToolAPI().getAuthentication(Context.getCurrentInstance().getRequest().getSession()); } MCAlfrescoBaseClient mcAlfrescoBaseClient = (MCAlfrescoBaseClient) RepoFactory.getInstance(repositoryId, homeAuthInfo); - HashMap> assignedLicenses = mcAlfrescoBaseClient.getChildrenByType(nodeId, + Map> assignedLicenses = mcAlfrescoBaseClient.getChildrenByType(nodeId, CCConstants.CCM_TYPE_ASSIGNED_LICENSE); - List licenses = new ArrayList(); - for (Map.Entry> entryLicense : assignedLicenses.entrySet()) { + List licenses = new ArrayList<>(); + for (Map.Entry> entryLicense : assignedLicenses.entrySet()) { String assignedLicenseNodeId = entryLicense.getKey(); String[] assignedLicenseLicense = new String[] { (String) entryLicense.getValue().get( CCConstants.CCM_PROP_ASSIGNED_LICENSE_ASSIGNEDLICENSE) }; @@ -44,22 +44,22 @@ public List getAssignedLicenses(String repositoryId, String nod public void setAssignedLicenses(String repositoryId, String nodeId, List assignedLicenses) throws Throwable { //remote repositories need a valid homeAuth to make the AuthByApp - HashMap homeAuthInfo = null; + Map homeAuthInfo = null; if(repositoryId != null && !ApplicationInfoList.getRepositoryInfoById(repositoryId).ishomeNode()){ homeAuthInfo = new AuthenticationToolAPI().getAuthentication(Context.getCurrentInstance().getRequest().getSession()); } MCAlfrescoBaseClient mcAlfrescoBaseClient = (MCAlfrescoBaseClient) RepoFactory.getInstance(repositoryId,homeAuthInfo); - ArrayList newAuthorities = new ArrayList(); + ArrayList newAuthorities = new ArrayList<>(); for (AssignedLicense assignedLicense : assignedLicenses) { newAuthorities.add(assignedLicense.getAuthority()); } // remove old licenses for authorities that are in // newAuthorities List - HashMap> assignedLicensesHashMap = mcAlfrescoBaseClient.getChildrenByType(nodeId, + Map> assignedLicensesHashMap = mcAlfrescoBaseClient.getChildrenByType(nodeId, CCConstants.CCM_TYPE_ASSIGNED_LICENSE); - for (Map.Entry> assignedLicenseEntry : assignedLicensesHashMap.entrySet()) { + for (Map.Entry> assignedLicenseEntry : assignedLicensesHashMap.entrySet()) { String oldAuthority = (String) assignedLicenseEntry.getValue().get(CCConstants.CCM_PROP_ASSIGNED_LICENSE_AUTHORITY); if (newAuthorities.contains(oldAuthority)) { mcAlfrescoBaseClient.removeChild(nodeId, assignedLicenseEntry.getKey(), CCConstants.CCM_ASSOC_ASSIGNEDLICENSES); @@ -71,7 +71,7 @@ public void setAssignedLicenses(String repositoryId, String nodeId, List properties = new HashMap(); + Map properties = new HashMap<>(); properties.put(CCConstants.CCM_PROP_ASSIGNED_LICENSE_AUTHORITY, assignedLicense.getAuthority()); properties.put(CCConstants.CCM_PROP_ASSIGNED_LICENSE_ASSIGNEDLICENSE, assignedLicense.getLicenses()[0]); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/lifecycle/PersonLifecycleService.java b/Backend/services/core/src/main/java/org/edu_sharing/service/lifecycle/PersonLifecycleService.java index 95e06ab9c7..6addb92ba0 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/lifecycle/PersonLifecycleService.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/lifecycle/PersonLifecycleService.java @@ -474,7 +474,7 @@ private void handleSharedFiles(NodeRef personNodeRef, PersonDeleteOptions option } else{ - List allFiles = new ArrayList(); + List allFiles = new ArrayList<>(); shared.forEach( (childAssociationRef -> { allFiles.addAll(NodeServiceFactory.getLocalService().getChildrenRecursive(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, childAssociationRef.getChildRef().getId(), null, RecurseMode.Folders)); @@ -679,14 +679,14 @@ private NodeRef getOrCreateTargetFolder(NodeRef personNodeRef, PersonDeleteOptio NodeRef deleted = getDeletedFolderForOrg(options, scope); String userFolder = NodeServiceFactory.getLocalService().findNodeByName(deleted.getId(), username); if (userFolder == null) { - HashMap props = new HashMap<>(); + Map props = new HashMap<>(); props.put(CCConstants.CM_NAME, username); userFolder = NodeServiceFactory.getLocalService().createNodeBasic(deleted.getId(), CCConstants.CCM_TYPE_MAP, props); } if (subfolder == null) return new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, userFolder); - HashMap props = new HashMap<>(); + Map props = new HashMap<>(); props.put(CCConstants.CM_NAME, subfolder); return new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, NodeServiceFactory.getLocalService().createNodeBasic(userFolder, CCConstants.CCM_TYPE_MAP, props)); }catch(Exception e){ @@ -716,7 +716,7 @@ private NodeRef getDeletedFolderForOrg(PersonDeleteOptions options, String scope String deletedHome= NodeServiceFactory.getLocalService().findNodeByName(orgHome.getId(),DELETED_PERSONS_FOLDER); if(deletedHome==null) { - HashMap props=new HashMap<>(); + Map props=new HashMap<>(); props.put(CCConstants.CM_NAME,DELETED_PERSONS_FOLDER); deletedHome=NodeServiceFactory.getLocalService().createNodeBasic(orgHome.getId(), CCConstants.CCM_TYPE_MAP, props); NodeRef deletedRef = new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, deletedHome); @@ -790,7 +790,7 @@ private void updateMetadataCreator(NodeRef nodeRef, String oldOwner, PersonDelet if(creator instanceof ArrayList){ creators= (ArrayList) creator; }else{ - creators = new ArrayList(); + creators = new ArrayList<>(); creators.add((String)creator); } if(creators.size()>0) { @@ -800,8 +800,8 @@ private void updateMetadataCreator(NodeRef nodeRef, String oldOwner, PersonDelet String lastName = (String) nodeService.getProperty(authority, QName.createQName(CCConstants.CM_PROP_PERSON_LASTNAME)); // filter all elements where current user is really attached creators= creators.stream().filter((c) -> { - HashMap vcard = VCardConverter. - getVCardHashMap(CCConstants.CCM_TYPE_IO, CCConstants.CCM_PROP_IO_REPL_METADATACONTRIBUTER_CREATOR, c); + Map vcard = VCardConverter. + getVCardMap(CCConstants.CCM_TYPE_IO, CCConstants.CCM_PROP_IO_REPL_METADATACONTRIBUTER_CREATOR, c); if (vcard != null && vcard.size() > 0) { if (Objects.equals(firstName, vcard.get(CCConstants.CCM_PROP_IO_REPL_METADATACONTRIBUTER_CREATOR+CCConstants.VCARD_GIVENNAME)) && Objects.equals(lastName, vcard.get(CCConstants.CCM_PROP_IO_REPL_METADATACONTRIBUTER_CREATOR+CCConstants.VCARD_SURNAME))) { @@ -837,15 +837,15 @@ public void removeContributer(NodeRef nodeRef, String username){ QName qnameMetadata = QName.createQName(CCConstants.CCM_PROP_IO_REPL_METADATACONTRIBUTER_CREATOR); List contributerAuthor = (List)nodeService.getProperty(nodeRef, qnameAuthor); List contributerMetadata = (List)nodeService.getProperty(nodeRef,qnameMetadata); - contributerAuthor.removeIf(author -> contains(VCardConverter.vcardToHashMap(author), firstName, lastName)); + contributerAuthor.removeIf(author -> contains(VCardConverter.vcardToMap(author), firstName, lastName)); nodeService.setProperty(nodeRef, qnameAuthor, (ArrayList)contributerAuthor); - contributerMetadata.removeIf(metadataContributer -> contains(VCardConverter.vcardToHashMap(metadataContributer), firstName, lastName)); + contributerMetadata.removeIf(metadataContributer -> contains(VCardConverter.vcardToMap(metadataContributer), firstName, lastName)); nodeService.setProperty(nodeRef, qnameMetadata, (ArrayList)contributerMetadata); } - private boolean contains(ArrayList> vcardList, String firstName, String lastName) { + private boolean contains(ArrayList> vcardList, String firstName, String lastName) { if(vcardList != null && vcardList.size() > 0) { Map vcard = vcardList.iterator().next(); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/lti13/LTIJWTUtil.java b/Backend/services/core/src/main/java/org/edu_sharing/service/lti13/LTIJWTUtil.java index 1da4620280..bd5edf1610 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/lti13/LTIJWTUtil.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/lti13/LTIJWTUtil.java @@ -276,13 +276,13 @@ private List> generateContentItems(Node[] nodes){ deepLink.put(LTIConstants.DEEP_LINK_URL, ApplicationInfoList.getHomeRepository().getClientBaseUrl() + "/rest/lti/v13/"+LTIConstants.LTI_TOOL_REDIRECTURL_PATH+"/"+node.getRef().getId()); //@TODO must custom part always be send? is only need when platform is also a tool that has customcontent option - HashMap custom = new HashMap<>(); + Map custom = new HashMap<>(); custom.put("nodeId",node.getRef().getId()); custom.put("repositoryId",node.getRef().getRepo()); deepLink.put("custom",custom); try { - HashMap thumbnail = new HashMap<>(); + Map thumbnail = new HashMap<>(); //thumbnail.put("url",node.getPreview().getUrl()); thumbnail.put("url",new MimeTypesV2().getIcon(node.getType(),NodeServiceFactory.getLocalService().getProperties(StoreRef.PROTOCOL_WORKSPACE,StoreRef.STORE_REF_WORKSPACE_SPACESSTORE.getIdentifier() ,node.getRef().getId()) ,node.getAspects())); thumbnail.put("width",""+node.getPreview().getWidth()); @@ -401,7 +401,7 @@ public Jws validateForCustomContent(String jwt, boolean validateNodeId) throw new ValidationException("wrong nodeId"); } - HashMap tokenData = new Gson().fromJson(ApiTool.decrpt(token), HashMap.class); + Map tokenData = new Gson().fromJson(ApiTool.decrpt(token), HashMap.class); if(!appId.equals(tokenData.get(LTIPlatformConstants.CUSTOM_CLAIM_APP_ID))){ throw new ValidationException("mismatch appId"); } @@ -498,7 +498,7 @@ public Jws validateForInitialToolSession(String jwt) throws ValidationEx * */ //validate that token appId (tool) is the same as the session appId (tool) - HashMap tokenData = new Gson().fromJson(ApiTool.decrpt(token), HashMap.class); + Map tokenData = new Gson().fromJson(ApiTool.decrpt(token), HashMap.class); if(!sessionObject.getAppId().equals(tokenData.get(LTIPlatformConstants.CUSTOM_CLAIM_APP_ID))){ throw new ValidationException("mismatch appId"); } diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/lti13/RepoTools.java b/Backend/services/core/src/main/java/org/edu_sharing/service/lti13/RepoTools.java index 2304a632f9..caded07852 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/lti13/RepoTools.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/lti13/RepoTools.java @@ -11,6 +11,7 @@ import jakarta.servlet.http.HttpServletRequest; import java.util.HashMap; +import java.util.Map; public class RepoTools { @@ -71,11 +72,11 @@ public String getAppId(String iss, String clientId, String ltiDeploymentId){ return applicationId; } - public static String authenticate(HttpServletRequest req, HashMap ssoMap){ + public static String authenticate(HttpServletRequest req, Map ssoMap){ ApplicationContext eduApplicationContext = org.edu_sharing.spring.ApplicationContextFactory.getApplicationContext(); SSOAuthorityMapper ssoMapper = (SSOAuthorityMapper)eduApplicationContext.getBean("ssoAuthorityMapper"); AuthenticationToolAPI authTool = new AuthenticationToolAPI(); - HashMap validAuthInfo = authTool.validateAuthentication(req.getSession()); + Map validAuthInfo = authTool.validateAuthentication(req.getSession()); String userName = ssoMap.get(ssoMapper.getSSOUsernameProp()); if (validAuthInfo != null ) { @@ -104,10 +105,10 @@ public static String authenticate(HttpServletRequest req, HashMap return userName; } - public static HashMap mapToSSOMap(String username, String firstName, String lastName, String email){ + public static Map mapToSSOMap(String username, String firstName, String lastName, String email){ ApplicationContext eduApplicationContext = org.edu_sharing.spring.ApplicationContextFactory.getApplicationContext(); SSOAuthorityMapper ssoMapper = (SSOAuthorityMapper)eduApplicationContext.getBean("ssoAuthorityMapper"); - HashMap result = new HashMap<>(); + Map result = new HashMap<>(); if(firstName != null) result.put(ssoMapper.getUserAttribute(CCConstants.CM_PROP_PERSON_FIRSTNAME),firstName); if(username != null) result.put(ssoMapper.getUserAttribute(CCConstants.CM_PROP_PERSON_USERNAME),username); if(lastName != null) result.put(ssoMapper.getUserAttribute(CCConstants.CM_PROP_PERSON_LASTNAME),lastName); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/lti13/registration/RegistrationService.java b/Backend/services/core/src/main/java/org/edu_sharing/service/lti13/registration/RegistrationService.java index ec37cfba68..c8efbd7e28 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/lti13/registration/RegistrationService.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/lti13/registration/RegistrationService.java @@ -276,7 +276,7 @@ public void registerPlatform(String platformId, String keysetUrl, String keyId, String authTokenUrl, DynamicRegistrationToken token) throws Exception{ - HashMap properties = new HashMap<>(); + Map properties = new HashMap<>(); String appId = new RepoTools().getAppId(platformId,clientId,deploymentId); properties.put(ApplicationInfo.KEY_APPID, appId); properties.put(ApplicationInfo.KEY_TYPE, ApplicationInfo.TYPE_LTIPLATFORM); @@ -399,7 +399,7 @@ public ApplicationInfo ltiDynamicToolRegistration(JSONObject registrationPayload public ApplicationInfo registerTool(String clientId, String initiateLoginUri, String jwksuri, String targetLinkUri, String redirectUris, String logoUri, String customParameters, String description, String clientName, String targetLinkUriDeepLink, String toolUrl) throws Exception { - HashMap properties = new HashMap<>(); + Map properties = new HashMap<>(); /** * fallback to required redrect Urls diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/mediacenter/MediacenterServiceImpl.java b/Backend/services/core/src/main/java/org/edu_sharing/service/mediacenter/MediacenterServiceImpl.java index 5e70586ced..6e3554393d 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/mediacenter/MediacenterServiceImpl.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/mediacenter/MediacenterServiceImpl.java @@ -183,17 +183,17 @@ public String createMediacenter(String id, String displayName, String postalCode */ NodeRef authorityNodeRef = authorityService.getAuthorityNodeRef(alfAuthorityName); - Map groupExtProps = new HashMap(); + Map groupExtProps = new HashMap<>(); groupExtProps.put(QName.createQName(CCConstants.CCM_PROP_GROUPEXTENSION_GROUPTYPE), AuthorityService.MEDIA_CENTER_GROUP_TYPE); nodeService.addAspect(authorityNodeRef, QName.createQName(CCConstants.CCM_ASPECT_GROUPEXTENSION), groupExtProps); - Map groupAddressProps = new HashMap(); + Map groupAddressProps = new HashMap<>(); if (postalCode != null) groupAddressProps.put(QName.createQName(CCConstants.CCM_PROP_ADDRESS_POSTALCODE), postalCode); if (city != null) groupAddressProps.put(QName.createQName(CCConstants.CCM_PROP_ADDRESS_CITY), city); nodeService.addAspect(authorityNodeRef, QName.createQName(CCConstants.CCM_ASPECT_ADDRESS), groupAddressProps); - Map groupMZProps = new HashMap(); + Map groupMZProps = new HashMap<>(); groupMZProps.put(QName.createQName(CCConstants.CCM_PROP_MEDIACENTER_ID), id); if (city != null) groupMZProps.put(QName.createQName(CCConstants.CCM_PROP_ADDRESS_CITY), city); nodeService.addAspect(authorityNodeRef, QName.createQName(CCConstants.CCM_ASPECT_MEDIACENTER), groupMZProps); @@ -306,7 +306,7 @@ public Integer doWork() throws Exception { if (rs == null || rs.length() < 1) { logger.error("no mediacenters found"); } else { - Map> existingMZsAndSchools = new HashMap>(); + Map> existingMZsAndSchools = new HashMap<>(); for (NodeRef mzNodeRef : rs.getNodeRefs()) { String authorityName = (String) nodeService.getProperty(mzNodeRef, ContentModel.PROP_AUTHORITY_NAME); String mzId = authorityName.replace("GROUP_MEDIA_CENTER_", ""); @@ -331,7 +331,7 @@ public Integer doWork() throws Exception { List schools = existingMZsAndSchools.get(mzId); if (schools == null) { - schools = new ArrayList(); + schools = new ArrayList<>(); } if (!schools.contains(schoolId)) { schools.add(schoolId); @@ -347,7 +347,7 @@ public Integer doWork() throws Exception { List newSchools = newMZsAndSchools.get(mzAndSchools.getKey()); if (newSchools == null) { logger.info("existing mz:" + mzAndSchools.getKey() + " has a null school list in new sheet"); - newSchools = new ArrayList(); + newSchools = new ArrayList<>(); } if (mzAndSchools.getValue() == null) { @@ -422,11 +422,11 @@ public Integer doWork() throws Exception { } Map> listToUniqueMap(List> records) { - Map> result = new HashMap>(); + Map> result = new HashMap<>(); for (List record : records) { if (!result.containsKey(record.get(0))) { - List list = new ArrayList(); + List list = new ArrayList<>(); list.add(record.get(1)); result.put(record.get(0), list); } else { @@ -625,10 +625,10 @@ public void manageNodeLicenses() { logger.error("no imported objects folder found"); return; } - HashMap importedNodes = new NodeHelper().getImportedNodes(impFolderId); + Map importedNodes = new NodeHelper().getImportedNodes(impFolderId); - HashMap> sodisMediacenterIdNodes = new HashMap<>(); + Map> sodisMediacenterIdNodes = new HashMap<>(); for (String mediacenterId : allMediacenterIds) { logger.info("cache provider mediacenter nodes mediacenterId:" + mediacenterId + " already cached:" + sodisMediacenterIdNodes.size()); List nodes = MediacenterLicenseProviderFactory.getMediacenterLicenseProvider().getNodes(mediacenterId); @@ -636,8 +636,8 @@ public void manageNodeLicenses() { } - HashMap> addToMediacenterList = new HashMap<>(); - HashMap> removeFromMediacenterList = new HashMap<>(); + Map> addToMediacenterList = new HashMap<>(); + Map> removeFromMediacenterList = new HashMap<>(); for (String mediacenterId : allMediacenterIds) { logger.info("collect differences for " + mediacenterId); @@ -664,7 +664,7 @@ public void manageNodeLicenses() { if (sodisLicensedNodes.contains(entry.getKey()) && (!hasConsumerPermission || !hasPublishPermission)) { List nodeRefs = addToMediacenterList.get(mediacenterName); if (nodeRefs == null) { - nodeRefs = new ArrayList(); + nodeRefs = new ArrayList<>(); addToMediacenterList.put(mediacenterName, nodeRefs); } nodeRefs.add(entry.getValue()); @@ -672,7 +672,7 @@ public void manageNodeLicenses() { && (hasConsumerPermission || hasPublishPermission)) { List nodeRefs = removeFromMediacenterList.get(mediacenterName); if (nodeRefs == null) { - nodeRefs = new ArrayList(); + nodeRefs = new ArrayList<>(); removeFromMediacenterList.put(mediacenterName, nodeRefs); } nodeRefs.add(entry.getValue()); @@ -868,7 +868,7 @@ private void fixMediacenterStatus(NodeRef nodeRef, String mediacenterGroupName, } private NodeRef getNodeRefByReplicationSourceId(String replicationSourceId){ - NodeRef nodeRef = getPersistentHandlerEdusharing().getNodeIfExists(new HashMap() { + NodeRef nodeRef = getPersistentHandlerEdusharing().getNodeIfExists(new HashMap<>() { { put(CCConstants.CCM_PROP_IO_REPLICATIONSOURCEID, replicationSourceId); }} @@ -876,19 +876,14 @@ private NodeRef getNodeRefByReplicationSourceId(String replicationSourceId){ if(nodeRef == null){ logger.info("creating dummy object for:"+replicationSourceId); - HashMap properties = new HashMap<>(); + Map properties = new HashMap<>(); properties.put(CCConstants.CM_NAME,replicationSourceId); properties.put(CCConstants.CCM_PROP_IO_REPLICATIONSOURCETIMESTAMP, "1900-01-01T00:00:00Z"); properties.put(CCConstants.CCM_PROP_IO_REPLICATIONSOURCEID,replicationSourceId); properties.put(CCConstants.CCM_PROP_IO_REPLICATIONSOURCE,MediacenterLicenseProviderFactory.getMediacenterLicenseProvider().getCatalogId()); properties.put(CCConstants.CCM_PROP_IO_TECHNICAL_STATE,"problem_notAvailable"); try { - String nodeId = getPersistentHandlerEdusharing().safe(new RecordHandlerInterfaceBase() { - @Override - public HashMap getProperties() { - return properties; - } - },null,MediacenterLicenseProviderFactory.getMediacenterLicenseProvider().getSet()); + String nodeId = getPersistentHandlerEdusharing().safe((RecordHandlerInterfaceBase) () -> properties,null,MediacenterLicenseProviderFactory.getMediacenterLicenseProvider().getSet()); if(nodeId != null){ nodeRef = new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE,nodeId); } diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/mime/MimeTypesV2.java b/Backend/services/core/src/main/java/org/edu_sharing/service/mime/MimeTypesV2.java index 5533f34802..e109862625 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/mime/MimeTypesV2.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/mime/MimeTypesV2.java @@ -21,8 +21,8 @@ public enum PathType{ } public static final String MIME_DIRECTORY="application/x-directory"; - private static HashMap extensionMimeMap; - private static HashMap lrtMimeMap; + private static Map extensionMimeMap; + private static Map lrtMimeMap; private final ApplicationInfo appInfo; private String theme; private final PathType pathType; @@ -318,7 +318,7 @@ private static boolean isLtiObject(List aspects) { return false; return aspects.contains(CCConstants.CCM_ASPECT_TOOL_OBJECT); } - public static HashMap getLrtMimeMap() { + public static Map getLrtMimeMap() { if (lrtMimeMap == null) { lrtMimeMap = new HashMap<>(); @@ -336,10 +336,10 @@ public static HashMap getLrtMimeMap() { } return lrtMimeMap; } -public static HashMap getExtensionMimeMap() { +public static Map getExtensionMimeMap() { if(extensionMimeMap == null){ - extensionMimeMap = new HashMap(); + extensionMimeMap = new HashMap<>(); extensionMimeMap.put("jpg", "image/jpeg"); extensionMimeMap.put("jpeg", "image/jpeg"); extensionMimeMap.put("png", "image/png"); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/model/NodeRef.java b/Backend/services/core/src/main/java/org/edu_sharing/service/model/NodeRef.java index c470f1650f..8a9dccc1ac 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/model/NodeRef.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/model/NodeRef.java @@ -29,44 +29,44 @@ interface Preview{ Boolean getIcon(); } - public String getRepositoryId(); + String getRepositoryId(); - public void setRepositoryId(String repositoryId); + void setRepositoryId(String repositoryId); - public String getStoreProtocol(); + String getStoreProtocol(); - public void setStoreProtocol(String storeProtocol); + void setStoreProtocol(String storeProtocol); - public String getStoreId(); + String getStoreId(); - public void setStoreId(String storeId); + void setStoreId(String storeId); - public String getNodeId(); + String getNodeId(); - public void setNodeId(String nodeId); + void setNodeId(String nodeId); - public HashMap getProperties(); + Map getProperties(); - public void setProperties(HashMap properties); + void setProperties(Map properties); - public void setPreview(Preview preview); + void setPreview(Preview preview); - public Preview getPreview(); + Preview getPreview(); - public Map getPermissions(); + Map getPermissions(); - public void setPermissions(Map permissions); + void setPermissions(Map permissions); public Boolean getPublic(); - public void setPublic(Boolean aPublic); + void setPublic(Boolean aPublic); void setAspects(List aspects); - public List getAspects(); + List getAspects(); - public void setUsedInCollections(List usedInCollections); + void setUsedInCollections(List usedInCollections); - public List getUsedInCollections(); + List getUsedInCollections(); } diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/model/NodeRefImpl.java b/Backend/services/core/src/main/java/org/edu_sharing/service/model/NodeRefImpl.java index 47a99abbbb..fda7494054 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/model/NodeRefImpl.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/model/NodeRefImpl.java @@ -65,7 +65,7 @@ public Boolean getIcon() { String nodeId; Preview preview; - HashMap properties; + Map properties; Map permissions; /** @@ -90,7 +90,7 @@ public NodeRefImpl(String repositoryId, String storeProtocol, String storeId, St this.storeProtocol = storeProtocol; this.nodeId = nodeId; } - public NodeRefImpl(String repositoryId, String storeProtocol, String storeId, HashMap properties ){ + public NodeRefImpl(String repositoryId, String storeProtocol, String storeId, Map properties ){ this.repositoryId = repositoryId; this.storeId = storeId; this.storeProtocol = storeProtocol; @@ -126,11 +126,11 @@ public void setNodeId(String nodeId) { } @Override - public HashMap getProperties() { + public Map getProperties() { return properties; } - public void setProperties(HashMap properties) { + public void setProperties(Map properties) { this.properties = properties; } diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/network/NetworkServiceImpl.java b/Backend/services/core/src/main/java/org/edu_sharing/service/network/NetworkServiceImpl.java index 57c429902a..cb7cd4c3ae 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/network/NetworkServiceImpl.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/network/NetworkServiceImpl.java @@ -21,10 +21,7 @@ import java.net.URL; import java.nio.file.Files; import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; +import java.util.*; import java.util.stream.Collectors; @@ -42,7 +39,7 @@ public Collection getServices() throws Throwable{ Collection result=new ArrayList<>(); result.add(getOwnService()); for(ChildAssociationRef service : services){ - HashMap props = nodeService.getProperties(service.getChildRef().getStoreRef().getProtocol(), service.getChildRef().getStoreRef().getIdentifier(), service.getChildRef().getId()); + Map props = nodeService.getProperties(service.getChildRef().getStoreRef().getProtocol(), service.getChildRef().getStoreRef().getIdentifier(), service.getChildRef().getId()); String data= (String) props.get(CCConstants.CCM_PROP_SERVICE_NODE_DATA); StoredService serviceObject = new Gson().fromJson(data, StoredService.class); serviceObject.setId((String) props.get(CCConstants.CM_NAME)); @@ -100,7 +97,7 @@ public StoredService addService(Service service) throws Throwable { String parent=new UserEnvironmentTool().getEdu_SharingServiceFolder(); String id=generateId(service); - HashMap props = generateProps(id,service); + Map props = generateProps(id,service); nodeService.createNode(parent,CCConstants.CCM_TYPE_SERVICE_NODE,props); return new StoredService(id,service); } @@ -115,7 +112,7 @@ public StoredService updateService(String id, Service service) throws Throwable try{ String parent=new UserEnvironmentTool().getEdu_SharingServiceFolder(); String node = nodeService.findNodeByName(parent, id); - HashMap props = generateProps(id,service); + Map props = generateProps(id,service); nodeService.updateNode(node,props); return new StoredService(id,service); } @@ -127,8 +124,8 @@ private String generateId(Service service) { return DigestUtils.shaHex(service.getUrl()); } - private HashMap generateProps(String id, Service service) { - HashMap props = new HashMap<>(); + private Map generateProps(String id, Service service) { + Map props = new HashMap<>(); props.put(CCConstants.CM_NAME,new String[]{id}); String json=new Gson().toJson(service); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/nodeservice/NodeFrontpage.java b/Backend/services/core/src/main/java/org/edu_sharing/service/nodeservice/NodeFrontpage.java index 8ee71d0922..460c10df2a 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/nodeservice/NodeFrontpage.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/nodeservice/NodeFrontpage.java @@ -43,7 +43,7 @@ public class NodeFrontpage { private SearchService searchService= SearchServiceFactory.getLocalService(); private NodeService nodeService=NodeServiceFactory.getLocalService(); private PermissionService permissionService= PermissionServiceFactory.getLocalService(); - private HashMap APPLY_DATES; + private Map APPLY_DATES; SearchServiceElastic searchServiceElastic = new SearchServiceElastic(ApplicationInfoList.getHomeRepository().getAppId()); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/nodeservice/NodeService.java b/Backend/services/core/src/main/java/org/edu_sharing/service/nodeservice/NodeService.java index d7de09b10d..287e522675 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/nodeservice/NodeService.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/nodeservice/NodeService.java @@ -11,26 +11,23 @@ import java.io.InputStream; import java.io.Serializable; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; +import java.util.*; public interface NodeService { - public void updateNode(String nodeId, HashMap props) throws Throwable; + public void updateNode(String nodeId, Map props) throws Throwable; public void createAssoc(String parentId,String childId,String assocName); - public String createNode(String parentId, String nodeType, HashMap props)throws Throwable; + public String createNode(String parentId, String nodeType, Map props)throws Throwable; - public String createNode(String parentId, String nodeType, HashMap props, String childAssociation) throws Throwable; + public String createNode(String parentId, String nodeType, Map props, String childAssociation) throws Throwable; - public String createNodeBasic(String parentID, String nodeTypeString, HashMap _props); + public String createNodeBasic(String parentID, String nodeTypeString, Map _props); public String createNodeBasic(StoreRef store, String parentID, String nodeTypeString, String childAssociation, - HashMap _props); + Map _props); public String findNodeByName(String parentId, String name ); @@ -38,7 +35,7 @@ public String createNodeBasic(StoreRef store, String parentID, String nodeTypeSt public String getCompanyHome(); - public HashMap getNameProperty(String name); + public Map getNameProperty(String name); List getChildrenRecursive(StoreRef store, String nodeId, List types,RecurseMode recurseMode); @@ -79,19 +76,19 @@ public void writeContent(final StoreRef store, final String nodeID, final InputS public void removeNode(String nodeID, String fromID); - public HashMap getProperties(String storeProtocol, String storeId, String nodeId) throws Throwable; + public Map getProperties(String storeProtocol, String storeId, String nodeId) throws Throwable; /** * this method is called when a local object has ccm:remoterepositry aspect, and all local properties will get * updated on the fly with the properties provided by this method */ - public HashMap getPropertiesDynamic(String storeProtocol, String storeId, String nodeId) throws Throwable; + public Map getPropertiesDynamic(String storeProtocol, String storeId, String nodeId) throws Throwable; /** * this method is called when a local object has ccm:remoterepositry aspect and the node should be stored localy * You can define which properties should be copied locally and which should be fetched dynamically by skipping them here */ - public HashMap getPropertiesPersisting(String storeProtocol, String storeId, String nodeId) throws Throwable; + public Map getPropertiesPersisting(String storeProtocol, String storeId, String nodeId) throws Throwable; public default boolean hasAspect(String storeProtocol, String storeId, String nodeId, String aspect){ return Arrays.asList(getAspects(storeProtocol,storeId,nodeId)).contains(aspect); @@ -112,7 +109,7 @@ public default boolean hasAspect(String storeProtocol, String storeId, String no public void revertVersion(String nodeId, String verLbl) throws Exception; - public HashMap> getVersionHistory(String nodeId) throws Throwable; + public Map> getVersionHistory(String nodeId) throws Throwable; @NonNull List getVersionLabelsHistory(String nodeId); @@ -137,7 +134,7 @@ public default boolean hasAspect(String storeProtocol, String storeId, String no public void removeAspect(String nodeId, String aspect); - public void updateNodeNative(String nodeId, HashMap _props); + public void updateNodeNative(String nodeId, Map _props); public void removeProperty(String storeProtocol, String storeId, String nodeId, String property); @@ -160,10 +157,11 @@ default String getProperty(String storeProtocol, String storeId, String nodeId, /** * Sets the properties for this node's template (inherit metadata to child nodes) * Should only be supported for folder types + * * @param nodeId - * @param stringHashMap + * @param properties */ - void setTemplateProperties(String nodeId, HashMap stringHashMap) throws Throwable; + void setTemplateProperties(String nodeId, Map properties) throws Throwable; /** * Set if the inherition of properties is enabled for this folder @@ -180,7 +178,7 @@ default String getProperty(String storeProtocol, String storeId, String nodeId, void setProperty(String protocol, String storeId, String nodeId, String property, Serializable value, boolean skipDefinitionChecks); - GetPreviewResult getPreview(String storeProtocol, String storeIdentifier, String nodeId, HashMap nodeProps, String version); + GetPreviewResult getPreview(String storeProtocol, String storeIdentifier, String nodeId, Map nodeProps, String version); Collection getFrontpageNodes() throws Throwable; diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/nodeservice/NodeServiceAdapter.java b/Backend/services/core/src/main/java/org/edu_sharing/service/nodeservice/NodeServiceAdapter.java index 77a65c54ae..67c82c1080 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/nodeservice/NodeServiceAdapter.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/nodeservice/NodeServiceAdapter.java @@ -2,10 +2,7 @@ import java.io.InputStream; import java.io.Serializable; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; +import java.util.*; import java.util.Map.Entry; import org.alfresco.service.cmr.repository.*; @@ -30,7 +27,7 @@ public NodeServiceAdapter(String appId) { } @Override - public void updateNode(String nodeId, HashMap props) throws Throwable { + public void updateNode(String nodeId, Map props) throws Throwable { } @Override @@ -39,12 +36,12 @@ public void createAssoc(String parentId, String childId, String assocName) { } @Override - public String createNode(String parentId, String nodeType, HashMap props) throws Throwable { + public String createNode(String parentId, String nodeType, Map props) throws Throwable { return null; } @Override - public String createNodeBasic(String parentID, String nodeTypeString, HashMap _props) { + public String createNodeBasic(String parentID, String nodeTypeString, Map _props) { return null; } @@ -64,7 +61,7 @@ public String getCompanyHome() { } @Override - public HashMap getNameProperty(String name) { + public Map getNameProperty(String name) { return null; } @@ -111,17 +108,17 @@ public void removeNode(String nodeID, String fromID) { } @Override - public HashMap getProperties(String storeProtocol, String storeId, String nodeId) throws Throwable { - return new HashMap(); + public Map getProperties(String storeProtocol, String storeId, String nodeId) throws Throwable { + return new HashMap<>(); } @Override - public HashMap getPropertiesDynamic(String storeProtocol, String storeId, String nodeId) throws Throwable { - return new HashMap(); + public Map getPropertiesDynamic(String storeProtocol, String storeId, String nodeId) throws Throwable { + return new HashMap<>(); } @Override - public HashMap getPropertiesPersisting(String storeProtocol, String storeId, String nodeId) throws Throwable { + public Map getPropertiesPersisting(String storeProtocol, String storeId, String nodeId) throws Throwable { return getProperties(storeProtocol, storeId, nodeId); } @@ -149,7 +146,7 @@ public void revertVersion(String nodeId, String verLbl) throws Exception { } @Override - public HashMap> getVersionHistory(String nodeId) throws Throwable { + public Map> getVersionHistory(String nodeId) throws Throwable { return null; } @@ -160,7 +157,7 @@ public List getVersionLabelsHistory(String nodeId) { } private List getPropertyValues(ValueTool vt,Object value) { - List values = new ArrayList(); + List values = new ArrayList<>(); if (value != null ){ for (String mv : vt.getMultivalue(value.toString())) { values.add(mv); @@ -169,9 +166,9 @@ private List getPropertyValues(ValueTool vt,Object value) { return values; } - private HashMap convertProperties(HashMap propsIn){ + private Map convertProperties(Map propsIn){ ValueTool vt = new ValueTool(); - HashMap properties = new HashMap(); + Map properties = new HashMap<>(); for (Entry entry : propsIn.entrySet()) { List values = getPropertyValues(vt, entry.getValue()); properties.put(entry.getKey(), values.toArray(new String[values.size()])); @@ -197,7 +194,7 @@ public Integer getContentLength(String nodeId) throws Throwable{ */ @Override public String importNode(String nodeId,String localParent) throws Throwable { - HashMap props = getProperties(null, null, nodeId); + Map props = getProperties(null, null, nodeId); String mimetype=null; if(props.containsKey(CCConstants.LOM_PROP_TECHNICAL_FORMAT)) mimetype= (String) props.get(CCConstants.LOM_PROP_TECHNICAL_FORMAT); @@ -239,7 +236,7 @@ public User getOwner(String storeId, String storeProtocol, String nodeId) { } @Override - public String createNode(String parentId, String nodeType, HashMap props, String childAssociation) + public String createNode(String parentId, String nodeType, Map props, String childAssociation) throws Throwable { // TODO Auto-generated method stub return null; @@ -280,7 +277,7 @@ public void removeAspect(String nodeId, String aspect) { } @Override - public void updateNodeNative(String nodeId, HashMap _props) { + public void updateNodeNative(String nodeId, Map _props) { // TODO Auto-generated method stub } @@ -293,7 +290,7 @@ public void removeProperty(String storeProtocol, String storeId, String nodeId, @Override public String createNodeBasic(StoreRef store, String parentID, String nodeTypeString, String childAssociation, - HashMap _props) { + Map _props) { // TODO Auto-generated method stub return null; } @@ -321,7 +318,7 @@ public String getTemplateNode(String nodeId,boolean create) throws Throwable { } @Override - public void setTemplateProperties(String nodeId, HashMap stringHashMap) throws Throwable { + public void setTemplateProperties(String nodeId, Map properties) throws Throwable { } @@ -362,7 +359,7 @@ public void setProperty(String protocol, String storeId, String nodeId, String p } @Override - public GetPreviewResult getPreview(String storeProtocol, String storeIdentifier, String nodeId, HashMap nodeProps, String version) { + public GetPreviewResult getPreview(String storeProtocol, String storeIdentifier, String nodeId, Map nodeProps, String version) { try { String previewURL = URLTool.getBaseUrl(true); previewURL += "/preview?nodeId="+URLEncoder.encodeUriComponent(nodeId)+"&repository="+ diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/nodeservice/NodeServiceAdapterCached.java b/Backend/services/core/src/main/java/org/edu_sharing/service/nodeservice/NodeServiceAdapterCached.java index ebc868f586..3e518042d4 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/nodeservice/NodeServiceAdapterCached.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/nodeservice/NodeServiceAdapterCached.java @@ -5,23 +5,24 @@ import org.edu_sharing.repository.client.tools.CCConstants; import java.util.HashMap; +import java.util.Map; import java.util.concurrent.ConcurrentMap; public class NodeServiceAdapterCached extends NodeServiceAdapter{ - private static final ConcurrentMap propertyCache = new ConcurrentLinkedHashMap.Builder() + private static final ConcurrentMap> propertyCache = new ConcurrentLinkedHashMap.Builder>() .maximumWeightedCapacity(1000) .build(); public NodeServiceAdapterCached(String appId) { super(appId); } - public static void updateCache(HashMap properties) { - propertyCache.put(properties.get(CCConstants.SYS_PROP_NODE_UID), properties); + public static void updateCache(Map properties) { + propertyCache.put((String)properties.get(CCConstants.SYS_PROP_NODE_UID), properties); } @Override - public HashMap getProperties(String storeProtocol, String storeId, String nodeId) throws Throwable { + public Map getProperties(String storeProtocol, String storeId, String nodeId) throws Throwable { if (propertyCache.containsKey(nodeId)) - return (HashMap) propertyCache.get(nodeId); + return propertyCache.get(nodeId); return null; } } diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/nodeservice/NodeServiceBrockhausImpl.java b/Backend/services/core/src/main/java/org/edu_sharing/service/nodeservice/NodeServiceBrockhausImpl.java index 44cdc1bb63..a9d9de9271 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/nodeservice/NodeServiceBrockhausImpl.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/nodeservice/NodeServiceBrockhausImpl.java @@ -1,18 +1,14 @@ package org.edu_sharing.service.nodeservice; -import org.apache.commons.collections.map.LRUMap; import org.apache.log4j.Logger; import org.edu_sharing.repository.client.tools.CCConstants; -import org.edu_sharing.repository.server.SearchResultNodeRef; import org.edu_sharing.repository.server.tools.ApplicationInfo; import org.edu_sharing.repository.server.tools.ApplicationInfoList; import org.edu_sharing.service.search.SearchServiceBrockhausImpl; -import javax.net.ssl.HttpsURLConnection; import java.io.InputStream; -import java.net.HttpURLConnection; -import java.net.URL; import java.util.HashMap; +import java.util.Map; public class NodeServiceBrockhausImpl extends NodeServiceAdapterCached{ @@ -28,8 +24,8 @@ public NodeServiceBrockhausImpl(String appId) { } @Override - public HashMap getProperties(String storeProtocol, String storeId, String nodeId) throws Throwable { - HashMap props = super.getProperties(storeProtocol, storeId, nodeId); + public Map getProperties(String storeProtocol, String storeId, String nodeId) throws Throwable { + Map props = super.getProperties(storeProtocol, storeId, nodeId); if (props == null) { props = new HashMap<>(); } @@ -40,7 +36,7 @@ public HashMap getProperties(String storeProtocol, String storeI return props; } @Override - public HashMap getPropertiesDynamic(String storeProtocol, String storeId, String nodeId) throws Throwable { + public Map getPropertiesDynamic(String storeProtocol, String storeId, String nodeId) throws Throwable { return getProperties(storeProtocol, storeId, nodeId); } diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/nodeservice/NodeServiceDDBImpl.java b/Backend/services/core/src/main/java/org/edu_sharing/service/nodeservice/NodeServiceDDBImpl.java index 7488d9f827..c6c1f3d31c 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/nodeservice/NodeServiceDDBImpl.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/nodeservice/NodeServiceDDBImpl.java @@ -34,7 +34,7 @@ public class NodeServiceDDBImpl extends NodeServiceAdapterCached{ private final XPathFactory pfactory = XPathFactory.newInstance(); private final XPath xpath = pfactory.newXPath(); - private final Map LICENSE_MAPPINGS = new HashMap(){{ + private final Map LICENSE_MAPPINGS = new HashMap<>(){{ put("http://creativecommons.org/publicdomain/zero/1.0/", CCConstants.COMMON_LICENSE_CC_ZERO); put("http://creativecommons.org/licenses/by/3.0/", CCConstants.COMMON_LICENSE_CC_BY); put("http://creativecommons.org/licenses/by-sa/4.0/", CCConstants.COMMON_LICENSE_CC_BY_SA); @@ -50,13 +50,13 @@ public NodeServiceDDBImpl(String appId) { } @Override - public HashMap getProperties(String storeProtocol, String storeId, String nodeId) throws Throwable { - HashMap props = super.getProperties(storeProtocol, storeId, nodeId); + public Map getProperties(String storeProtocol, String storeId, String nodeId) throws Throwable { + Map props = super.getProperties(storeProtocol, storeId, nodeId); if(props != null) { return props; } - HashMap properties = new HashMap(); + Map properties = new HashMap<>(); properties.put(CCConstants.SYS_PROP_NODE_UID,nodeId); String url = "https://www.deutsche-digitale-bibliothek.de/item/"+nodeId; properties.put(CCConstants.LOM_PROP_TECHNICAL_LOCATION, url); @@ -64,7 +64,7 @@ public HashMap getProperties(String storeProtocol, String storeI properties.put(CCConstants.CCM_PROP_IO_REPLICATIONSOURCE, "ddb"); try{ // fetch binary info - String all = SearchServiceDDBImpl.httpGet(SearchServiceDDBImpl.DDB_API+"/items/"+nodeId+"?oauth_consumer_key=" + URLEncoder.encode(this.APIKey, "UTF-8"), new HashMap() {{ + String all = SearchServiceDDBImpl.httpGet(SearchServiceDDBImpl.DDB_API+"/items/"+nodeId+"?oauth_consumer_key=" + URLEncoder.encode(this.APIKey, "UTF-8"), new HashMap<>() {{ put("Accept", "application/xml"); put("Content-Type", "application/xml"); }}); @@ -181,4 +181,4 @@ public String getType(String nodeId) { public InputStream getContent(String nodeId) throws Throwable { return null; } -} \ No newline at end of file +} diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/nodeservice/NodeServiceHelper.java b/Backend/services/core/src/main/java/org/edu_sharing/service/nodeservice/NodeServiceHelper.java index 429f392859..f87070c959 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/nodeservice/NodeServiceHelper.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/nodeservice/NodeServiceHelper.java @@ -3,8 +3,6 @@ import org.alfresco.model.ContentModel; import org.alfresco.repo.model.Repository; import org.alfresco.repo.security.authentication.AuthenticationUtil; -import org.alfresco.repo.security.permissions.PermissionReference; -import org.alfresco.repo.security.permissions.impl.model.PermissionModel; import org.alfresco.service.ServiceRegistry; import org.alfresco.service.cmr.repository.ChildAssociationRef; import org.alfresco.service.cmr.repository.NodeRef; @@ -62,7 +60,7 @@ public static void setCreateVersion(String nodeId, boolean create) { new MCAlfrescoAPIClient().setProperty(nodeId, CCConstants.CCM_PROP_IO_CREATE_VERSION, create); } public static Map transformLongToShortProperties(Map properties) { - HashMap result = new HashMap<>(); + Map result = new HashMap<>(); for(Map.Entry prop: properties.entrySet()){ if(CCConstants.getValidLocalName(prop.getKey()) != null) { result.put(CCConstants.getValidLocalName(prop.getKey()), prop.getValue()); @@ -70,15 +68,15 @@ public static Map transformLongToShortProperties(Map p } return result; } - public static HashMap transformShortToLongProperties(HashMap properties) { + public static Map transformShortToLongProperties(Map properties) { /** * shortNames to long names */ - HashMap propsLongKeys = (HashMap)new NameSpaceTool() + Map propsLongKeys = new NameSpaceTool() .transformKeysToLongQname(properties); - HashMap result = new HashMap(); + Map result = new HashMap<>(); for (Map.Entry property : propsLongKeys.entrySet()) { if(result.containsKey(property.getKey())) continue; @@ -99,7 +97,7 @@ public static List> getSubobjects(NodeService service, String List childs=service.getChildrenChildAssociationRefAssoc(nodeId,null,filter,sort); for(ChildAssociationRef child : childs) { NodeRef ref = child.getChildRef(); - HashMap props = service.getProperties(ref.getStoreRef().getProtocol(),ref.getStoreRef().getIdentifier(),ref.getId()); + Map props = service.getProperties(ref.getStoreRef().getProtocol(),ref.getStoreRef().getIdentifier(),ref.getId()); result.add(props); } return result; @@ -172,7 +170,7 @@ public static boolean hasPropertyValue(NodeRef nodeRef, String key) { */ public static Serializable getPropertyNativeWithMapping(NodeRef nodeRef, String key) throws Throwable { if(key.endsWith(CCConstants.DISPLAYNAME_SUFFIX)) { - HashMap props = getProperties(nodeRef); + Map props = getProperties(nodeRef); MetadataHelper.addVirtualDisplaynameProperties( MetadataHelper.getMetadataset(nodeRef), props @@ -203,17 +201,17 @@ public static String[] getAspects(NodeRef nodeRef){ public static boolean hasAspect(NodeRef nodeRef,String aspect){ return NodeServiceFactory.getLocalService().hasAspect(nodeRef.getStoreRef().getProtocol(),nodeRef.getStoreRef().getIdentifier(),nodeRef.getId(),aspect); } - public static HashMap getProperties(NodeRef nodeRef) throws Throwable { + public static Map getProperties(NodeRef nodeRef) throws Throwable { return NodeServiceFactory.getLocalService().getProperties(nodeRef.getStoreRef().getProtocol(),nodeRef.getStoreRef().getIdentifier(),nodeRef.getId()); } - public static HashMap getPropertiesVersion(NodeRef nodeRef, String version) throws Throwable { + public static Map getPropertiesVersion(NodeRef nodeRef, String version) throws Throwable { if(version == null){ return getProperties(nodeRef); } - HashMap> versionHistory = NodeServiceFactory.getLocalService().getVersionHistory(nodeRef.getId()); + Map> versionHistory = NodeServiceFactory.getLocalService().getVersionHistory(nodeRef.getId()); if (versionHistory != null) { - for (HashMap versionData : versionHistory.values()) { + for (Map versionData : versionHistory.values()) { if(version.equals(versionData.get(CCConstants.CM_PROP_VERSIONABLELABEL))){ return versionData; } @@ -253,9 +251,9 @@ public static void validatePermissionRestrictedAccess(NodeRef nodeRef, String... /* * map the permissions to simplified values as stored in the CCM_PROP_RESTRICTED_ACCESS_PERMISSIONS */ - HashMap permissionsMapped = new HashMap() {{ - put(CCConstants.PERMISSION_READ_PREVIEW, CCConstants.PERMISSION_READ_ALL); - }}; + Map permissionsMapped = new HashMap<>() {{ + put(CCConstants.PERMISSION_READ_PREVIEW, CCConstants.PERMISSION_READ_ALL); + }}; if(Arrays.stream(permissions) .filter((permission) -> !PermissionServiceHelper.hasPermission(new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, originalNodeId), permission)) .map(permission -> permissionsMapped.getOrDefault(permission, permission)) @@ -301,8 +299,8 @@ public static void writeContentText(NodeRef nodeRef,String content) throws Throw * @return * @throws Throwable */ - public static HashMap getPropertiesMultivalue(Map properties) { - HashMap propertiesMultivalue = new HashMap<>(); + public static Map getPropertiesMultivalue(Map properties) { + Map propertiesMultivalue = new HashMap<>(); if(properties!=null) { properties.forEach((key, value) -> { String[] result = value==null ? null : ValueTool.getMultivalue(value.toString()); @@ -323,8 +321,8 @@ public static HashMap getPropertiesMultivalue(Map p * @return * @throws Throwable */ - public static HashMap getPropertiesSinglevalue(Map properties) { - HashMap propertiesMultivalue = new HashMap<>(); + public static Map getPropertiesSinglevalue(Map properties) { + Map propertiesMultivalue = new HashMap<>(); if(properties!=null) { properties.forEach((key, value) -> convertMutlivaluePropToGeneric(value, propertiesMultivalue, key)); return propertiesMultivalue; @@ -367,7 +365,7 @@ public static List findNodeByPropertiesRecursive(NodeRef parent, List nodeProps) { + public static GetPreviewResult getPreview(NodeRef ref, Map nodeProps) { return NodeServiceFactory.getLocalService().getPreview(ref.getStoreRef().getProtocol(),ref.getStoreRef().getIdentifier(),ref.getId(), nodeProps, null); } public static GetPreviewResult getPreview(org.edu_sharing.service.model.NodeRef ref) { @@ -455,7 +453,7 @@ public static String getContainerIdByPath(String rootPath, String pattern){ public static String getContainerRootPath(String rootPath) throws Throwable { MCAlfrescoAPIClient client = new MCAlfrescoAPIClient(); - HashMap> search = client.search("PATH:\"" + rootPath + "\"", CCConstants.CM_TYPE_FOLDER); + Map> search = client.search("PATH:\"" + rootPath + "\"", CCConstants.CM_TYPE_FOLDER); String rootId = null; if (search.size() != 1) { if(search.size() > 1) throw new IllegalArgumentException("The path must reference a unique node."); @@ -483,7 +481,7 @@ public static String getContainerRootPath(String rootPath) throws Throwable { * @param nodeRef * @return */ - public static HashMap getPropertiesOriginal(NodeRef nodeRef) throws Throwable{ + public static Map getPropertiesOriginal(NodeRef nodeRef) throws Throwable{ if(NodeServiceHelper.hasAspect(nodeRef, CCConstants.CCM_ASPECT_COLLECTION_IO_REFERENCE)){ if(!PermissionServiceHelper.hasPermission(nodeRef, CCConstants.PERMISSION_READ)){ throw new PermissionException(nodeRef.toString(), CCConstants.PERMISSION_READ); @@ -507,12 +505,12 @@ public static HashMap getPropertiesOriginal(NodeRef nodeRef) thr return NodeServiceHelper.getProperties(nodeRef); } - public static void convertMutlivaluePropToGeneric(String[] arr, HashMap target, String property) { + public static void convertMutlivaluePropToGeneric(String[] arr, Map target, String property) { if(arr != null){ if(arr.length==0) target.put(property,null); else if(arr.length > 1) - target.put(property,new ArrayList(Arrays.asList(arr))); + target.put(property,new ArrayList<>(Arrays.asList(arr))); else target.put(property, arr[0]); } diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/nodeservice/NodeServiceImpl.java b/Backend/services/core/src/main/java/org/edu_sharing/service/nodeservice/NodeServiceImpl.java index 5408e39f4a..40a8b05efd 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/nodeservice/NodeServiceImpl.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/nodeservice/NodeServiceImpl.java @@ -98,7 +98,7 @@ public NodeServiceImpl(String appId) { dictionaryService = serviceRegistry.getDictionaryService(); repositoryHelper = (Repository) applicationContext.getBean("repositoryHelper"); this.appId=appId; - HashMap homeAuthInfo = null; + Map homeAuthInfo = null; if(!ApplicationInfoList.getRepositoryInfoById(repositoryId).ishomeNode()){ homeAuthInfo = new AuthenticationToolAPI().getAuthentication(Context.getCurrentInstance().getRequest().getSession()); } @@ -110,11 +110,11 @@ public NodeServiceImpl(String appId) { } } - public void updateNode(String nodeId, HashMap props) throws Throwable{ + public void updateNode(String nodeId, Map props) throws Throwable{ String nodeType = getType(nodeId); String[] aspects = getAspects(StoreRef.PROTOCOL_WORKSPACE, StoreRef.STORE_REF_WORKSPACE_SPACESSTORE.getIdentifier(), nodeId); String parentId = nodeService.getPrimaryParent(new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE,nodeId)).getParentRef().getId(); - HashMap toSafeProps = getToSafeProps(props,nodeType,aspects, nodeId, parentId,null); + Map toSafeProps = getToSafeProps(props,nodeType,aspects, nodeId, parentId,null); updateNodeNative(nodeId, toSafeProps); } @@ -169,31 +169,31 @@ private void throwIfRestrictedAccessPresent(NodeRef nodeRef) { } } - private void resetVersion(NodeRef nodeRef) throws Throwable { + private void resetVersion(NodeRef nodeRef) { if(CCConstants.CCM_TYPE_IO.equals(getType(nodeRef.getId()))) { - HashMap props = new HashMap(); + Map props = new HashMap<>(); props.put(CCConstants.LOM_PROP_LIFECYCLE_VERSION,"1.0"); updateNodeNative(nodeRef.getId(), props); } } - public String createNode(String parentId, String nodeType, HashMap props) throws Throwable{ - HashMap toSafeProps = getToSafeProps(props,nodeType,null, null,parentId,null); + public String createNode(String parentId, String nodeType, Map props) throws Throwable{ + Map toSafeProps = getToSafeProps(props,nodeType,null, null,parentId,null); return createNodeBasic(parentId, nodeType, toSafeProps); } @Override - public String createNode(String parentId, String nodeType, HashMap props, String childAssociation) + public String createNode(String parentId, String nodeType, Map props, String childAssociation) throws Throwable { - HashMap toSafeProps = getToSafeProps(props,nodeType,null, null,parentId,null); + Map toSafeProps = getToSafeProps(props,nodeType,null, null,parentId,null); return this.createNodeBasic(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, parentId, nodeType,childAssociation, toSafeProps); } @Override - public String createNodeBasic(String parentID, String nodeTypeString, HashMap _props) { + public String createNodeBasic(String parentID, String nodeTypeString, Map _props) { return this.createNodeBasic(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, parentID, nodeTypeString,CCConstants.CM_ASSOC_FOLDER_CONTAINS, _props); } @Override - public String createNodeBasic(StoreRef store, String parentID, String nodeTypeString, String childAssociation, HashMap _props) { + public String createNodeBasic(StoreRef store, String parentID, String nodeTypeString, String childAssociation, Map _props) { childAssociation = (childAssociation == null) ? CCConstants.CM_ASSOC_FOLDER_CONTAINS : childAssociation; NodeRef parentNodeRef = new NodeRef(store, parentID); @@ -246,7 +246,7 @@ public String getCompanyHome(){ return repositoryHelper.getCompanyHome().getId(); } - private HashMap getToSafeProps(HashMap props, String nodeType, String[] aspects, String nodeId, String parentId,String templateName) throws Throwable{ + private Map getToSafeProps(Map props, String nodeType, String[] aspects, String nodeId, String parentId,String templateName) throws Throwable{ String[] metadataSetIdArr = props.get(CCConstants.CM_PROP_METADATASET_EDU_METADATASET); String metadataSetId = (metadataSetIdArr != null && metadataSetIdArr.length > 0) ? metadataSetIdArr[0] : null; @@ -285,7 +285,7 @@ private HashMap getToSafeProps(HashMap props, S } MetadataSet mds = MetadataHelper.getMetadataset(getApplication(), metadataSetId); - HashMap toSafe = new HashMap(); + Map toSafe = new HashMap<>(); for (MetadataWidget widget : (templateName==null ? mds.getWidgetsByNode(nodeType,Arrays.asList(ArrayUtils.nullToEmpty(aspects)), false) : mds.getWidgetsByTemplate(templateName))) { @@ -402,8 +402,8 @@ private static Iterable getAllSafeProps() { return safe; } @Override - public HashMap getNameProperty(String name) { - HashMap map=new HashMap(); + public Map getNameProperty(String name) { + Map map= new HashMap<>(); map.put(CCConstants.CM_NAME, new String[]{name}); return map; } @@ -426,11 +426,11 @@ private List getChildrenAssocsByType(StoreRef store, String return childAssocList; } - public HashMap> getChildrenByType(StoreRef store, String nodeId, String type) { - HashMap> result = new HashMap>(); + public Map> getChildrenByType(StoreRef store, String nodeId, String type) { + Map> result = new HashMap<>(); List childAssocList = getChildrenAssocsByType(store,nodeId,type); for (ChildAssociationRef child : childAssocList) { - HashMap resultProps = getPropertiesWithoutChildren(child.getChildRef()); + Map resultProps = getPropertiesWithoutChildren(child.getChildRef()); String childNodeId = child.getChildRef().getId(); result.put(childNodeId, resultProps); } @@ -505,9 +505,9 @@ public NodeRef getChild(StoreRef store, String parentId, String type, String pro - private HashMap getPropertiesWithoutChildren(NodeRef nodeRef) { + private Map getPropertiesWithoutChildren(NodeRef nodeRef) { Map childPropMap = nodeService.getProperties(nodeRef); - HashMap resultProps = new HashMap(); + Map resultProps = new HashMap<>(); String nodeType = nodeService.getType(nodeRef).toString(); @@ -522,7 +522,7 @@ private HashMap getPropertiesWithoutChildren(NodeRef nodeRef) { // VCard String type = nodeService.getType(nodeRef).toString(); - HashMap vcard = VCardConverter.getVCardHashMap(type, qname.toString(), value); + Map vcard = VCardConverter.getVCardMap(type, qname.toString(), value); if (vcard != null && vcard.size() > 0) resultProps.putAll(vcard); @@ -641,7 +641,7 @@ protected String getMLTextString(Object _mlText) { } @Override - public void updateNodeNative(String nodeId, HashMap _props) { + public void updateNodeNative(String nodeId, Map _props) { this.updateNodeNative(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, nodeId, _props); } @@ -712,19 +712,19 @@ public void updateNodeNative(StoreRef store, String nodeId, Map _prop } - Map transformPropMap(Map map) { - Map result = new HashMap(); + Map transformPropMap(Map map) { + Map result = new HashMap<>(); for (Object key : map.keySet()) { try { Object value = map.get(key); - if (value instanceof HashMap) { - value = getMLText((HashMap) value); + if (value instanceof Map) { + value = getMLText((Map) value); } else if (value instanceof List) { List transformedList = new ArrayList(); - for (Object valCol : (ArrayList) value) { - if (valCol instanceof HashMap) { - transformedList.add(getMLText((HashMap) valCol)); + for (Object valCol : (List) value) { + if (valCol instanceof Map) { + transformedList.add(getMLText((Map) valCol)); } else { transformedList.add(valCol); } @@ -740,11 +740,10 @@ Map transformPropMap(Map map) { return result; } - private MLText getMLText(HashMap i18nMap) { + private MLText getMLText(Map i18nMap) { MLText mlText = new MLText(); - for (Object obj : i18nMap.keySet()) { - String locale = (String) obj; - mlText.addValue(new Locale(locale), (String) i18nMap.get(obj)); + for (String locale : i18nMap.keySet()) { + mlText.addValue(new Locale(locale), i18nMap.get(locale)); } return mlText; } @@ -797,7 +796,7 @@ public String getUserInbox(boolean createIfNotExists) { if(inbox!=null && inbox.size()>0) return inbox.get(0).getChildRef().getId(); if(createIfNotExists) { - HashMap properties = new HashMap<>(); + Map properties = new HashMap<>(); properties.put(CCConstants.CM_NAME, "Inbox"); properties.put(CCConstants.CCM_PROP_MAP_TYPE, CCConstants.CCM_VALUE_MAP_TYPE_USERINBOX); return createNodeBasic(userhome.getId(), CCConstants.CCM_TYPE_MAP, properties); @@ -811,7 +810,7 @@ public String getUserSavedSearch(boolean createIfNotExists) { if(savedSearch!=null && savedSearch.size()>0) return savedSearch.get(0).getChildRef().getId(); if(createIfNotExists) { - HashMap properties = new HashMap<>(); + Map properties = new HashMap<>(); properties.put(CCConstants.CM_NAME, "SavedSearch"); properties.put(CCConstants.CCM_PROP_MAP_TYPE, CCConstants.CCM_VALUE_MAP_TYPE_USERSAVEDSEARCH); return createNodeBasic(userhome.getId(), CCConstants.CCM_TYPE_MAP, properties); @@ -841,7 +840,7 @@ public List sortNodeRefList(List list,List filter, SortDefiniti } list=filtered; - HashMap cache=new HashMap(); + Map cache=new HashMap<>(); Collections.sort(list, (o1, o2) -> sortNodes(cache,getAsNode(o1),getAsNode(o2),sortDefinition)); return list; } @@ -863,7 +862,7 @@ else if(obj instanceof NodeRef){ return node; } - private int sortNodes(HashMap cache, NodeRef n1, NodeRef n2, SortDefinition sortDefinition) { + private int sortNodes(Map cache, NodeRef n1, NodeRef n2, SortDefinition sortDefinition) { String keyType1=n1.toString()+"_TYPE"; String keyType2=n2.toString()+"_TYPE"; @@ -1120,16 +1119,16 @@ public void removeNodeForce(String storeProtocol, String storeId, String nodeId, } @Override - public HashMap getProperties(String storeProtocol, String storeId, String nodeId) throws Throwable{ + public Map getProperties(String storeProtocol, String storeId, String nodeId) throws Throwable{ return apiClient.getProperties(storeProtocol, storeId, nodeId); } @Override - public HashMap getPropertiesDynamic(String storeProtocol, String storeId, String nodeId) throws Throwable{ + public Map getPropertiesDynamic(String storeProtocol, String storeId, String nodeId) throws Throwable{ throw new NotImplementedException("getPropertiesDynamic may not be called for the local repository (was the remote repo removed?)"); } @Override - public HashMap getPropertiesPersisting(String storeProtocol, String storeId, String nodeId) throws Throwable{ + public Map getPropertiesPersisting(String storeProtocol, String storeId, String nodeId) throws Throwable{ throw new NotImplementedException("getPropertiesPersisting may not be called for the local repository (was the remote repo removed?)"); } @@ -1257,7 +1256,7 @@ public void createHandle(NodeRef nodeRef, List publishedCopies, HandleMo String handle = null; - Map publishedProps = new HashMap(); + Map publishedProps = new HashMap<>(); if(handleMode.equals(HandleMode.distinct)) { try { @@ -1365,9 +1364,9 @@ public String getTemplateNode(String nodeId,boolean create) throws Throwable { return null; addAspect(nodeId,CCConstants.CCM_ASPECT_METADATA_PRESETTING); - HashMap props = new HashMap<>(); + Map props = new HashMap<>(); props.put(CCConstants.CM_NAME,new String[]{CCConstants.TEMPLATE_NODE_NAME}); - String id=createNode(nodeId,CCConstants.CCM_TYPE_IO,props); + String id=createNode(nodeId,CCConstants.CCM_TYPE_IO, props); nodeService.createAssociation(new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE,nodeId), new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE,id), assocQName); @@ -1375,11 +1374,11 @@ public String getTemplateNode(String nodeId,boolean create) throws Throwable { return id; } @Override - public void setTemplateProperties(String nodeId, HashMap props) throws Throwable { + public void setTemplateProperties(String nodeId, Map props) throws Throwable { //updateNode(getOrCreateTemplateNode(nodeId),props); String template = getTemplateNode(nodeId,true); String nodeType = getType(template); - HashMap toSafeProps = getToSafeProps(props,nodeType,null, template, nodeId,"io_template"); + Map toSafeProps = getToSafeProps(props, nodeType, null, template, nodeId, "io_template"); updateNodeNative(template, toSafeProps); } @@ -1479,7 +1478,7 @@ public void revertVersion(String nodeId, String verLbl) throws Exception { } @Override - public HashMap> getVersionHistory(String nodeId) throws Throwable { + public Map> getVersionHistory(String nodeId) throws Throwable { return apiClient.getVersionHistory(nodeId); } @@ -1588,7 +1587,7 @@ public void setProperty(String protocol, String storeId, String nodeId, String p } @Override - public GetPreviewResult getPreview(String storeProtocol, String storeIdentifier, String nodeId, HashMap nodeProps, String version){ + public GetPreviewResult getPreview(String storeProtocol, String storeIdentifier, String nodeId, Map nodeProps, String version){ boolean isIcon; if(nodeProps == null) { NodeRef nodeRef = new NodeRef(new StoreRef(storeProtocol, storeIdentifier), nodeId); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/nodeservice/NodeServiceLAppsImpl.java b/Backend/services/core/src/main/java/org/edu_sharing/service/nodeservice/NodeServiceLAppsImpl.java index 1f23287caa..8df9fdb971 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/nodeservice/NodeServiceLAppsImpl.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/nodeservice/NodeServiceLAppsImpl.java @@ -8,11 +8,7 @@ import java.time.LocalDateTime; import java.time.ZoneId; import java.time.format.DateTimeFormatter; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; +import java.util.*; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; @@ -45,7 +41,7 @@ public NodeServiceLAppsImpl(String appId) { } @Override - public HashMap getProperties(String storeProtocol, String storeId, String nodeId) throws Throwable { + public Map getProperties(String storeProtocol, String storeId, String nodeId) throws Throwable { String path = "getappbyid="+nodeId; @@ -77,8 +73,8 @@ public HashMap getProperties(String storeProtocol, String storeI return getPropertiesForNode(this.appId,map); } - public static HashMap getPropertiesForNode(String appId, NamedNodeMap map) { - HashMap properties=new HashMap<>(); + public static Map getPropertiesForNode(String appId, NamedNodeMap map) { + Map properties=new HashMap<>(); properties.put(CCConstants.SYS_PROP_NODE_UID,map.getNamedItem("id").getNodeValue()); properties.put(CCConstants.LOM_PROP_GENERAL_TITLE,map.getNamedItem("title").getNodeValue()); @@ -141,4 +137,4 @@ public boolean verify(String hostname, SSLSession session) { }); return connection; } -} \ No newline at end of file +} diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/nodeservice/NodeServiceMemuchoImpl.java b/Backend/services/core/src/main/java/org/edu_sharing/service/nodeservice/NodeServiceMemuchoImpl.java index 57cbe000cd..471374e002 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/nodeservice/NodeServiceMemuchoImpl.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/nodeservice/NodeServiceMemuchoImpl.java @@ -1,6 +1,7 @@ package org.edu_sharing.service.nodeservice; -import java.util.HashMap; +import java.util.Map; + import org.edu_sharing.service.search.SearchServiceMemuchoImpl; public class NodeServiceMemuchoImpl extends NodeServiceAdapter{ @@ -13,11 +14,11 @@ public NodeServiceMemuchoImpl(String appId) { } @Override - public HashMap getProperties(String storeProtocol, String storeId, String nodeId) throws Throwable { + public Map getProperties(String storeProtocol, String storeId, String nodeId) throws Throwable { SearchServiceMemuchoImpl searchservice = new SearchServiceMemuchoImpl(this.appId); return null;//searchservice.getProperties(nodeId); } -} \ No newline at end of file +} diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/nodeservice/NodeServiceOCAImpl.java b/Backend/services/core/src/main/java/org/edu_sharing/service/nodeservice/NodeServiceOCAImpl.java index 8962457e8d..7c4a9968ea 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/nodeservice/NodeServiceOCAImpl.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/nodeservice/NodeServiceOCAImpl.java @@ -1,6 +1,7 @@ package org.edu_sharing.service.nodeservice; -import java.util.HashMap; +import java.util.Map; + import org.edu_sharing.service.search.SearchServiceOCartImpl; public class NodeServiceOCAImpl extends NodeServiceAdapter{ @@ -13,11 +14,11 @@ public NodeServiceOCAImpl(String appId) { } @Override - public HashMap getProperties(String storeProtocol, String storeId, String nodeId) throws Throwable { + public Map getProperties(String storeProtocol, String storeId, String nodeId) throws Throwable { SearchServiceOCartImpl searchservice = new SearchServiceOCartImpl (this.appId); return searchservice.getProperties(nodeId); } -} \ No newline at end of file +} diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/nodeservice/NodeServicePixabayImpl.java b/Backend/services/core/src/main/java/org/edu_sharing/service/nodeservice/NodeServicePixabayImpl.java index 980116307b..78977d0557 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/nodeservice/NodeServicePixabayImpl.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/nodeservice/NodeServicePixabayImpl.java @@ -1,13 +1,12 @@ package org.edu_sharing.service.nodeservice; import java.io.InputStream; -import java.net.HttpURLConnection; import java.net.URL; import java.util.HashMap; +import java.util.Map; import javax.net.ssl.HttpsURLConnection; -import org.apache.commons.collections.map.LRUMap; import org.apache.log4j.Logger; import org.edu_sharing.repository.client.tools.CCConstants; import org.edu_sharing.repository.server.SearchResultNodeRef; @@ -15,8 +14,6 @@ import org.edu_sharing.repository.server.tools.ApplicationInfoList; import org.edu_sharing.service.search.SearchServicePixabayImpl; -import com.google.common.collect.MapMaker; - public class NodeServicePixabayImpl extends NodeServiceAdapterCached{ private String repositoryId; @@ -33,7 +30,7 @@ public NodeServicePixabayImpl(String appId) { @Override public InputStream getContent(String nodeId) throws Throwable { try { - HashMap properties = getProperties(null, null, nodeId); + Map properties = getProperties(null, null, nodeId); String download = (String) properties.get(CCConstants.CCM_PROP_IO_THUMBNAILURL); URL url = new URL(download); HttpsURLConnection connection = SearchServicePixabayImpl.openPixabayUrl(url); @@ -52,8 +49,8 @@ public InputStream getContent(String nodeId) throws Throwable { } } @Override - public HashMap getProperties(String storeProtocol, String storeId, String nodeId) throws Throwable { - HashMap props = super.getProperties(storeProtocol, storeId, nodeId); + public Map getProperties(String storeProtocol, String storeId, String nodeId) throws Throwable { + Map props = super.getProperties(storeProtocol, storeId, nodeId); if(props != null) { return props; } diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/nodeservice/NodeServiceTutoryImpl.java b/Backend/services/core/src/main/java/org/edu_sharing/service/nodeservice/NodeServiceTutoryImpl.java index d999514e49..1fb0b8a289 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/nodeservice/NodeServiceTutoryImpl.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/nodeservice/NodeServiceTutoryImpl.java @@ -1,6 +1,7 @@ package org.edu_sharing.service.nodeservice; import java.util.HashMap; +import java.util.Map; import org.edu_sharing.repository.client.tools.CCConstants; import org.edu_sharing.service.search.SearchServiceTutoryImpl; @@ -15,12 +16,12 @@ public NodeServiceTutoryImpl(String appId) { } @Override - public HashMap getProperties(String storeProtocol, String storeId, String nodeId) throws Throwable { + public Map getProperties(String storeProtocol, String storeId, String nodeId) throws Throwable { String httpResult = SearchServiceTutoryImpl.getHttpResult("https://www.tutory.de/api/v1/worksheet/" + nodeId); JSONObject worksheet = new JSONObject(httpResult); - HashMap properties = SearchServiceTutoryImpl.getProperties(worksheet); + Map properties = SearchServiceTutoryImpl.getProperties(worksheet); properties.put(CCConstants.REPOSITORY_ID, this.appId); return properties; diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/nodeservice/NodeServiceYouTube.java b/Backend/services/core/src/main/java/org/edu_sharing/service/nodeservice/NodeServiceYouTube.java index 54dbf70090..5eaf755fe3 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/nodeservice/NodeServiceYouTube.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/nodeservice/NodeServiceYouTube.java @@ -5,8 +5,8 @@ import java.util.Date; import java.util.HashMap; import java.util.List; +import java.util.Map; -import org.apache.http.HttpRequest; import org.edu_sharing.repository.client.tools.CCConstants; import org.edu_sharing.repository.client.tools.forms.VCardTool; import org.edu_sharing.repository.server.tools.ApplicationInfo; @@ -36,18 +36,12 @@ public NodeServiceYouTube(String appId) { } @Override - public HashMap getProperties(String storeProtocol, String storeId, String nodeId) throws Throwable { + public Map getProperties(String storeProtocol, String storeId, String nodeId) throws Throwable { return getProperties(nodeId); } - private HashMap getProperties(String nodeId) throws Throwable { - YouTube youtube = new YouTube.Builder(new NetHttpTransport(), new JacksonFactory(), new HttpRequestInitializer() { - public void initialize(HttpRequest request) throws IOException { - } - - @Override - public void initialize(com.google.api.client.http.HttpRequest arg0) throws IOException { - } - }).setApplicationName("youtube-cmdline-search-sample").build(); + private Map getProperties(String nodeId) throws Throwable { + YouTube youtube = new YouTube.Builder(new NetHttpTransport(), new JacksonFactory(), arg -> { + }).setApplicationName("youtube-cmdline-search-sample").build(); Videos.List list = youtube.videos().list("id,snippet"); list.setId(nodeId); list.setKey(googleAPIKey); @@ -64,8 +58,8 @@ public void initialize(com.google.api.client.http.HttpRequest arg0) throws IOExc return null; } - public static HashMap getPropsByVideoEntry(String repositoryId,GenericJson searchResult) { - HashMap properties = new HashMap(); + public static Map getPropsByVideoEntry(String repositoryId,GenericJson searchResult) { + Map properties = new HashMap<>(); String esrId = null; String esrTitle = null; diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/nodeservice/PropertiesInterceptorFactory.java b/Backend/services/core/src/main/java/org/edu_sharing/service/nodeservice/PropertiesInterceptorFactory.java index 1b696134f0..78ffc9f70f 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/nodeservice/PropertiesInterceptorFactory.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/nodeservice/PropertiesInterceptorFactory.java @@ -5,9 +5,8 @@ import org.edu_sharing.alfresco.lightbend.LightbendConfigLoader; import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; import java.util.Map; +import java.util.List; import java.util.function.Supplier; import java.util.stream.Collectors; @@ -83,7 +82,7 @@ public static void refresh(){ propertiesSetInterceptors = null; } - public static PropertiesGetInterceptor.PropertiesContext getPropertiesContext(NodeRef nodeRef, Map properties, List aspects, HashMap permissions, Map elasticsearchSource){ + public static PropertiesGetInterceptor.PropertiesContext getPropertiesContext(NodeRef nodeRef, Map properties, List aspects, Map permissions, Map elasticsearchSource){ PropertiesGetInterceptor.PropertiesContext propertiesContext = new PropertiesGetInterceptor.PropertiesContext(); propertiesContext.setProperties(properties); propertiesContext.setAspects(aspects); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/notification/NotificationService.java b/Backend/services/core/src/main/java/org/edu_sharing/service/notification/NotificationService.java index 48d023a8a2..6ff1ca78bd 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/notification/NotificationService.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/notification/NotificationService.java @@ -41,7 +41,7 @@ public interface NotificationService { @Permission(requiresUser = true) default NotificationConfig getConfig() throws Exception { - HashMap info = new MCAlfrescoAPIClient().getUserInfo(AuthenticationUtil.getFullyAuthenticatedUser()); + Map info = new MCAlfrescoAPIClient().getUserInfo(AuthenticationUtil.getFullyAuthenticatedUser()); if (!StringUtils.isEmpty(info.get(CCConstants.CCM_PROP_PERSON_NOTIFICATION_PREFERENCES))) { return new ObjectMapper().readValue(info.get(CCConstants.CCM_PROP_PERSON_NOTIFICATION_PREFERENCES), NotificationConfig.class); } @@ -50,7 +50,7 @@ default NotificationConfig getConfig() throws Exception { @Permission(requiresUser = true) default void setConfig(NotificationConfig config) throws Exception { - HashMap userInfo = new HashMap<>(); + Map userInfo = new HashMap<>(); userInfo.put(CCConstants.PROP_USERNAME, AuthenticationUtil.getFullyAuthenticatedUser()); userInfo.put(CCConstants.CCM_PROP_PERSON_NOTIFICATION_PREFERENCES, new ObjectMapper().writeValueAsString(config)); new MCAlfrescoAPIClient().updateUser(userInfo); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/notification/NotificationServiceImpl.java b/Backend/services/core/src/main/java/org/edu_sharing/service/notification/NotificationServiceImpl.java index 41643ba83a..45eaf3e4a3 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/notification/NotificationServiceImpl.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/notification/NotificationServiceImpl.java @@ -72,16 +72,16 @@ public void notifyNodeIssue(String nodeId, String reason, String nodeType, List< ); } try { - HashMap userProps = NodeServiceHelper.getProperties(AuthorityServiceFactory.getLocalService().getAuthorityNodeRef(AuthenticationUtil.getFullyAuthenticatedUser())); + Map userProps = NodeServiceHelper.getProperties(AuthorityServiceFactory.getLocalService().getAuthorityNodeRef(AuthenticationUtil.getFullyAuthenticatedUser())); MailTemplate.applyNodePropertiesToMap("user.", userProps, replace); SearchResult orgList = SearchServiceFactory.getLocalService().getAllOrganizations(true); if(!orgList.getData().isEmpty()) { - HashMap orgProps = NodeServiceHelper.getProperties(AuthorityServiceFactory.getLocalService().getAuthorityNodeRef(orgList.getData().get(0).getGroupname())); + Map orgProps = NodeServiceHelper.getProperties(AuthorityServiceFactory.getLocalService().getAuthorityNodeRef(orgList.getData().get(0).getGroupname())); MailTemplate.applyNodePropertiesToMap("user.organization.", orgProps, replace); } List mzList = SearchServiceFactory.getLocalService().getAllMediacenters(); if(!mzList.isEmpty()) { - HashMap mzProps = NodeServiceHelper.getProperties(AuthorityServiceFactory.getLocalService().getAuthorityNodeRef(mzList.get(0))); + Map mzProps = NodeServiceHelper.getProperties(AuthorityServiceFactory.getLocalService().getAuthorityNodeRef(mzList.get(0))); MailTemplate.applyNodePropertiesToMap("user.mediacenter.", mzProps, replace); } } catch (Throwable ignored) { diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/permission/PermissionService.java b/Backend/services/core/src/main/java/org/edu_sharing/service/permission/PermissionService.java index 7cd7586e56..fe6ac90c51 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/permission/PermissionService.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/permission/PermissionService.java @@ -25,7 +25,7 @@ public interface PermissionService { * @param _sendCopy * @throws Throwable */ - public void addPermissions(String _nodeId, HashMap _authPerm, + void addPermissions(String _nodeId, Map _authPerm, Boolean _inheritPermissions, String _mailText, Boolean _sendMail, Boolean _sendCopy) throws Throwable; @@ -41,11 +41,11 @@ public void addPermissions(String _nodeId, HashMap _authPerm, * @param sendCopy * @throws Throwable */ - public void setPermissions(String nodeId, List aces, Boolean inheritPermissions, + void setPermissions(String nodeId, List aces, Boolean inheritPermissions, String mailText, Boolean sendMail, Boolean sendCopy) throws Throwable; - public void createNotifyObject(final String nodeId, final String user, final String action); + void createNotifyObject(final String nodeId, final String user, final String action); void addToRecentProperty(String property, NodeRef elementAdd); @@ -56,47 +56,47 @@ public void setPermissions(String nodeId, List aces, Boolean inheritPermiss List getNotifyList(String nodeId) throws Throwable; - public void setPermissions(String nodeId, List aces, Boolean inheritPermission) throws Exception; + void setPermissions(String nodeId, List aces, Boolean inheritPermission) throws Exception; - public void setPermissions(String nodeId, List aces) throws Exception; + void setPermissions(String nodeId, List aces) throws Exception; - public void setPermissions(String nodeId, String authority, String[] permissions, Boolean inheritPermission) throws Exception; + void setPermissions(String nodeId, String authority, String[] permissions, Boolean inheritPermission) throws Exception; void setPermissionInherit(String nodeId, boolean inheritPermission) throws Exception; - public void addPermissions(String nodeId, ACE[] aces) throws Exception; + void addPermissions(String nodeId, ACE[] aces) throws Exception; - public void removePermissions(String nodeId, ACE[] aces) throws Exception; + void removePermissions(String nodeId, ACE[] aces) throws Exception; void removeAllPermissions(String nodeId) throws Exception; - public void removePermissions(String nodeId, String authority, String[] _permissions) throws Exception; + void removePermissions(String nodeId, String authority, String[] _permissions) throws Exception; StringBuffer getFindGroupsSearchString(String searchWord, boolean globalContext, boolean skipTpCheck); - public Result> findUsers(String query, Map searchFields, boolean globalContext, int from, int nrOfResults); + Result> findUsers(String query, Map searchFields, boolean globalContext, int from, int nrOfResults); StringBuffer getFindUsersSearchString(String query, Map searchFields, boolean globalContext); - public Result> findAuthorities(String searchWord, boolean globalContext, int from, int nrOfResults); + Result> findAuthorities(String searchWord, boolean globalContext, int from, int nrOfResults); - public Result> findGroups(String searchWord, boolean globalContext, int from, int nrOfResults); + Result> findGroups(String searchWord, boolean globalContext, int from, int nrOfResults); void addUserToSharedList(String user, NodeRef nodeRef); void cleanUpSharedList(NodeRef nodeRef); - public boolean hasPermission(String storeProtocol, String storeId, String nodeId, String permission); + boolean hasPermission(String storeProtocol, String storeId, String nodeId, String permission); - public boolean hasPermission(String storeProtocol, String storeId, String nodeId, String authority, String permission); + boolean hasPermission(String storeProtocol, String storeId, String nodeId, String authority, String permission); - HashMap hasAllPermissions(String storeProtocol, String storeId, String nodeId, String authority, + Map hasAllPermissions(String storeProtocol, String storeId, String nodeId, String authority, String[] permissions); - public HashMap hasAllPermissions(String storeProtocol, String storeId, String nodeId, String[] permissions); + Map hasAllPermissions(String storeProtocol, String storeId, String nodeId, String[] permissions); - public ACL getPermissions(String nodeId) throws Exception; - public List getPermissionsForAuthority(String nodeId,String authorityId, Collection permissions) throws InsufficientPermissionException; + ACL getPermissions(String nodeId) throws Exception; + List getPermissionsForAuthority(String nodeId,String authorityId, Collection permissions) throws InsufficientPermissionException; default List getPermissionsForAuthority(String nodeId,String authorityId) throws InsufficientPermissionException { return getPermissionsForAuthority(nodeId, authorityId, CCConstants.getPermissionList()); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/permission/PermissionServiceAdapter.java b/Backend/services/core/src/main/java/org/edu_sharing/service/permission/PermissionServiceAdapter.java index 12fdd5bbb1..be0013fe29 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/permission/PermissionServiceAdapter.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/permission/PermissionServiceAdapter.java @@ -17,7 +17,7 @@ public class PermissionServiceAdapter implements PermissionService { protected List ALLOWED_PERMISSIONS=new ArrayList<>(); @Override - public void addPermissions(String _nodeId, HashMap _authPerm, Boolean _inheritPermissions, + public void addPermissions(String _nodeId, Map _authPerm, Boolean _inheritPermissions, String _mailText, Boolean _sendMail, Boolean _sendCopy) throws Throwable { } @@ -120,9 +120,9 @@ public boolean hasPermission(String storeProtocol, String storeId, String nodeId } @Override - public HashMap hasAllPermissions(String storeProtocol, String storeId, String nodeId, + public Map hasAllPermissions(String storeProtocol, String storeId, String nodeId, String[] permissions) { - HashMap map = new HashMap(); + Map map = new HashMap<>(); for(String permission : permissions){ if(ALLOWED_PERMISSIONS.contains(permission)) map.put(permission, true); @@ -154,7 +154,7 @@ public boolean hasPermission(String storeProtocol, String storeId, String nodeId } @Override - public HashMap hasAllPermissions(String storeProtocol, String storeId, String nodeId, String authority, String[] permissions) { + public Map hasAllPermissions(String storeProtocol, String storeId, String nodeId, String authority, String[] permissions) { return null; } @Override diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/permission/PermissionServiceHelper.java b/Backend/services/core/src/main/java/org/edu_sharing/service/permission/PermissionServiceHelper.java index 95a11fae2c..cc5c3fddb3 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/permission/PermissionServiceHelper.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/permission/PermissionServiceHelper.java @@ -72,14 +72,14 @@ public void validatePermissionOrThrow(String nodeId, String permissionName) { throw new PermissionException(nodeId,permissionName); } - public HashMap hasAllPermissions(String storeProtocol,String storeId,String nodeId){ + public Map hasAllPermissions(String storeProtocol,String storeId,String nodeId){ return permissionService.hasAllPermissions(storeProtocol, storeId, nodeId, PERMISSIONS); } - public HashMap hasAllPermissions(String nodeId){ + public Map hasAllPermissions(String nodeId){ return hasAllPermissions(StoreRef.PROTOCOL_WORKSPACE,StoreRef.STORE_REF_WORKSPACE_SPACESSTORE.getIdentifier(), nodeId); } public static List getPermissionsAsString(Map hasPermissions){ - List result = new ArrayList(); + List result = new ArrayList<>(); for (String permission : PERMISSIONS) { diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/permission/PermissionServiceImpl.java b/Backend/services/core/src/main/java/org/edu_sharing/service/permission/PermissionServiceImpl.java index 6089b8c14b..c7434570d6 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/permission/PermissionServiceImpl.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/permission/PermissionServiceImpl.java @@ -130,7 +130,7 @@ public void setPermissions(String nodeId, List aces, Boolean inheritPermiss /** * remove the inherited from the old and new */ - List acesNew = new ArrayList(aces); + List acesNew = new ArrayList<>(aces); acesNew=addCollectionCoordinatorPermission(new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE,nodeId),acesNew); Iterator acesNewIter = acesNew.iterator(); while (acesNewIter.hasNext()) { @@ -140,7 +140,7 @@ public void setPermissions(String nodeId, List aces, Boolean inheritPermiss } } - List acesOld = new ArrayList(Arrays.asList(currentACL.getAces())); + List acesOld = new ArrayList<>(Arrays.asList(currentACL.getAces())); Iterator acesOldIter = acesOld.iterator(); while (acesOldIter.hasNext()) { ACE ace = acesOldIter.next(); @@ -149,10 +149,10 @@ public void setPermissions(String nodeId, List aces, Boolean inheritPermiss } } - List acesToAdd = new ArrayList(); - List acesToUpdate = new ArrayList(); - List acesToRemove = new ArrayList(); - List acesNotChanged = new ArrayList(); + List acesToAdd = new ArrayList<>(); + List acesToUpdate = new ArrayList<>(); + List acesToRemove = new ArrayList<>(); + List acesNotChanged = new ArrayList<>(); /** * remove the ones that are already set (didn't change) @@ -166,7 +166,7 @@ public void setPermissions(String nodeId, List aces, Boolean inheritPermiss } } - List aceOldAuthorityList = new ArrayList(); + List aceOldAuthorityList = new ArrayList<>(); for (ACE aceOld : acesOld) { aceOldAuthorityList.add(aceOld.getAuthority()); } @@ -186,13 +186,13 @@ public void setPermissions(String nodeId, List aces, Boolean inheritPermiss boolean createNotify = false; if (acesToAdd.size() > 0) { - HashMap authPermissions = new HashMap(); + Map authPermissions = new HashMap<>(); for (ACE toAdd : acesToAdd) { String[] permissions = authPermissions.get(toAdd.getAuthority()); if (permissions == null) { permissions = new String[] { toAdd.getPermission() }; } else { - ArrayList plist = new ArrayList(Arrays.asList(permissions)); + ArrayList plist = new ArrayList<>(Arrays.asList(permissions)); plist.add(toAdd.getPermission()); permissions = plist.toArray(new String[plist.size()]); } @@ -270,7 +270,7 @@ public void setPermissions(String nodeId, List aces, Boolean inheritPermiss } @Override - public void addPermissions(String _nodeId, HashMap _authPerm, Boolean _inheritPermissions, + public void addPermissions(String _nodeId, Map _authPerm, Boolean _inheritPermissions, String _mailText, Boolean _sendMail, Boolean _sendCopy) throws Throwable { String user = new AuthenticationToolAPI().getCurrentUser(); @@ -291,7 +291,7 @@ public void addPermissions(String _nodeId, HashMap _authPerm, if (_sendMail) { String nodeType = eduNodeService.getType(StoreRef.PROTOCOL_WORKSPACE, StoreRef.STORE_REF_WORKSPACE_SPACESSTORE.getIdentifier(), _nodeId); - HashMap props = eduNodeService.getProperties(StoreRef.PROTOCOL_WORKSPACE, StoreRef.STORE_REF_WORKSPACE_SPACESSTORE.getIdentifier(), _nodeId); + Map props = eduNodeService.getProperties(StoreRef.PROTOCOL_WORKSPACE, StoreRef.STORE_REF_WORKSPACE_SPACESSTORE.getIdentifier(), _nodeId); List aspects = Arrays.asList(eduNodeService.getAspects(StoreRef.PROTOCOL_WORKSPACE, StoreRef.STORE_REF_WORKSPACE_SPACESSTORE.getIdentifier(), _nodeId)); NotificationServiceFactoryUtility.getLocalService() .notifyPermissionChanged(user, authority, _nodeId, nodeType, aspects, props, permissions, _mailText); @@ -373,7 +373,7 @@ public int compare(Notify o1, Notify o2) { Gson gson = new Gson(); List jsonHistory = (List)nodeService.getProperty(new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE,nodeId),QName.createQName(CCConstants.CCM_PROP_PH_HISTORY)); - List notifyList = new ArrayList(); + List notifyList = new ArrayList<>(); if(jsonHistory != null) { for(String json : jsonHistory) { Notify notify = gson.fromJson(json, Notify.class); @@ -450,7 +450,7 @@ public void setPermissions(String nodeId, List aces, Boolean inheritPermiss } } - ArrayList toRemove = new ArrayList(); + ArrayList toRemove = new ArrayList<>(); Set allSetPerm = permissionsService.getAllSetPermissions(nodeRef); for (AccessPermission accessPerm : allSetPerm) { @@ -1120,7 +1120,7 @@ public Result> findUsers(String query,Map searchField searchParameters.addSort("@" + CCConstants.PROP_USER_EMAIL, true); ResultSet resultSet = searchService.query(searchParameters); - List data = new ArrayList(); + List data = new ArrayList<>(); for (NodeRef nodeRef : resultSet.getNodeRefs()) { User user = new User(); user.setEmail((String) nodeService.getProperty(nodeRef, ContentModel.PROP_EMAIL)); @@ -1185,7 +1185,7 @@ public Result> findAuthorities(String searchWord, boolean global System.out.println("finalQuery:" + finalQuery); - List data = new ArrayList(); + List data = new ArrayList<>(); SearchParameters searchParameters = new SearchParameters(); searchParameters.addStore(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE); @@ -1264,7 +1264,7 @@ public Result> findGroups(String searchWord, boolean globalContext, return new Result>(); } - List data = new ArrayList(); + List data = new ArrayList<>(); SearchParameters searchParameters = new SearchParameters(); searchParameters.addStore(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE); @@ -1351,7 +1351,7 @@ public void createNotifyObject(final String nodeId, final String user, final Str String jsonStringACL = gson.toJson(n); List history = (List) nodeService.getProperty(nodeRef, QName.createQName(CCConstants.CCM_PROP_PH_HISTORY)); - history = (history == null) ? new ArrayList() : history; + history = (history == null) ? new ArrayList<>() : history; while (history.size() > MAX_NOTIFY_HISTORY_LENGTH) { history.remove(0); } @@ -1377,7 +1377,7 @@ public void addUserToSharedList(String user, NodeRef nodeRef){ private void addUserToSharedList(String user, NodeRef nodeRef, Date created) { ArrayList phUsers = (ArrayList) nodeService.getProperty(nodeRef, QName.createQName(CCConstants.CCM_PROP_PH_USERS)); - if (phUsers == null) phUsers = new ArrayList(); + if (phUsers == null) phUsers = new ArrayList<>(); if (!phUsers.contains(user)) phUsers.add(user); nodeService.setProperty(nodeRef, QName.createQName(CCConstants.CCM_PROP_PH_USERS), phUsers); nodeService.setProperty(nodeRef, QName.createQName(CCConstants.CCM_PROP_PH_MODIFIED), created); @@ -1490,16 +1490,16 @@ public boolean hasPermission(String storeProtocol, String storeId, String nodeId return hasAllPermissions(storeProtocol,storeId,nodeId,authority,new String[]{permission}).get(permission); } @Override - public HashMap hasAllPermissions(String storeProtocol, String storeId, String nodeId, String authority, + public Map hasAllPermissions(String storeProtocol, String storeId, String nodeId, String authority, String[] permissions) { return AuthenticationUtil.runAs(()->hasAllPermissions(storeProtocol,storeId,nodeId,permissions),authority); } @Override - public HashMap hasAllPermissions(String storeProtocol, String storeId, String nodeId, + public Map hasAllPermissions(String storeProtocol, String storeId, String nodeId, String[] permissions) { boolean guest = GuestCagePolicy.getGuestUsers().contains(AuthenticationUtil.getFullyAuthenticatedUser()); PermissionService permissionService = serviceRegistry.getPermissionService(); - HashMap result = new HashMap(); + Map result = new HashMap<>(); NodeRef nodeRef = new NodeRef(new StoreRef(storeProtocol, storeId), nodeId); if (permissions != null && permissions.length > 0) { for (String permission : permissions) { diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/permission/PermissionServiceInterceptor.java b/Backend/services/core/src/main/java/org/edu_sharing/service/permission/PermissionServiceInterceptor.java index 705d9dd6d2..51c9bf2aa7 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/permission/PermissionServiceInterceptor.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/permission/PermissionServiceInterceptor.java @@ -34,14 +34,14 @@ public Object invoke(MethodInvocation invocation) throws Throwable { } return NodeServiceInterceptor.handleInvocation(nodeId, invocation, false); } else if (methodName.equals("hasAllPermissions")) { - HashMap result = (HashMap) invocation.proceed(); + Map result = (Map) invocation.proceed(); // to improve performance, if node seems to have any valid permissions, return true if (result.values().stream().anyMatch((v) -> v)) { return result; } // fetch all permissions but only allow the onces that are allowed for usages - result = (HashMap) NodeServiceInterceptor.handleInvocation(nodeId, invocation, false); - return new HashMap(result.entrySet().stream().map((e) -> { + result = (Map) NodeServiceInterceptor.handleInvocation(nodeId, invocation, false); + return new HashMap<>(result.entrySet().stream().map((e) -> { e.setValue(e.getValue() && CCConstants.getUsagePermissions().contains(e.getKey())); return e; }).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue))); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/provider/Provider.java b/Backend/services/core/src/main/java/org/edu_sharing/service/provider/Provider.java index b0e4860b61..a3b2003711 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/provider/Provider.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/provider/Provider.java @@ -26,6 +26,7 @@ import org.edu_sharing.spring.ApplicationContextFactory; import java.util.HashMap; +import java.util.Map; public abstract class Provider { protected final String appId; @@ -64,7 +65,7 @@ public CollectionService getCollectionService(){ /** * @Deprecated */ - public MCBaseClient getApiClient(HashMap auth){ + public MCBaseClient getApiClient(Map auth){ return new MCAlfrescoAPIClient(appId, auth); } public abstract SearchService getSearchService(); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/rating/RatingBase.java b/Backend/services/core/src/main/java/org/edu_sharing/service/rating/RatingBase.java index 405fe48c3f..df1bee7f4e 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/rating/RatingBase.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/rating/RatingBase.java @@ -4,18 +4,19 @@ import java.io.Serializable; import java.util.HashMap; +import java.util.Map; public class RatingBase implements Serializable { private RatingData overall; - private HashMap affiliation; + private Map affiliation; - public void setAffiliation(HashMap affiliation) { + public void setAffiliation(Map affiliation) { this.affiliation = affiliation; } - public HashMap getAffiliation() { + public Map getAffiliation() { return affiliation; } diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/rating/RatingServiceImpl.java b/Backend/services/core/src/main/java/org/edu_sharing/service/rating/RatingServiceImpl.java index 039bf94d62..e939beb333 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/rating/RatingServiceImpl.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/rating/RatingServiceImpl.java @@ -64,7 +64,7 @@ public void addOrUpdateRating(String nodeId, Double rating, String text) throws checkPreconditions(nodeId); AuthenticationUtil.runAsSystem(() -> { Rating currentRating = getRatingForUser(nodeId); - HashMap props = new HashMap<>(); + Map props = new HashMap<>(); props.put(CCConstants.CCM_PROP_RATING_VALUE, rating); props.put(CCConstants.CCM_PROP_RATING_TEXT, text); if (currentRating == null) { @@ -77,7 +77,7 @@ public void addOrUpdateRating(String nodeId, Double rating, String text) throws String nodeType = null; List nodeAspects; - HashMap nodeProps; + Map nodeProps; try { nodeType = nodeService.getType(StoreRef.PROTOCOL_WORKSPACE, StoreRef.STORE_REF_WORKSPACE_SPACESSTORE.getIdentifier(), nodeId); nodeAspects = Arrays.asList(nodeService.getAspects(StoreRef.PROTOCOL_WORKSPACE, StoreRef.STORE_REF_WORKSPACE_SPACESSTORE.getIdentifier(), nodeId)); @@ -134,7 +134,7 @@ public void deleteRating(String nodeId) throws Exception { String nodeType = null; List nodeAspects; - HashMap nodeProps; + Map nodeProps; try { nodeType = nodeService.getType(StoreRef.PROTOCOL_WORKSPACE, StoreRef.STORE_REF_WORKSPACE_SPACESSTORE.getIdentifier(), nodeId); nodeAspects = Arrays.asList(nodeService.getAspects(StoreRef.PROTOCOL_WORKSPACE, StoreRef.STORE_REF_WORKSPACE_SPACESSTORE.getIdentifier(), nodeId)); @@ -179,7 +179,7 @@ public RatingDetails getAccumulatedRatings(org.edu_sharing.service.model.NodeRef RatingsCache accumulated = new RatingsCache(); accumulated.setOverall(new RatingsCache.RatingData(ratings.stream().map(Rating::getRating).reduce(Double::sum).orElse(0.), ratings.size())); accumulated.setUsers(new HashMap<>(ratings.stream().collect(Collectors.toMap(Rating::getAuthority, Rating::getRating)))); - HashMap affiliation = new HashMap<>(); + Map affiliation = new HashMap<>(); // collect counts for each affiliation group ratings.forEach((r) -> { String authorityAffiliation = (String) authorityService.getAuthorityProperty(r.getAuthority(), CCConstants.CM_PROP_PERSON_EDU_SCHOOL_PRIMARY_AFFILIATION); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/rating/RatingsCache.java b/Backend/services/core/src/main/java/org/edu_sharing/service/rating/RatingsCache.java index ecfda0f93d..b338f0d4fe 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/rating/RatingsCache.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/rating/RatingsCache.java @@ -3,19 +3,19 @@ import io.swagger.v3.oas.annotations.media.Schema; import java.io.Serializable; -import java.util.HashMap; +import java.util.Map; @Schema public class RatingsCache extends RatingBase implements Serializable { // ratings per user/authority - private HashMap users; + private Map users; - public void setUsers(HashMap users) { + public void setUsers(Map users) { this.users = users; } - public HashMap getUsers() { + public Map getUsers() { return users; } } diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/register/RegisterServiceImpl.java b/Backend/services/core/src/main/java/org/edu_sharing/service/register/RegisterServiceImpl.java index fb7aa9455f..7dff630180 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/register/RegisterServiceImpl.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/register/RegisterServiceImpl.java @@ -179,7 +179,7 @@ public String activate(String key) throws Throwable { private void authenticate(RegisterInformation info) throws Exception { AuthenticationTool authTool=new AuthenticationToolAPI(); - HashMap validatedAuth = authTool.createNewSession(info.getAuthorityName(), info.getPassword()); + Map validatedAuth = authTool.createNewSession(info.getAuthorityName(), info.getPassword()); authTool.storeAuthInfoInSession(info.getAuthorityName(), validatedAuth.get(CCConstants.AUTH_TICKET),CCConstants.AUTH_TYPE_DEFAULT, Context.getCurrentInstance().getRequest().getSession(true)); authService.authenticate(info.getAuthorityName(),info.getPassword().toCharArray()); } diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/relations/RelationTypeUtil.java b/Backend/services/core/src/main/java/org/edu_sharing/service/relations/RelationTypeUtil.java index b78e413af2..19d745e91c 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/relations/RelationTypeUtil.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/relations/RelationTypeUtil.java @@ -4,7 +4,7 @@ import java.util.Map; public final class RelationTypeUtil { - private final static Map invertRelationTypeSet = new HashMap(){{ + private final static Map invertRelationTypeSet = new HashMap<>(){{ put(OutputRelationType.isBasisFor, OutputRelationType.isBasedOn); put(OutputRelationType.hasPart, OutputRelationType.isPartOf); put(OutputRelationType.references, OutputRelationType.references); @@ -12,7 +12,7 @@ public final class RelationTypeUtil { put(OutputRelationType.isPartOf, OutputRelationType.hasPart); }}; - private final static Map convertRelationTypeSet = new HashMap(){{ + private final static Map convertRelationTypeSet = new HashMap<>(){{ put(InputRelationType.references, OutputRelationType.references); put(InputRelationType.isBasedOn, OutputRelationType.isBasedOn); put(InputRelationType.isPartOf, OutputRelationType.isPartOf); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/remote/RemoteObjectService.java b/Backend/services/core/src/main/java/org/edu_sharing/service/remote/RemoteObjectService.java index 39e777d717..ca14c3f115 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/remote/RemoteObjectService.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/remote/RemoteObjectService.java @@ -25,236 +25,236 @@ public class RemoteObjectService { - Logger logger = Logger.getLogger(RemoteObjectService.class); - private ApplicationContext applicationContext = AlfAppContextGate.getApplicationContext(); - ServiceRegistry serviceRegistry = (ServiceRegistry) applicationContext.getBean(ServiceRegistry.SERVICE_REGISTRY); - private BehaviourFilter policyBehaviourFilter = (BehaviourFilter) applicationContext.getBean("policyBehaviourFilter"); + Logger logger = Logger.getLogger(RemoteObjectService.class); + private ApplicationContext applicationContext = AlfAppContextGate.getApplicationContext(); + ServiceRegistry serviceRegistry = (ServiceRegistry) applicationContext.getBean(ServiceRegistry.SERVICE_REGISTRY); + private BehaviourFilter policyBehaviourFilter = (BehaviourFilter) applicationContext.getBean("policyBehaviourFilter"); - /** - * creates and returns remoteObjectId when it's a 3dParty repo - * returns nodeId if its homeRepo - * @param repositoryId - * @param nodeId - * @return - */ - public String getRemoteObject(String repositoryId, String nodeId) { + /** + * creates and returns remoteObjectId when it's a 3dParty repo + * returns nodeId if its homeRepo + * + * @param repositoryId + * @param nodeId + * @return + */ + public String getRemoteObject(String repositoryId, String nodeId) { - return AuthenticationUtil.runAsSystem(() -> { - try { - ApplicationInfo repInfo = ApplicationInfoList.getRepositoryInfoById(repositoryId); - if (is3dPartyRepository(repInfo)) { - logger.info("repository " + repInfo.getAppId() + " is not HomeNode and No Alfresco"); + return AuthenticationUtil.runAsSystem(() -> { + try { + ApplicationInfo repInfo = ApplicationInfoList.getRepositoryInfoById(repositoryId); + if (is3dPartyRepository(repInfo)) { + logger.info("repository " + repInfo.getAppId() + " is not HomeNode and No Alfresco"); - MCAlfrescoBaseClient mcAlfrescoBaseClient = new MCAlfrescoAPIClient(); + MCAlfrescoBaseClient mcAlfrescoBaseClient = new MCAlfrescoAPIClient(); - org.edu_sharing.service.permission.PermissionService permissionService = PermissionServiceFactory - .getPermissionService(ApplicationInfoList.getHomeRepository().getAppId()); - String remoteObjectFolderId = null; - remoteObjectFolderId = getRemoteObjectsFolder(); + org.edu_sharing.service.permission.PermissionService permissionService = PermissionServiceFactory + .getPermissionService(ApplicationInfoList.getHomeRepository().getAppId()); + String remoteObjectFolderId = null; + remoteObjectFolderId = getRemoteObjectsFolder(); - // check for existing remote object - NodeRef existing = NodeServiceFactory.getLocalService().getChild(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, - remoteObjectFolderId, CCConstants.CCM_TYPE_REMOTEOBJECT, CCConstants.CCM_PROP_REMOTEOBJECT_NODEID, nodeId); - /*HashMap remoteObjectProps = mcAlfrescoBaseClient.getChild(remoteObjectFolderId, + // check for existing remote object + NodeRef existing = NodeServiceFactory.getLocalService().getChild(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, + remoteObjectFolderId, CCConstants.CCM_TYPE_REMOTEOBJECT, CCConstants.CCM_PROP_REMOTEOBJECT_NODEID, nodeId); + /*Map remoteObjectProps = mcAlfrescoBaseClient.getChild(remoteObjectFolderId, CCConstants.CCM_TYPE_REMOTEOBJECT, CCConstants.CCM_PROP_REMOTEOBJECT_NODEID, nodeId);*/ - HashMap remoteObjectProps; - String remoteObjectNodeId; - if (existing == null) { - logger.info("found no remote object for remote node id:" + nodeId + " creating new one"); - // create RemoteObject as system - remoteObjectProps = new HashMap<>(); - remoteObjectProps.put(CCConstants.CCM_PROP_REMOTEOBJECT_NODEID, nodeId); - remoteObjectProps.put(CCConstants.CCM_PROP_REMOTEOBJECT_REPOSITORY_TYPE, - repInfo.getRepositoryType()); - remoteObjectProps.put(CCConstants.CCM_PROP_REMOTEOBJECT_REPOSITORYID, repInfo.getAppId()); + Map remoteObjectProps; + String remoteObjectNodeId; + if (existing == null) { + logger.info("found no remote object for remote node id:" + nodeId + " creating new one"); + // create RemoteObject as system + remoteObjectProps = new HashMap<>(); + remoteObjectProps.put(CCConstants.CCM_PROP_REMOTEOBJECT_NODEID, nodeId); + remoteObjectProps.put(CCConstants.CCM_PROP_REMOTEOBJECT_REPOSITORY_TYPE, + repInfo.getRepositoryType()); + remoteObjectProps.put(CCConstants.CCM_PROP_REMOTEOBJECT_REPOSITORYID, repInfo.getAppId()); - remoteObjectNodeId = NodeServiceFactory.getLocalService().createNodeBasic(remoteObjectFolderId, - CCConstants.CCM_TYPE_REMOTEOBJECT, remoteObjectProps); - NodeService nodeService = NodeServiceFactory.getNodeService(repInfo.getAppId()); - InputStream content = nodeService.getContent(StoreRef.PROTOCOL_WORKSPACE, - StoreRef.STORE_REF_WORKSPACE_SPACESSTORE.getIdentifier(), nodeId, - null,CCConstants.CM_PROP_CONTENT); - HashMap properties = nodeService.getPropertiesPersisting(StoreRef.PROTOCOL_WORKSPACE, - StoreRef.STORE_REF_WORKSPACE_SPACESSTORE.getIdentifier(), nodeId); - if (content != null) { - // Store content from remote repo in node - NodeServiceFactory.getLocalService().writeContent( - StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, remoteObjectNodeId, content, - (String) properties.get(CCConstants.LOM_PROP_TECHNICAL_FORMAT), "UTF-8", - CCConstants.CM_PROP_CONTENT); - } - } else { - remoteObjectNodeId = existing.getId(); - } + remoteObjectNodeId = NodeServiceFactory.getLocalService().createNodeBasic(remoteObjectFolderId, + CCConstants.CCM_TYPE_REMOTEOBJECT, remoteObjectProps); + NodeService nodeService = NodeServiceFactory.getNodeService(repInfo.getAppId()); + InputStream content = nodeService.getContent(StoreRef.PROTOCOL_WORKSPACE, + StoreRef.STORE_REF_WORKSPACE_SPACESSTORE.getIdentifier(), nodeId, + null, CCConstants.CM_PROP_CONTENT); + Map properties = nodeService.getPropertiesPersisting(StoreRef.PROTOCOL_WORKSPACE, + StoreRef.STORE_REF_WORKSPACE_SPACESSTORE.getIdentifier(), nodeId); + if (content != null) { + // Store content from remote repo in node + NodeServiceFactory.getLocalService().writeContent( + StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, remoteObjectNodeId, content, + (String) properties.get(CCConstants.LOM_PROP_TECHNICAL_FORMAT), "UTF-8", + CCConstants.CM_PROP_CONTENT); + } + } else { + remoteObjectNodeId = existing.getId(); + } - // CLEANUP english? - // read rechte für den eigentlichen user auf das remote Object - // setzen, damit render service das checken kann + // CLEANUP english? + // read rechte für den eigentlichen user auf das remote Object + // setzen, damit render service das checken kann - String userName = (String) Context.getCurrentInstance().getRequest().getSession() - .getAttribute(CCConstants.AUTH_USERNAME); - permissionService.setPermissions(remoteObjectNodeId, userName, - new String[] { CCConstants.PERMISSION_ALL, CCConstants.PERMISSION_CC_PUBLISH }, true); + String userName = (String) Context.getCurrentInstance().getRequest().getSession() + .getAttribute(CCConstants.AUTH_USERNAME); + permissionService.setPermissions(remoteObjectNodeId, userName, + new String[]{CCConstants.PERMISSION_ALL, CCConstants.PERMISSION_CC_PUBLISH}, true); - return remoteObjectNodeId; + return remoteObjectNodeId; - } else { - return nodeId; - } + } else { + return nodeId; + } - } catch (Throwable t) { - throw new Exception(t); - } + } catch (Throwable t) { + throw new Exception(t); + } - }); + }); - } - - public HashMap getRemoteObjectProperties(String repositoryId, String nodeId){ - try { - String tmpNodeId = getRemoteObject(repositoryId, nodeId); - if(nodeId.equals(tmpNodeId)) { - return NodeServiceFactory.getNodeService(repositoryId).getProperties(MCAlfrescoAPIClient.storeRef.getProtocol(), MCAlfrescoAPIClient.storeRef.getIdentifier(), tmpNodeId); - }else { - HashMap props = new NodeServiceImpl(repositoryId).getProperties(MCAlfrescoAPIClient.storeRef.getProtocol(), MCAlfrescoAPIClient.storeRef.getIdentifier(), tmpNodeId); - props.putAll(NodeServiceFactory.getNodeService(repositoryId).getProperties(MCAlfrescoAPIClient.storeRef.getProtocol(), MCAlfrescoAPIClient.storeRef.getIdentifier(), tmpNodeId)); - return props; - } - }catch(Throwable e) { - logger.error(e.getMessage(), e); - return null; - } - } + } - private String getRemoteObjectsFolder() throws Throwable, Exception { + public Map getRemoteObjectProperties(String repositoryId, String nodeId) { + try { + String tmpNodeId = getRemoteObject(repositoryId, nodeId); + if (nodeId.equals(tmpNodeId)) { + return NodeServiceFactory.getNodeService(repositoryId).getProperties(MCAlfrescoAPIClient.storeRef.getProtocol(), MCAlfrescoAPIClient.storeRef.getIdentifier(), tmpNodeId); + } else { + Map props = new NodeServiceImpl(repositoryId).getProperties(MCAlfrescoAPIClient.storeRef.getProtocol(), MCAlfrescoAPIClient.storeRef.getIdentifier(), tmpNodeId); + props.putAll(NodeServiceFactory.getNodeService(repositoryId).getProperties(MCAlfrescoAPIClient.storeRef.getProtocol(), MCAlfrescoAPIClient.storeRef.getIdentifier(), tmpNodeId)); + return props; + } + } catch (Throwable e) { + logger.error(e.getMessage(), e); + return null; + } + } - MCAlfrescoAPIClient mcAlfrescoBaseClient = new MCAlfrescoAPIClient(); + private String getRemoteObjectsFolder() throws Throwable, Exception { - String remoteObjectFolderId = null; - String companyHomeId = mcAlfrescoBaseClient.getCompanyHomeNodeId(); - HashMap defaultRemoteFolderProps = mcAlfrescoBaseClient.getChild(companyHomeId, - CCConstants.CCM_TYPE_MAP, CCConstants.CM_NAME, CCConstants.CC_DEFAULT_REMOTEOBJECT_FOLDER_NAME); - if (defaultRemoteFolderProps == null) { + MCAlfrescoAPIClient mcAlfrescoBaseClient = new MCAlfrescoAPIClient(); - HashMap newDefaultRemoteFolderProps = new HashMap(); - newDefaultRemoteFolderProps.put(CCConstants.CM_NAME, CCConstants.CC_DEFAULT_REMOTEOBJECT_FOLDER_NAME); - newDefaultRemoteFolderProps.put(CCConstants.CM_PROP_C_TITLE, CCConstants.CC_DEFAULT_REMOTEOBJECT_FOLDER_NAME); - String newRemoteFolderId = mcAlfrescoBaseClient.createNode(companyHomeId, CCConstants.CCM_TYPE_MAP, newDefaultRemoteFolderProps); + String remoteObjectFolderId = null; + String companyHomeId = mcAlfrescoBaseClient.getCompanyHomeNodeId(); + Map defaultRemoteFolderProps = mcAlfrescoBaseClient.getChild(companyHomeId, + CCConstants.CCM_TYPE_MAP, CCConstants.CM_NAME, CCConstants.CC_DEFAULT_REMOTEOBJECT_FOLDER_NAME); + if (defaultRemoteFolderProps == null) { - if (newRemoteFolderId != null) { - remoteObjectFolderId = newRemoteFolderId; - } else { - logger.error("Could not create default Data Folder"); - } - } else { - remoteObjectFolderId = (String) defaultRemoteFolderProps.get(CCConstants.SYS_PROP_NODE_UID); - } - return remoteObjectFolderId; + Map newDefaultRemoteFolderProps = new HashMap<>(); + newDefaultRemoteFolderProps.put(CCConstants.CM_NAME, CCConstants.CC_DEFAULT_REMOTEOBJECT_FOLDER_NAME); + newDefaultRemoteFolderProps.put(CCConstants.CM_PROP_C_TITLE, CCConstants.CC_DEFAULT_REMOTEOBJECT_FOLDER_NAME); + String newRemoteFolderId = mcAlfrescoBaseClient.createNode(companyHomeId, CCConstants.CCM_TYPE_MAP, newDefaultRemoteFolderProps); - } + if (newRemoteFolderId != null) { + remoteObjectFolderId = newRemoteFolderId; + } else { + logger.error("Could not create default Data Folder"); + } + } else { + remoteObjectFolderId = (String) defaultRemoteFolderProps.get(CCConstants.SYS_PROP_NODE_UID); + } + return remoteObjectFolderId; - private boolean is3dPartyRepository(ApplicationInfo repInfo) { - return !repInfo.ishomeNode() && !repInfo.isRemoteAlfresco(); - } + } - public static synchronized String getOrCreateRemoteMetadataObject(String sourceRepositoryId, String originalNodeId) throws Throwable { - String ROOT_PATH = "/app:company_home/ccm:remote_ios"; - ApplicationInfo repInfo = ApplicationInfoList.getRepositoryInfoById(sourceRepositoryId); - NodeService nsSourceRepo = NodeServiceFactory.getNodeService(sourceRepositoryId); - HashMap propsIn = nsSourceRepo.getPropertiesPersisting(null, null, originalNodeId); - if(propsIn == null || propsIn.size() == 0) { - throw new Exception("no properties found for source nodeId:" + originalNodeId + ", appId: " + sourceRepositoryId); - } - if(propsIn.containsKey(CCConstants.CM_NAME)) { - propsIn.put(CCConstants.CM_NAME, - NodeServiceHelper.cleanupCmName((String) propsIn.get(CCConstants.CM_NAME) + "_" + UUID.randomUUID()) - ); - } - String importMds = repInfo.getString(ApplicationInfo.KEY_IMPORT_METADATASET, null); - if(importMds != null && !importMds.isEmpty()){ - // use the specified metadataset for imports - propsIn.put(CCConstants.CM_PROP_METADATASET_EDU_METADATASET, importMds); - } else { - // set the metadataset to keep the rendering of metadata consistent - propsIn.put(CCConstants.CM_PROP_METADATASET_EDU_METADATASET, repInfo.getMetadatsets()[0]); - } - // set the wwwurl so that the rendering will redirect to the source - // @TODO: Check behaviour for each connected repository type - // propsIn.put(CCConstants.CCM_PROP_IO_WWWURL, propsIn.get(CCConstants.LOM_PROP_TECHNICAL_LOCATION)); + private boolean is3dPartyRepository(ApplicationInfo repInfo) { + return !repInfo.ishomeNode() && !repInfo.isRemoteAlfresco(); + } - // set the metadataset to keep the rendering of metadata consistent - propsIn.put(CCConstants.CM_PROP_METADATASET_EDU_METADATASET, repInfo.getMetadatsets()[0]); - // We also need to store repository information for remote edu-sharing objects - propsIn.put(CCConstants.CCM_PROP_REMOTEOBJECT_NODEID, originalNodeId); - propsIn.put(CCConstants.CCM_PROP_REMOTEOBJECT_REPOSITORY_TYPE, repInfo.getRepositoryType()); - propsIn.put(CCConstants.CCM_PROP_REMOTEOBJECT_REPOSITORYID, repInfo.getAppId()); - // remove illegal data - HashMap props = cleanupRemoteProperties(propsIn); - return AuthenticationUtil.runAsSystem(() -> { - try { - Map searchProps = new HashMap<>(); - searchProps.put(CCConstants.CCM_PROP_REMOTEOBJECT_NODEID, originalNodeId); - searchProps.put(CCConstants.CCM_PROP_REMOTEOBJECT_REPOSITORYID, repInfo.getAppId()); - NodeService nodeService = NodeServiceFactory.getLocalService(); - String root = NodeServiceHelper.getContainerRootPath(ROOT_PATH); - // allow everyone to cc publish from this folder - PermissionServiceFactory.getLocalService().setPermissions(root, CCConstants.AUTHORITY_GROUP_EVERYONE, - new String[]{CCConstants.PERMISSION_CONSUMER, CCConstants.PERMISSION_CC_PUBLISH}, false); - List nodes = NodeServiceHelper.findNodeByPropertiesRecursive( - new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, - root), - Collections.singletonList(CCConstants.CCM_TYPE_IO), - searchProps); - if(nodes.size()>1){ - throw new Exception("For remote node "+originalNodeId+" where found "+nodes.size()+" local objects, invalid state!"); - } - if(nodes.size()==0) { - // create - ApplicationContext applicationContext = AlfAppContextGate.getApplicationContext(); - ServiceRegistry serviceRegistry = (ServiceRegistry) applicationContext.getBean(ServiceRegistry.SERVICE_REGISTRY); - BehaviourFilter policyBehaviourFilter = (BehaviourFilter) applicationContext.getBean("policyBehaviourFilter"); - return serviceRegistry.getRetryingTransactionHelper().doInTransaction(() -> { - String containerId = NodeServiceHelper.getContainerIdByPath(ROOT_PATH, "yyyy/MM/dd"); - props.put(CCConstants.CCM_PROP_IO_VERSION_COMMENT, CCConstants.VERSION_COMMENT_REMOTE_OBJECT_INIT); - String nodeId = nodeService.createNodeBasic(containerId, CCConstants.CCM_TYPE_IO, props); - NodeRef ref = new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, nodeId); + public static synchronized String getOrCreateRemoteMetadataObject(String sourceRepositoryId, String originalNodeId) throws Throwable { + String ROOT_PATH = "/app:company_home/ccm:remote_ios"; + ApplicationInfo repInfo = ApplicationInfoList.getRepositoryInfoById(sourceRepositoryId); + NodeService nsSourceRepo = NodeServiceFactory.getNodeService(sourceRepositoryId); + Map propsIn = nsSourceRepo.getPropertiesPersisting(null, null, originalNodeId); + if (propsIn == null || propsIn.size() == 0) { + throw new Exception("no properties found for source nodeId:" + originalNodeId + ", appId: " + sourceRepositoryId); + } + if (propsIn.containsKey(CCConstants.CM_NAME)) { + propsIn.put(CCConstants.CM_NAME, + NodeServiceHelper.cleanupCmName((String) propsIn.get(CCConstants.CM_NAME) + "_" + UUID.randomUUID()) + ); + } + String importMds = repInfo.getString(ApplicationInfo.KEY_IMPORT_METADATASET, null); + if (importMds != null && !importMds.isEmpty()) { + // use the specified metadataset for imports + propsIn.put(CCConstants.CM_PROP_METADATASET_EDU_METADATASET, importMds); + } else { + // set the metadataset to keep the rendering of metadata consistent + propsIn.put(CCConstants.CM_PROP_METADATASET_EDU_METADATASET, repInfo.getMetadatsets()[0]); + } + // set the wwwurl so that the rendering will redirect to the source + // @TODO: Check behaviour for each connected repository type + // propsIn.put(CCConstants.CCM_PROP_IO_WWWURL, propsIn.get(CCConstants.LOM_PROP_TECHNICAL_LOCATION)); - policyBehaviourFilter.disableBehaviour(ref); - // admin is the owner, not the current user - nodeService.setOwner(nodeId, ApplicationInfoList.getHomeRepository().getUsername()); - NodeServiceHelper.setProperty(ref, CCConstants.CM_PROP_C_CREATOR, ApplicationInfoList.getHomeRepository().getUsername(), false); - NodeServiceHelper.setProperty(ref, CCConstants.CM_PROP_C_MODIFIER, ApplicationInfoList.getHomeRepository().getUsername(), false); - nodeService.createVersion(nodeId); - policyBehaviourFilter.enableBehaviour(ref); - return nodeId; - }); - } - else{ - // update in case metadata of remote source have changed - nodeService.updateNodeNative(nodes.get(0).getId(), props); - return nodes.get(0).getId(); - } - }catch(Throwable t){ - throw new RuntimeException(t); - } - }); - } + // set the metadataset to keep the rendering of metadata consistent + propsIn.put(CCConstants.CM_PROP_METADATASET_EDU_METADATASET, repInfo.getMetadatsets()[0]); + // We also need to store repository information for remote edu-sharing objects + propsIn.put(CCConstants.CCM_PROP_REMOTEOBJECT_NODEID, originalNodeId); + propsIn.put(CCConstants.CCM_PROP_REMOTEOBJECT_REPOSITORY_TYPE, repInfo.getRepositoryType()); + propsIn.put(CCConstants.CCM_PROP_REMOTEOBJECT_REPOSITORYID, repInfo.getAppId()); + // remove illegal data + Map props = cleanupRemoteProperties(propsIn); + return AuthenticationUtil.runAsSystem(() -> { + try { + Map searchProps = new HashMap<>(); + searchProps.put(CCConstants.CCM_PROP_REMOTEOBJECT_NODEID, originalNodeId); + searchProps.put(CCConstants.CCM_PROP_REMOTEOBJECT_REPOSITORYID, repInfo.getAppId()); + NodeService nodeService = NodeServiceFactory.getLocalService(); + String root = NodeServiceHelper.getContainerRootPath(ROOT_PATH); + // allow everyone to cc publish from this folder + PermissionServiceFactory.getLocalService().setPermissions(root, CCConstants.AUTHORITY_GROUP_EVERYONE, + new String[]{CCConstants.PERMISSION_CONSUMER, CCConstants.PERMISSION_CC_PUBLISH}, false); + List nodes = NodeServiceHelper.findNodeByPropertiesRecursive( + new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, + root), + Collections.singletonList(CCConstants.CCM_TYPE_IO), + searchProps); + if (nodes.size() > 1) { + throw new Exception("For remote node " + originalNodeId + " where found " + nodes.size() + " local objects, invalid state!"); + } + if (nodes.size() == 0) { + // create + ApplicationContext applicationContext = AlfAppContextGate.getApplicationContext(); + ServiceRegistry serviceRegistry = (ServiceRegistry) applicationContext.getBean(ServiceRegistry.SERVICE_REGISTRY); + BehaviourFilter policyBehaviourFilter = (BehaviourFilter) applicationContext.getBean("policyBehaviourFilter"); + return serviceRegistry.getRetryingTransactionHelper().doInTransaction(() -> { + String containerId = NodeServiceHelper.getContainerIdByPath(ROOT_PATH, "yyyy/MM/dd"); + props.put(CCConstants.CCM_PROP_IO_VERSION_COMMENT, CCConstants.VERSION_COMMENT_REMOTE_OBJECT_INIT); + String nodeId = nodeService.createNodeBasic(containerId, CCConstants.CCM_TYPE_IO, props); + NodeRef ref = new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, nodeId); - public static HashMap cleanupRemoteProperties(HashMap propsIn) { - HashMap props=new HashMap<>(propsIn); - props.remove(CCConstants.SYS_PROP_NODE_UID); - props.remove(CCConstants.NODECREATOR_EMAIL); - props.remove(CCConstants.NODECREATOR_FIRSTNAME); - props.remove(CCConstants.NODECREATOR_LASTNAME); - props.remove(CCConstants.NODEMODIFIER_EMAIL); - props.remove(CCConstants.NODEMODIFIER_FIRSTNAME); - props.remove(CCConstants.NODEMODIFIER_LASTNAME); - props.remove(CCConstants.CONTENTURL); - for(Map.Entry prop: propsIn.entrySet()){ - if(prop.getKey().startsWith("{virtualproperty}")) { - props.remove(prop.getKey()); - } - } - return props; - } + policyBehaviourFilter.disableBehaviour(ref); + // admin is the owner, not the current user + nodeService.setOwner(nodeId, ApplicationInfoList.getHomeRepository().getUsername()); + NodeServiceHelper.setProperty(ref, CCConstants.CM_PROP_C_CREATOR, ApplicationInfoList.getHomeRepository().getUsername(), false); + NodeServiceHelper.setProperty(ref, CCConstants.CM_PROP_C_MODIFIER, ApplicationInfoList.getHomeRepository().getUsername(), false); + nodeService.createVersion(nodeId); + policyBehaviourFilter.enableBehaviour(ref); + return nodeId; + }); + } else { + // update in case metadata of remote source have changed + nodeService.updateNodeNative(nodes.get(0).getId(), props); + return nodes.get(0).getId(); + } + } catch (Throwable t) { + throw new RuntimeException(t); + } + }); + } + + public static Map cleanupRemoteProperties(Map propsIn) { + Map props = new HashMap<>(propsIn); + props.remove(CCConstants.SYS_PROP_NODE_UID); + props.remove(CCConstants.NODECREATOR_EMAIL); + props.remove(CCConstants.NODECREATOR_FIRSTNAME); + props.remove(CCConstants.NODECREATOR_LASTNAME); + props.remove(CCConstants.NODEMODIFIER_EMAIL); + props.remove(CCConstants.NODEMODIFIER_FIRSTNAME); + props.remove(CCConstants.NODEMODIFIER_LASTNAME); + props.remove(CCConstants.CONTENTURL); + for (Map.Entry prop : propsIn.entrySet()) { + if (prop.getKey().startsWith("{virtualproperty}")) { + props.remove(prop.getKey()); + } + } + return props; + } } diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/rendering/RenderingServiceImpl.java b/Backend/services/core/src/main/java/org/edu_sharing/service/rendering/RenderingServiceImpl.java index 5258abf296..186b5aba9b 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/rendering/RenderingServiceImpl.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/rendering/RenderingServiceImpl.java @@ -56,7 +56,7 @@ public class RenderingServiceImpl implements RenderingService{ private final PermissionService permissionService; ApplicationInfo appInfo; - HashMap authInfo; + Map authInfo; AuthenticationTool authTool; @@ -79,7 +79,7 @@ public void setAppId(String appId) { || (guestUn != null && guestUn.equals(AuthenticationUtil.getFullyAuthenticatedUser()) )) { logger.debug("starting in runas user mode"); - this.authInfo = new HashMap(); + this.authInfo = new HashMap<>(); this.authInfo.put(CCConstants.AUTH_USERNAME, AuthenticationUtil.getRunAsUser()); }else { this.authInfo = this.authTool.validateAuthentication(Context.getCurrentInstance().getCurrentInstance().getRequest().getSession()); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/repoproxy/RepoProxy.java b/Backend/services/core/src/main/java/org/edu_sharing/service/repoproxy/RepoProxy.java index bbf778c7a5..3e86e2f277 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/repoproxy/RepoProxy.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/repoproxy/RepoProxy.java @@ -40,7 +40,7 @@ Response getChildren(String repository, String node, Integer maxItems, Integer s boolean myTurn(String repoId); RemoteRepoDetails myTurn(String repoId, String nodeId); - public HashMap remoteAuth(ApplicationInfo repoInfo, String username, boolean validate) throws Throwable; + Map remoteAuth(ApplicationInfo repoInfo, String username, boolean validate) throws Throwable; Response prepareUsage(String repository, String node, HttpServletRequest req) throws Throwable; @@ -70,4 +70,4 @@ public void setNodeId(String nodeId) { this.nodeId = nodeId; } } -} \ No newline at end of file +} diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/repoproxy/RepoProxyAbstract.java b/Backend/services/core/src/main/java/org/edu_sharing/service/repoproxy/RepoProxyAbstract.java index 3ac2f4de43..d909ca1a1c 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/repoproxy/RepoProxyAbstract.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/repoproxy/RepoProxyAbstract.java @@ -11,6 +11,7 @@ import org.edu_sharing.service.toolpermission.ToolPermissionServiceFactory; import java.util.HashMap; +import java.util.Map; public abstract class RepoProxyAbstract implements RepoProxy { @@ -62,7 +63,7 @@ public RemoteRepoDetails myTurn(String repoId, String node) { } @Override - public HashMap remoteAuth(ApplicationInfo repoInfo, String username, boolean validate) throws Throwable { + public Map remoteAuth(ApplicationInfo repoInfo, String username, boolean validate) throws Throwable { // TODO Auto-generated method stub return null; } diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/schoolcontext/SchoolContextServiceImpl.java b/Backend/services/core/src/main/java/org/edu_sharing/service/schoolcontext/SchoolContextServiceImpl.java index 332324b26a..410497b3e5 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/schoolcontext/SchoolContextServiceImpl.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/schoolcontext/SchoolContextServiceImpl.java @@ -48,7 +48,7 @@ public SchoolContextValues getSchoolConextValues(String nodeRefFederalState, Str MCAlfrescoBaseClient mcAlfrescoBaseClient = repoClient; SearchToken st = new SearchToken(); - ArrayList facettes = new ArrayList(); + ArrayList facettes = new ArrayList<>(); facettes.add(SchoolContext.PROP_REF_AGEGROUP); facettes.add(SchoolContext.PROP_REF_DISCIPLINE); facettes.add(SchoolContext.PROP_REF_FEDERALSTATE); @@ -130,11 +130,11 @@ public SchoolContextValues getSchoolConextValues(String nodeRefFederalState, Str } - private void fillSchoolContextValues(String type, HashMap targetMap, MCAlfrescoBaseClient mcAlfrescoBaseClient) throws Throwable{ + private void fillSchoolContextValues(String type, Map targetMap, MCAlfrescoBaseClient mcAlfrescoBaseClient) throws Throwable{ String query = "TYPE:\""+type+"\""; - ArrayList facette = new ArrayList(); + ArrayList facette = new ArrayList<>(); facette.add(CCConstants.SYS_PROP_NODE_UID); SearchResult srAG = mcAlfrescoBaseClient.searchSolr(query, 0, 0, facette, 1, 500000); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/search/SearchService.java b/Backend/services/core/src/main/java/org/edu_sharing/service/search/SearchService.java index 86476dc1a4..ed0e4b23e9 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/search/SearchService.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/search/SearchService.java @@ -10,7 +10,6 @@ import org.edu_sharing.service.search.model.*; import java.io.IOException; -import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; @@ -86,7 +85,7 @@ SearchResult searchUsers(String _pattern, boolean globalSearch, int _ski SearchResult searchPersonGroups(String authorityName, String pattern, int skipCount, int maxValues, SortDefinition sort); - HashMap getLastSearchTokens() throws Throwable; + Map getLastSearchTokens() throws Throwable; public default List getSuggestions(MetadataSet mds, String queryId, String parameterId, String value, List criterias) { return null; diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/search/SearchServiceAdapter.java b/Backend/services/core/src/main/java/org/edu_sharing/service/search/SearchServiceAdapter.java index ea3233ceac..5c43a992e9 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/search/SearchServiceAdapter.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/search/SearchServiceAdapter.java @@ -84,7 +84,7 @@ public SearchResult findAuthorities(AuthorityType user, String searchWor } @Override - public HashMap getLastSearchTokens() throws Throwable { + public Map getLastSearchTokens() throws Throwable { // TODO Auto-generated method stub return null; } diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/search/SearchServiceBrockhausImpl.java b/Backend/services/core/src/main/java/org/edu_sharing/service/search/SearchServiceBrockhausImpl.java index 4f63027c70..9dfb424666 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/search/SearchServiceBrockhausImpl.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/search/SearchServiceBrockhausImpl.java @@ -55,7 +55,7 @@ public SearchResultNodeRef searchBrockhaus(String path) throws Exception{ for(int i=0;i properties=new HashMap<>(); + Map properties=new HashMap<>(); // swagger doesn't like / as %2F encoded, so we try to prevent issues by mapping the data properties.put(CCConstants.SYS_PROP_NODE_UID,document.getString("url").replace("/","%2f")); properties.put(CCConstants.CM_PROP_C_MODIFIED,System.currentTimeMillis()); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/search/SearchServiceDDBImpl.java b/Backend/services/core/src/main/java/org/edu_sharing/service/search/SearchServiceDDBImpl.java index 8bff0835be..5f5dc51ece 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/search/SearchServiceDDBImpl.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/search/SearchServiceDDBImpl.java @@ -28,202 +28,205 @@ import java.util.*; import java.util.stream.Collectors; -public class SearchServiceDDBImpl extends SearchServiceAdapter{ - - public static final String DDB_API = "https://api.deutsche-digitale-bibliothek.de"; - - Logger logger = Logger.getLogger(SearchServiceDDBImpl.class); - - String repositoryId = null; - - String APIKey = null; - - private ApplicationInfo appInfo; - - - public SearchServiceDDBImpl(String appId) { - appInfo = ApplicationInfoList.getRepositoryInfoById(appId); - this.repositoryId = appInfo.getAppId(); - this.APIKey = appInfo.getApiKey(); - - } - - public static HttpsURLConnection openDDBUrl(URL url) throws KeyManagementException, IOException, NoSuchAlgorithmException{ - HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); - - // TODO! - TrustManager[] trustAllCerts = new TrustManager[]{ - new X509TrustManager() { - public java.security.cert.X509Certificate[] getAcceptedIssuers() { - return null; - } - public void checkClientTrusted( - java.security.cert.X509Certificate[] certs, String authType) { - } - public void checkServerTrusted( - java.security.cert.X509Certificate[] certs, String authType) { - } - } - }; - SSLContext sc = SSLContext.getInstance("SSL"); - sc.init(null, trustAllCerts, new java.security.SecureRandom()); - connection.setSSLSocketFactory(sc.getSocketFactory()); - connection.setHostnameVerifier(new HostnameVerifier() { - public boolean verify(String hostname, SSLSession session) { - return true; - } - }); - return connection; - } - public SearchResultNodeRef searchDDB(String repositoryId,String apiKey,String path) throws Exception{ - String jsonString = ""; - String urlAsStr = DDB_API+path; - jsonString = query(urlAsStr); - JSONObject jo = new JSONObject(jsonString); - Integer nrOfResult = (Integer)jo.get("numberOfResults"); - JSONArray resultsArr = (JSONArray)jo.get("results"); - JSONObject results = (JSONObject)resultsArr.get(0); - JSONArray docs = (JSONArray)results.get("docs"); - - - SearchResultNodeRef searchResultNodeRef = new SearchResultNodeRef(); - List data=new ArrayList<>(); - - HashMap> result = new HashMap>(); - for(int i = 0; i < docs.length(); i++){ - JSONObject doc = (JSONObject)docs.get(i); - String id = this.getNodeId(doc); - org.edu_sharing.service.model.NodeRef ref = new org.edu_sharing.service.model.NodeRefImpl( - repositoryId, - StoreRef.STORE_REF_WORKSPACE_SPACESSTORE.getProtocol(), - StoreRef.STORE_REF_WORKSPACE_SPACESSTORE.getIdentifier(), - id); - data.add(ref); - - } - searchResultNodeRef.setData(data); - searchResultNodeRef.setNodeCount(jo.getInt("numberOfResults")); - return searchResultNodeRef; - - } - - private String query(String urlAsStr) throws Exception { - URL url = new URL(urlAsStr); - HttpsURLConnection connection = openDDBUrl(url); - connection.connect(); - - InputStreamReader isr = new InputStreamReader(connection.getInputStream(), "UTF-8"); - BufferedReader br = new BufferedReader(isr); - StringBuilder sb = new StringBuilder(); - String line; - while ((line = br.readLine()) != null) { - sb.append(line); - } - br.close(); - isr.close(); - connection.disconnect(); - return sb.toString(); - } - - public static String httpGet(String urlStr, Map headers) throws IOException { - // open HTTP connection with URL - return new HttpQueryTool().query(urlStr, headers, new HttpGet(urlStr)); - } - - private String getNodeId(JSONObject doc){ - String id = null; - try { - id = (String)doc.get("id"); - } catch (JSONException e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); - } - return id; - } - - @Override - public List getSuggestions(MetadataSet mds, String queryId, String parameterId, String value, List criterias) { - List result = new ArrayList(); - - List facets = mds.findQuery(queryId, MetadataReader.QUERY_SYNTAX_LUCENE).findParameterByName(parameterId).getFacets(); - //String url = getUrl("/search",parameterId +":("+value+")",facets, 0, 0); - String url = getUrl("/search","*",facets, 0, 0); - System.out.println("url:" + url); - - try { - String json = this.query(url); - System.out.println(json); - JSONObject jo = new JSONObject(json); - - JSONArray resultsArr = (JSONArray)jo.get("facets"); - - for(int i = 0; i < resultsArr.length(); i++) { - JSONObject facetObj = (JSONObject)resultsArr.get(i); - String field = facetObj.getString("field"); - int numberOfFacets = facetObj.getInt("numberOfFacets"); - if(facets.contains(field) && numberOfFacets > 0) { - - JSONArray facetValues = facetObj.getJSONArray("facetValues"); - for(int j = 0; j < facetValues.length(); j++) { - JSONObject facetteVal = (JSONObject)facetValues.get(j); - //int count = facetteVal.getInt("count"); - String val = facetteVal.getString("value"); - - if(val.contains(value)) { - Suggestion dto = new Suggestion(); - dto.setKey(val); - dto.setDisplayString(val); - - result.add(dto); - } - } - - - } - } - - } catch (Exception e) { - logger.error(e.getMessage(),e); - } - return result; - } - - public String getUrl(String basePath, String query, List facets, int offset, int rows){ - String url = DDB_API + basePath; - - try { - url += "?oauth_consumer_key=" + URLEncoder.encode(APIKey, "UTF-8"); - } catch (UnsupportedEncodingException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - url += "&query=" + org.springframework.extensions.surf.util.URLEncoder.encodeUriComponent(query); - if(facets != null && facets.size() > 0) { - url += "&facet="; - int i = 0; - for(String facet : facets) { - if(i == 0) { - url += facet; - }else { - url += "," +facet; - } - - } - } - url += "&offset="+offset; - url += "&rows="+rows; - - return url; - } - - @Override - public SearchResultNodeRef search(MetadataSet mds, String query, Map criterias, - SearchToken searchToken) throws Throwable { - - - if(!MetadataSet.DEFAULT_CLIENT_QUERY.equals(query)){ - throw new Exception("Only ngsearch query is supported for this repository type, requested "+query); - } +public class SearchServiceDDBImpl extends SearchServiceAdapter { + + public static final String DDB_API = "https://api.deutsche-digitale-bibliothek.de"; + + Logger logger = Logger.getLogger(SearchServiceDDBImpl.class); + + String repositoryId = null; + + String APIKey = null; + + private ApplicationInfo appInfo; + + + public SearchServiceDDBImpl(String appId) { + appInfo = ApplicationInfoList.getRepositoryInfoById(appId); + this.repositoryId = appInfo.getAppId(); + this.APIKey = appInfo.getApiKey(); + + } + + public static HttpsURLConnection openDDBUrl(URL url) throws KeyManagementException, IOException, NoSuchAlgorithmException { + HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); + + // TODO! + TrustManager[] trustAllCerts = new TrustManager[]{ + new X509TrustManager() { + public java.security.cert.X509Certificate[] getAcceptedIssuers() { + return null; + } + + public void checkClientTrusted( + java.security.cert.X509Certificate[] certs, String authType) { + } + + public void checkServerTrusted( + java.security.cert.X509Certificate[] certs, String authType) { + } + } + }; + SSLContext sc = SSLContext.getInstance("SSL"); + sc.init(null, trustAllCerts, new java.security.SecureRandom()); + connection.setSSLSocketFactory(sc.getSocketFactory()); + connection.setHostnameVerifier(new HostnameVerifier() { + public boolean verify(String hostname, SSLSession session) { + return true; + } + }); + return connection; + } + + public SearchResultNodeRef searchDDB(String repositoryId, String apiKey, String path) throws Exception { + String jsonString = ""; + String urlAsStr = DDB_API + path; + jsonString = query(urlAsStr); + JSONObject jo = new JSONObject(jsonString); + Integer nrOfResult = (Integer) jo.get("numberOfResults"); + JSONArray resultsArr = (JSONArray) jo.get("results"); + JSONObject results = (JSONObject) resultsArr.get(0); + JSONArray docs = (JSONArray) results.get("docs"); + + + SearchResultNodeRef searchResultNodeRef = new SearchResultNodeRef(); + List data = new ArrayList<>(); + + Map> result = new HashMap<>(); + for (int i = 0; i < docs.length(); i++) { + JSONObject doc = (JSONObject) docs.get(i); + String id = this.getNodeId(doc); + org.edu_sharing.service.model.NodeRef ref = new org.edu_sharing.service.model.NodeRefImpl( + repositoryId, + StoreRef.STORE_REF_WORKSPACE_SPACESSTORE.getProtocol(), + StoreRef.STORE_REF_WORKSPACE_SPACESSTORE.getIdentifier(), + id); + data.add(ref); + + } + searchResultNodeRef.setData(data); + searchResultNodeRef.setNodeCount(jo.getInt("numberOfResults")); + return searchResultNodeRef; + + } + + private String query(String urlAsStr) throws Exception { + URL url = new URL(urlAsStr); + HttpsURLConnection connection = openDDBUrl(url); + connection.connect(); + + InputStreamReader isr = new InputStreamReader(connection.getInputStream(), "UTF-8"); + BufferedReader br = new BufferedReader(isr); + StringBuilder sb = new StringBuilder(); + String line; + while ((line = br.readLine()) != null) { + sb.append(line); + } + br.close(); + isr.close(); + connection.disconnect(); + return sb.toString(); + } + + public static String httpGet(String urlStr, Map headers) throws IOException { + // open HTTP connection with URL + return new HttpQueryTool().query(urlStr, headers, new HttpGet(urlStr)); + } + + private String getNodeId(JSONObject doc) { + String id = null; + try { + id = (String) doc.get("id"); + } catch (JSONException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + return id; + } + + @Override + public List getSuggestions(MetadataSet mds, String queryId, String parameterId, String value, List criterias) { + List result = new ArrayList<>(); + + List facets = mds.findQuery(queryId, MetadataReader.QUERY_SYNTAX_LUCENE).findParameterByName(parameterId).getFacets(); + //String url = getUrl("/search",parameterId +":("+value+")",facets, 0, 0); + String url = getUrl("/search", "*", facets, 0, 0); + System.out.println("url:" + url); + + try { + String json = this.query(url); + System.out.println(json); + JSONObject jo = new JSONObject(json); + + JSONArray resultsArr = (JSONArray) jo.get("facets"); + + for (int i = 0; i < resultsArr.length(); i++) { + JSONObject facetObj = (JSONObject) resultsArr.get(i); + String field = facetObj.getString("field"); + int numberOfFacets = facetObj.getInt("numberOfFacets"); + if (facets.contains(field) && numberOfFacets > 0) { + + JSONArray facetValues = facetObj.getJSONArray("facetValues"); + for (int j = 0; j < facetValues.length(); j++) { + JSONObject facetteVal = (JSONObject) facetValues.get(j); + //int count = facetteVal.getInt("count"); + String val = facetteVal.getString("value"); + + if (val.contains(value)) { + Suggestion dto = new Suggestion(); + dto.setKey(val); + dto.setDisplayString(val); + + result.add(dto); + } + } + + + } + } + + } catch (Exception e) { + logger.error(e.getMessage(), e); + } + return result; + } + + public String getUrl(String basePath, String query, List facets, int offset, int rows) { + String url = DDB_API + basePath; + + try { + url += "?oauth_consumer_key=" + URLEncoder.encode(APIKey, "UTF-8"); + } catch (UnsupportedEncodingException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + url += "&query=" + org.springframework.extensions.surf.util.URLEncoder.encodeUriComponent(query); + if (facets != null && facets.size() > 0) { + url += "&facet="; + int i = 0; + for (String facet : facets) { + if (i == 0) { + url += facet; + } else { + url += "," + facet; + } + + } + } + url += "&offset=" + offset; + url += "&rows=" + rows; + + return url; + } + + @Override + public SearchResultNodeRef search(MetadataSet mds, String query, Map criterias, + SearchToken searchToken) throws Throwable { + + + if (!MetadataSet.DEFAULT_CLIENT_QUERY.equals(query)) { + throw new Exception("Only ngsearch query is supported for this repository type, requested " + query); + } /* * String url = baseUrl+"/search"; @@ -234,117 +237,115 @@ public SearchResultNodeRef search(MetadataSet mds, String query, Map0) { - searchWord = searchWordCriteria[0]; - } - if (searchWord.equals("*") ){ - searchWord=""; - } - MetadataQuery mdsQuery = mds.findQuery(MetadataSet.DEFAULT_CLIENT_QUERY, MetadataReader.QUERY_SYNTAX_LUCENE); - List extendedFilters = new ArrayList<>(); - new HashMap() {{ - put("virtual:title", "title"); - put("virtual:place", "place"); - put("virtual:affiliate", "affiliate"); - put("cclom:general_keyword", "keywords"); - }}.forEach( - (key, value) -> { - if (criterias.get(key) != null) { - String lucene = StringUtils.join(Arrays.stream(criterias.get(key)). - filter(StringUtils::isNotEmpty). - map( - str -> value + ":" + QueryParser.escape(str) - ).collect(Collectors.toList()), - " " + mdsQuery.findParameterByName(key).getMultiplejoin() + " "); - if(!lucene.isEmpty()) { - extendedFilters.add("(" + lucene + ")"); - } - } - } - ); - HttpsURLConnection connection=null; - - try { - - - String oauth = "/search?oauth_consumer_key=" + URLEncoder.encode(this.APIKey, "UTF-8"); - String offset = "&offset="+searchToken.getFrom(); - String rows = "&rows="+searchToken.getMaxResult(); - String solrQuery = QueryParser.escape(searchWord); - if(!extendedFilters.isEmpty()) { - solrQuery += " AND ("; - solrQuery += StringUtils.join(extendedFilters, " AND "); - solrQuery += ")"; - } - StringBuilder uri = new StringBuilder(oauth + "&query=" + org.springframework.extensions.surf.util.URLEncoder.encodeUriComponent(solrQuery) + offset + rows); - - - searchToken.setQueryString(uri.toString()); - - return searchDDB(repositoryId,APIKey, uri.toString()); - - } - catch(IOException e){ - InputStream is=connection.getErrorStream(); - StringBuilder responseStrBuilder = new StringBuilder(); - String line; - BufferedReader bR = new BufferedReader( new InputStreamReader(is)); - while((line = bR.readLine()) != null){ - responseStrBuilder.append(line); - } - is.close(); - throw new Exception("Error from DDB: "+connection.getResponseCode()+" "+responseStrBuilder.toString()); - } - catch (Throwable t) { - t.printStackTrace(); - throw t; - } - - } - - public static void main(String[] args) { - try { - String searchWord = "*"; - String extendedSearch = "place:(Frankfurt)"; - String oauthKey = "nVyX1bwLOAEpMVrzfEIf3xth5eTtVOaqZeeUUcUEQDNa4Oigs6y1438781244192"; - String path = "/search"; - path += "?oauth_consumer_key=" + URLEncoder.encode(oauthKey, "UTF-8"); - path += "&query=" + org.springframework.extensions.surf.util.URLEncoder.encodeUriComponent(searchWord+" " +extendedSearch); - path += "&facet=place_fct"; - path += "&offset="+0; - path += "&rows="+0; - - - URL url=new URL(DDB_API+path); - HttpsURLConnection connection = openDDBUrl(url); - connection.connect(); - - InputStreamReader isr = new InputStreamReader(connection.getInputStream(), "UTF-8"); - BufferedReader br = new BufferedReader(isr); - StringBuilder sb = new StringBuilder(); - String line; - while ((line = br.readLine()) != null) { - sb.append(line); - } - br.close(); - isr.close(); - connection.disconnect(); - String jsonString = sb.toString(); - System.out.println(jsonString); - JSONObject jo = new JSONObject(jsonString); - - Integer nrOfResult = (Integer)jo.get("numberOfResults"); - JSONArray resultsArr = (JSONArray)jo.get("results"); - JSONObject results = (JSONObject)resultsArr.get(0); - JSONArray docs = (JSONArray)results.get("docs"); - }catch(Exception e) { - e.printStackTrace(); - } - } + String[] searchWordCriteria = criterias.get(MetadataSet.DEFAULT_CLIENT_QUERY_CRITERIA); + + + String searchWord = ""; + if (searchWordCriteria != null && searchWordCriteria.length > 0) { + searchWord = searchWordCriteria[0]; + } + if (searchWord.equals("*")) { + searchWord = ""; + } + MetadataQuery mdsQuery = mds.findQuery(MetadataSet.DEFAULT_CLIENT_QUERY, MetadataReader.QUERY_SYNTAX_LUCENE); + List extendedFilters = new ArrayList<>(); + Map.of( + "virtual:title", "title", + "virtual:place", "place", + "virtual:affiliate", "affiliate", + "cclom:general_keyword", "keywords" + ).forEach( + (key, value) -> { + if (criterias.get(key) != null) { + String lucene = StringUtils.join(Arrays.stream(criterias.get(key)). + filter(StringUtils::isNotEmpty). + map( + str -> value + ":" + QueryParser.escape(str) + ).collect(Collectors.toList()), + " " + mdsQuery.findParameterByName(key).getMultiplejoin() + " "); + if (!lucene.isEmpty()) { + extendedFilters.add("(" + lucene + ")"); + } + } + } + ); + HttpsURLConnection connection = null; + + try { + + + String oauth = "/search?oauth_consumer_key=" + URLEncoder.encode(this.APIKey, "UTF-8"); + String offset = "&offset=" + searchToken.getFrom(); + String rows = "&rows=" + searchToken.getMaxResult(); + String solrQuery = QueryParser.escape(searchWord); + if (!extendedFilters.isEmpty()) { + solrQuery += " AND ("; + solrQuery += StringUtils.join(extendedFilters, " AND "); + solrQuery += ")"; + } + StringBuilder uri = new StringBuilder(oauth + "&query=" + org.springframework.extensions.surf.util.URLEncoder.encodeUriComponent(solrQuery) + offset + rows); + + + searchToken.setQueryString(uri.toString()); + + return searchDDB(repositoryId, APIKey, uri.toString()); + + } catch (IOException e) { + InputStream is = connection.getErrorStream(); + StringBuilder responseStrBuilder = new StringBuilder(); + String line; + BufferedReader bR = new BufferedReader(new InputStreamReader(is)); + while ((line = bR.readLine()) != null) { + responseStrBuilder.append(line); + } + is.close(); + throw new Exception("Error from DDB: " + connection.getResponseCode() + " " + responseStrBuilder.toString()); + } catch (Throwable t) { + t.printStackTrace(); + throw t; + } + + } + + public static void main(String[] args) { + try { + String searchWord = "*"; + String extendedSearch = "place:(Frankfurt)"; + String oauthKey = "nVyX1bwLOAEpMVrzfEIf3xth5eTtVOaqZeeUUcUEQDNa4Oigs6y1438781244192"; + String path = "/search"; + path += "?oauth_consumer_key=" + URLEncoder.encode(oauthKey, "UTF-8"); + path += "&query=" + org.springframework.extensions.surf.util.URLEncoder.encodeUriComponent(searchWord + " " + extendedSearch); + path += "&facet=place_fct"; + path += "&offset=" + 0; + path += "&rows=" + 0; + + + URL url = new URL(DDB_API + path); + HttpsURLConnection connection = openDDBUrl(url); + connection.connect(); + + InputStreamReader isr = new InputStreamReader(connection.getInputStream(), "UTF-8"); + BufferedReader br = new BufferedReader(isr); + StringBuilder sb = new StringBuilder(); + String line; + while ((line = br.readLine()) != null) { + sb.append(line); + } + br.close(); + isr.close(); + connection.disconnect(); + String jsonString = sb.toString(); + System.out.println(jsonString); + JSONObject jo = new JSONObject(jsonString); + + Integer nrOfResult = (Integer) jo.get("numberOfResults"); + JSONArray resultsArr = (JSONArray) jo.get("results"); + JSONObject results = (JSONObject) resultsArr.get(0); + JSONArray docs = (JSONArray) results.get("docs"); + } catch (Exception e) { + e.printStackTrace(); + } + } } diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/search/SearchServiceElastic.java b/Backend/services/core/src/main/java/org/edu_sharing/service/search/SearchServiceElastic.java index 8f11bfb72b..ae7437a2ce 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/search/SearchServiceElastic.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/search/SearchServiceElastic.java @@ -833,7 +833,7 @@ public NodeRef transformSearchHit(Set authorities, String user, Map hit, private T transform(Class clazz, Set authorities, String user, Map sourceAsMap, boolean resolveCollections) throws IllegalAccessException, InstantiationException { boolean isAdmin = AuthorityServiceHelper.isAdmin(); - HashMap mdsCache = new HashMap<>(); + Map mdsCache = new HashMap<>(); String currentLocale = new AuthenticationToolAPI().getCurrentLocale(); Map properties = (Map) sourceAsMap.get("properties"); @@ -849,7 +849,7 @@ private T transform(Class clazz, Set authorit String protocol = (String) storeRef.get("protocol"); String identifier = (String) storeRef.get("identifier"); - HashMap props = new HashMap<>(); + Map props = new HashMap<>(); for (Map.Entry entry : properties.entrySet()) { @@ -970,7 +970,7 @@ private T transform(Class clazz, Set authorit eduNodeRef.setAspects(((List) sourceAsMap.get("aspects")). stream().map(CCConstants::getValidGlobalName).filter(Objects::nonNull).collect(Collectors.toList())); - HashMap permissions = new HashMap<>(); + Map permissions = new HashMap<>(); permissions.put(CCConstants.PERMISSION_READ, true); String guestUser = ApplicationInfoList.getHomeRepository().getGuest_username(); long millis = System.currentTimeMillis(); @@ -1120,7 +1120,7 @@ private T transform(Class clazz, Set authorit /** * check if the user has permissions on this element via a collection and give him all permissions as it is an usage access */ - private static void processCollectionUsagePermissions(Set authorities, String user, Map sourceAsMap, HashMap permissions) { + private static void processCollectionUsagePermissions(Set authorities, String user, Map sourceAsMap, Map permissions) { if (permissions.size() == 1) { List> collections = (List>) sourceAsMap.get("collections"); for (Map collection : Optional.ofNullable(collections).orElse(Collections.emptyList())) { diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/search/SearchServiceImpl.java b/Backend/services/core/src/main/java/org/edu_sharing/service/search/SearchServiceImpl.java index 8063659756..6d1e662a13 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/search/SearchServiceImpl.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/search/SearchServiceImpl.java @@ -161,7 +161,7 @@ public List getAllMediacenters(boolean membershipsOnly) throws Exception NodeServiceFactory.getNodeService(applicationId).getProperty(ref.getStoreRef().getProtocol(), ref.getStoreRef().getIdentifier(), ref.getId(), CCConstants.CM_PROP_AUTHORITY_AUTHORITYNAME) ).collect(Collectors.toList()); }else { - List result = new ArrayList(); + List result = new ArrayList<>(); for(String memberShip : memberships) { NodeRef nodeRef = serviceRegistry.getAuthorityService().getAuthorityNodeRef(memberShip); if(nodeRef != null && serviceRegistry.getNodeService().hasAspect(nodeRef, QName.createQName(CCConstants.CCM_ASPECT_MEDIACENTER))) { @@ -199,7 +199,7 @@ public SearchResult searchOrganizations(String pattern, int skipCount, @Override public SearchResult doWork() throws Exception { try { - List result = new ArrayList(); + List result = new ArrayList<>(); org.alfresco.service.cmr.search.SearchService searchService = serviceRegistry .getSearchService(); SearchParameters parameters = new SearchParameters(); @@ -215,7 +215,7 @@ public SearchResult doWork() throws Exception { //only search organisations the curren user is in,except: its adminuser and onlyMemberShips == true StringBuilder additionalQuery=null; if(onlyMemberShips) { - List memberShibsOrg = new ArrayList(); + List memberShibsOrg = new ArrayList<>(); if(memberships != null && memberships.size() > 0) { for(String membershib : memberships) { NodeRef authorityNodeRef = serviceRegistry.getAuthorityService().getAuthorityNodeRef(membershib); @@ -261,12 +261,12 @@ public SearchResult doWork() throws Exception { ResultSet edugroups = searchService.query(parameters); for (ResultSetRow row : edugroups) { - HashMap entry = apiClient.getProperties(row.getNodeRef().getId()); + Map entry = apiClient.getProperties(row.getNodeRef().getId()); String nodeRef = (String) entry.get(CCConstants.CCM_PROP_AUTHORITYCONTAINER_EDUHOMEDIR); // when a group folder relation is removed the noderef can be null cause of async solr refresh if (nodeRef != null) { String nodeId = nodeRef.replace("workspace://SpacesStore/", ""); - HashMap folderProps = apiClient.getProperties(nodeId); + Map folderProps = apiClient.getProperties(nodeId); EduGroup eduGroup = new EduGroup(); eduGroup.setFolderId((String) folderProps.get(CCConstants.SYS_PROP_NODE_UID)); eduGroup.setFolderName((String) folderProps.get(CCConstants.CM_NAME)); @@ -355,7 +355,7 @@ public SearchResult execute() throws Throwable { }, true); } private SearchResult filterAndSortAuthorities(String[] data,String pattern,String authorityType,int skipCount, int maxValues,SortDefinition sort) throws Exception { - List list2 = new ArrayList(); + List list2 = new ArrayList<>(); if (authorityType != null && !authorityType.isEmpty()) { for (String authority : data) { if (authorityType.equals("GROUP") @@ -456,11 +456,11 @@ public SearchResult execute() throws Throwable { maxValues = 10; } - List result = new ArrayList(); + List result = new ArrayList<>(); if (globalSearch) { checkGlobalSearchPermission(); PersonService personService = serviceRegistry.getPersonService(); - List filters = new ArrayList(); + List filters = new ArrayList<>(); filters.add(ContentModel.PROP_FIRSTNAME); filters.add(ContentModel.PROP_LASTNAME); filters.add(ContentModel.PROP_EMAIL); @@ -622,7 +622,7 @@ public SearchResultNodeRef search(MetadataSet mds, String query, Map lastTokens = getLastSearchTokens(); + Map lastTokens = getLastSearchTokens(); lastTokens.put(searchToken.getContentType(),searchToken); Context.getCurrentInstance().getRequest().getSession().setAttribute(CCConstants.SESSION_LAST_SEARCH_TOKENS,lastTokens); List facets = searchToken.getFacets(); @@ -630,9 +630,9 @@ public SearchResultNodeRef search(MetadataSet mds, String query, Map getLastSearchTokens() throws Throwable { + public Map getLastSearchTokens() throws Throwable { if(Context.getCurrentInstance().getRequest().getSession().getAttribute(CCConstants.SESSION_LAST_SEARCH_TOKENS)!=null) { - return (HashMap) Context.getCurrentInstance().getRequest().getSession().getAttribute(CCConstants.SESSION_LAST_SEARCH_TOKENS); + return (Map) Context.getCurrentInstance().getRequest().getSession().getAttribute(CCConstants.SESSION_LAST_SEARCH_TOKENS); } return new HashMap<>(); @@ -696,7 +696,7 @@ public SearchResultNodeRef search(SearchToken searchToken, boolean scoped) { } } - List fieldHighlightParameters = new ArrayList(); + List fieldHighlightParameters = new ArrayList<>(); fieldHighlightParameters.add( new FieldHighlightParameters("cm:name",255,100,false,"","")); fieldHighlightParameters.add( new FieldHighlightParameters("cm:title",255,100,false,"","")); fieldHighlightParameters.add( new FieldHighlightParameters("cm:description",255,100,false,"","")); @@ -829,7 +829,7 @@ public SearchResult findAuthorities(AuthorityType type,String searchWord if(findUsersQuery == null && findGroupsQuery == null) { - return new SearchResult(new ArrayList(), 0, 0); + return new SearchResult(new ArrayList<>(), 0, 0); } /** @@ -879,7 +879,7 @@ else if(type.equals(AuthorityType.GROUP)) { logger.debug("finalQuery:" + finalQuery); - List data = new ArrayList(); + List data = new ArrayList<>(); SearchParameters searchParameters = new SearchParameters(); searchParameters.addStore(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE); @@ -898,7 +898,7 @@ else if(type.equals(AuthorityType.GROUP)) { org.alfresco.service.cmr.search.SearchService searchService = serviceRegistry.getSearchService(); ResultSet resultSet = searchService.query(searchParameters); - List result = new ArrayList(); + List result = new ArrayList<>(); for (NodeRef nodeRef : resultSet.getNodeRefs()) { String authorityName = (String) serviceRegistry.getNodeService().getProperty(nodeRef, ContentModel.PROP_AUTHORITY_NAME); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/search/SearchServiceLAppsImpl.java b/Backend/services/core/src/main/java/org/edu_sharing/service/search/SearchServiceLAppsImpl.java index 1f9383d23d..3959c0d262 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/search/SearchServiceLAppsImpl.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/search/SearchServiceLAppsImpl.java @@ -108,7 +108,7 @@ public static SearchResultNodeRef searchLApps(String repositoryId,String apiKey, NamedNodeMap map = node.getAttributes(); - HashMap properties = NodeServiceLAppsImpl.getPropertiesForNode(repositoryId, map); + Map properties = NodeServiceLAppsImpl.getPropertiesForNode(repositoryId, map); org.edu_sharing.service.model.NodeRef ref = new org.edu_sharing.service.model.NodeRefImpl(repositoryId, StoreRef.STORE_REF_WORKSPACE_SPACESSTORE.getProtocol(), diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/search/SearchServiceMemuchoImpl.java b/Backend/services/core/src/main/java/org/edu_sharing/service/search/SearchServiceMemuchoImpl.java index de3a9d7139..acf2337ebc 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/search/SearchServiceMemuchoImpl.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/search/SearchServiceMemuchoImpl.java @@ -95,7 +95,7 @@ public static SearchResultNodeRef searchMemucho( String searchWord, String repos searchResultNodeRef.setNodeCount(searchResultNodeRef.getNodeCount() + array.length()); for (int i = 0; i < array.length(); i++) { JSONObject json = array.getJSONObject(i); - HashMap properties = new HashMap<>(); + Map properties = new HashMap<>(); properties.put(CCConstants.SYS_PROP_NODE_UID, json.getString("TopicId")); properties.put(CCConstants.LOM_PROP_GENERAL_TITLE, json.getString("Name")); properties.put(CCConstants.CM_NAME, json.getString("Name")); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/search/SearchServiceOCartImpl.java b/Backend/services/core/src/main/java/org/edu_sharing/service/search/SearchServiceOCartImpl.java index c5f461b350..8d48b61547 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/search/SearchServiceOCartImpl.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/search/SearchServiceOCartImpl.java @@ -111,11 +111,11 @@ public SearchResultNodeRef searchOCA(String repositoryId,String apiKey,String p SearchResultNodeRef searchResultNodeRef = new SearchResultNodeRef(); List data=new ArrayList<>(); - HashMap> result = new HashMap>(); + Map> result = new HashMap<>(); for(int i = 0; i < docs.length(); i++){ JSONObject doc = (JSONObject)docs.get(i); - HashMap props = this.getProperties(doc); + Map props = this.getProperties(doc); result.put((String)props.get(CCConstants.SYS_PROP_NODE_UID), props); org.edu_sharing.service.model.NodeRef ref = new org.edu_sharing.service.model.NodeRefImpl(repositoryId, @@ -129,7 +129,7 @@ public SearchResultNodeRef searchOCA(String repositoryId,String apiKey,String p /* - HashMap properties=new HashMap<>(); + Map properties=new HashMap<>(); properties.put(CCConstants.SYS_PROP_NODE_UID,map.getNamedItem("id").getNodeValue()); properties.put(CCConstants.LOM_PROP_GENERAL_TITLE,map.getNamedItem("title").getNodeValue()); @@ -160,9 +160,9 @@ public SearchResultNodeRef searchOCA(String repositoryId,String apiKey,String p } - public static String httpGet(String urlStr, HashMap properties) throws IOException { + public static String httpGet(String urlStr, Map properties) throws IOException { if (properties == null) { - properties = new HashMap(); + properties = new HashMap<>(); } // open HTTP connection with URL URL url = new URL(urlStr); @@ -189,18 +189,18 @@ public static String httpGet(String urlStr, HashMap properties) return sb.toString(); } - private HashMap getProperties(JSONObject doc){ - HashMap properties = new HashMap(); + private Map getProperties(JSONObject doc){ + Map properties = new HashMap<>(); String id = null; try { - id = (String)doc.getString("id"); + id = doc.getString("id"); } catch (JSONException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } String title = null; try { - title = (String)doc.getString("title"); + title = doc.getString("title"); } catch (JSONException e1) { // TODO Auto-generated catch block e1.printStackTrace(); @@ -262,9 +262,9 @@ private HashMap getProperties(JSONObject doc){ } - public HashMap getProperties(String nodeId) throws Throwable { + public Map getProperties(String nodeId) throws Throwable { - HashMap properties = new HashMap(); + Map properties = new HashMap<>(); try{ String result = httpGet(OCA_API +"/search/json/?byids="+nodeId, null); if(result != null && result.trim().length() > 0){ @@ -320,7 +320,7 @@ public SearchResultNodeRef search(MetadataSet mds, String query, Map extSearch = new ArrayList(); + List extSearch = new ArrayList<>(); String searchWord = searchWordCriteria[0]; if (searchWord.equals("*") ){ diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/search/SearchServicePixabayImpl.java b/Backend/services/core/src/main/java/org/edu_sharing/service/search/SearchServicePixabayImpl.java index 8b81f0883e..848c458730 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/search/SearchServicePixabayImpl.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/search/SearchServicePixabayImpl.java @@ -122,7 +122,7 @@ public static SearchResultNodeRef searchPixabay(String repositoryId,String apiKe for(int i=0;i properties=new HashMap<>(); + Map properties=new HashMap<>(); properties.put(CCConstants.SYS_PROP_NODE_UID,json.getString("id")); properties.put(CCConstants.CM_PROP_C_MODIFIED,System.currentTimeMillis()); properties.put(CCConstants.LOM_PROP_GENERAL_TITLE,json.getString("tags")); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/search/SearchServiceTutoryImpl.java b/Backend/services/core/src/main/java/org/edu_sharing/service/search/SearchServiceTutoryImpl.java index 2b058717e4..2359606ea1 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/search/SearchServiceTutoryImpl.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/search/SearchServiceTutoryImpl.java @@ -79,8 +79,8 @@ public SearchResultNodeRef search(MetadataSet mds, String query, Map getProperties(JSONObject worksheet) throws JSONException{ - HashMap properties=new HashMap<>(); + public static Map getProperties(JSONObject worksheet) throws JSONException{ + Map properties=new HashMap<>(); String id = worksheet.getString("id"); properties.put(CCConstants.SYS_PROP_NODE_UID,id); properties.put(CCConstants.LOM_PROP_GENERAL_TITLE,worksheet.getString("name")); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/search/SearchServiceWSImpl.java b/Backend/services/core/src/main/java/org/edu_sharing/service/search/SearchServiceWSImpl.java index b7d2677729..7ef86c8121 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/search/SearchServiceWSImpl.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/search/SearchServiceWSImpl.java @@ -62,7 +62,7 @@ public SearchResult searchOrganizations(String pattern, int skipCount, @Override public SearchResultNodeRef search(SearchToken _searchToken) { org.edu_sharing.repository.client.rpc.SearchToken searchToken = new org.edu_sharing.repository.client.rpc.SearchToken(); - searchToken.setCountProps(new ArrayList(_searchToken.getFacets())); + searchToken.setCountProps(new ArrayList<>(_searchToken.getFacets())); searchToken.setCountPropsMinCount(_searchToken.getFacetsMinCount()); searchToken.setNrOfResults(_searchToken.getMaxResult()); searchToken.setRepositoryId(appId); @@ -96,7 +96,7 @@ public SearchResult findAuthorities(AuthorityType user, String searchWor } @Override - public HashMap getLastSearchTokens() throws Throwable { + public Map getLastSearchTokens() throws Throwable { // TODO Auto-generated method stub return null; } diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/search/SearchServiceYouTubeImpl.java b/Backend/services/core/src/main/java/org/edu_sharing/service/search/SearchServiceYouTubeImpl.java index 154553c2cc..527c1f4a1d 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/search/SearchServiceYouTubeImpl.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/search/SearchServiceYouTubeImpl.java @@ -105,7 +105,7 @@ private SearchResultNodeRef searchInternal(SearchCriterias rc, String query, Lis searchResultNodeRef.setSearchCriterias(rc); - HashMap> resultData = new HashMap>(); + Map> resultData = new HashMap<>(); searchResultNodeRef.setStartIDX(token.getFrom()); searchResultNodeRef.setNodeCount(searchResponse.getPageInfo()==null ? 0 : searchResponse.getPageInfo().getTotalResults()); Iterator iteratorSearchResults = searchResultList.iterator(); @@ -122,7 +122,7 @@ private SearchResultNodeRef searchInternal(SearchCriterias rc, String query, Lis // Confirm that the result represents a video. // Otherwise, the item will not contain a video ID. if (rId.getKind().equals("youtube#video")) { - HashMap esResult = NodeServiceYouTube.getPropsByVideoEntry(repositoryId,singleVideo); + Map esResult = NodeServiceYouTube.getPropsByVideoEntry(repositoryId,singleVideo); //resultData.put((String) esResult.get(CCConstants.SYS_PROP_NODE_UID), esResult); org.edu_sharing.service.model.NodeRef enr = new org.edu_sharing.service.model.NodeRefImpl(this.repositoryId, diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/search/model/SortDefinition.java b/Backend/services/core/src/main/java/org/edu_sharing/service/search/model/SortDefinition.java index 8bc0e4df59..a58a00b3c3 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/search/model/SortDefinition.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/search/model/SortDefinition.java @@ -29,7 +29,7 @@ public class SortDefinition implements Serializable { transient ApplicationContext applicationContext = AlfAppContextGate.getApplicationContext(); transient ServiceRegistry serviceRegistry = (ServiceRegistry) applicationContext.getBean(ServiceRegistry.SERVICE_REGISTRY); - List sortDefinitionEntries = new ArrayList(); + List sortDefinitionEntries = new ArrayList<>(); public static class SortDefinitionEntry implements Serializable{ String property; diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/share/ShareServiceImpl.java b/Backend/services/core/src/main/java/org/edu_sharing/service/share/ShareServiceImpl.java index 1506c7f325..689485f5da 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/share/ShareServiceImpl.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/share/ShareServiceImpl.java @@ -128,7 +128,7 @@ public String createShare(String nodeId, String[] emails, long expiryDate, Strin String token=null; for(String email : emails){ - Map props = new HashMap(); + Map props = new HashMap<>(); props.put(SHARE_PROP_EXPIRYDATE, expiryDate); props.put(SHARE_PROP_SHARE_MAIL, email); @@ -203,7 +203,7 @@ public void updateDownloadCount(Share share){ @Override public void updateShare(Share share) { NodeRef shareNodeRef = new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, share.getNodeId()); - Map props = new HashMap(); + Map props = new HashMap<>(); props.put(SHARE_PROP_SHARE_TOKEN, share.getToken()); props.put(SHARE_PROP_EXPIRYDATE, share.getExpiryDate()); @@ -227,7 +227,7 @@ public Share[] getShares(String nodeId) { qnameSet.add(SHARE_TYPE); List childNodeRefs = serviceRegistry.getNodeService().getChildAssocs(new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE,nodeId),qnameSet); - List result = new ArrayList(); + List result = new ArrayList<>(); for(ChildAssociationRef childRef : childNodeRefs){ Map props = serviceRegistry.getNodeService().getProperties(childRef.getChildRef()); Share share = getNodeShareObject(nodeId,childRef.getChildRef()); @@ -261,7 +261,7 @@ public boolean isNodeAccessibleViaShare(NodeRef sharedNode, String accessNodeId) return isChild || sharedNode.getId().equals(accessNodeId); } private Share getNodeShareObject(String nodeId, NodeRef shareNodeRef) { - HashMap props; + Map props; Map propsNative; try { props = NodeServiceFactory.getLocalService().getProperties(shareNodeRef.getStoreRef().getProtocol(), diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/statistic/Filter.java b/Backend/services/core/src/main/java/org/edu_sharing/service/statistic/Filter.java index a318fcf3da..fc3339e7d3 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/statistic/Filter.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/statistic/Filter.java @@ -5,7 +5,7 @@ public class Filter { - List entries = new ArrayList(); + List entries = new ArrayList<>(); public List getEntries() { diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/statistic/StatisticServiceImpl.java b/Backend/services/core/src/main/java/org/edu_sharing/service/statistic/StatisticServiceImpl.java index 6be900644a..612c44a708 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/statistic/StatisticServiceImpl.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/statistic/StatisticServiceImpl.java @@ -28,7 +28,7 @@ public class StatisticServiceImpl implements StatisticService { ApplicationInfo appInfo; - HashMap authInfo; + Map authInfo; MCAlfrescoBaseClient client; AuthenticationTool authTool; diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/statistic/Statistics.java b/Backend/services/core/src/main/java/org/edu_sharing/service/statistic/Statistics.java index ec5e50a0a3..0cdcb357c3 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/statistic/Statistics.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/statistic/Statistics.java @@ -6,7 +6,7 @@ public class Statistics { - List entries = new ArrayList(); + List entries = new ArrayList<>(); public void setEntries(List entries) { this.entries = entries; diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/stream/StreamServiceHelper.java b/Backend/services/core/src/main/java/org/edu_sharing/service/stream/StreamServiceHelper.java index 245f1dae53..82f9d67139 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/stream/StreamServiceHelper.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/stream/StreamServiceHelper.java @@ -12,7 +12,7 @@ public class StreamServiceHelper { public static List getCurrentAuthorities() { AuthorityService authorityService=AuthorityServiceFactory.getLocalService(); - ArrayList authorities = new ArrayList(); + ArrayList authorities = new ArrayList<>(); authorities.add(AuthenticationUtil.getFullyAuthenticatedUser()); AuthenticationUtil.runAsSystem(new AuthenticationUtil.RunAsWork() { diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/tracking/TrackingServiceImpl.java b/Backend/services/core/src/main/java/org/edu_sharing/service/tracking/TrackingServiceImpl.java index bae918da79..5c65d4d03c 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/tracking/TrackingServiceImpl.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/tracking/TrackingServiceImpl.java @@ -370,7 +370,7 @@ private static void mapAdditionalFields(EventType type, List additionalF if(current==null) { current = new HashMap<>(); } - HashMap counted = getArrayAggToCounts((String[]) resultSet.getArray(field).getArray()); + Map counted = getArrayAggToCounts((String[]) resultSet.getArray(field).getArray()); if(field.equals("authority_mediacenter") && mediacenter != null) { counted = counted.entrySet().stream().filter( e -> mediacenter.equals(e.getKey()) @@ -382,7 +382,7 @@ private static void mapAdditionalFields(EventType type, List additionalF } @NotNull - private static HashMap getArrayAggToCounts(String[] arrayAgg) throws SQLException { + private static Map getArrayAggToCounts(String[] arrayAgg) throws SQLException { // the sql field will add each property to an array like 1,2,1,3 // we will map it to {1:2,2:1,3:1} return new HashMap<>(Arrays.stream(arrayAgg).map((a)->a==null ? "" : a) diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/tracking/ibatis/NodeData.java b/Backend/services/core/src/main/java/org/edu_sharing/service/tracking/ibatis/NodeData.java index 2b64371764..7d9c1ad324 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/tracking/ibatis/NodeData.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/tracking/ibatis/NodeData.java @@ -4,14 +4,13 @@ import org.json.JSONException; import org.json.JSONObject; -import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class NodeData { private String timestamp; - HashMap counts = new HashMap<>(); + Map counts = new HashMap<>(); public String getTimestamp() { return timestamp; diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/usage/AlfServicesWrapper.java b/Backend/services/core/src/main/java/org/edu_sharing/service/usage/AlfServicesWrapper.java index 761b5f8534..a89b8a488e 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/usage/AlfServicesWrapper.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/usage/AlfServicesWrapper.java @@ -34,10 +34,7 @@ import org.alfresco.repo.security.authentication.AuthenticationUtil; import org.alfresco.repo.security.authentication.AuthenticationUtil.RunAsWork; import org.alfresco.service.ServiceRegistry; -import org.alfresco.service.cmr.repository.ChildAssociationRef; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.repository.NodeService; -import org.alfresco.service.cmr.repository.StoreRef; +import org.alfresco.service.cmr.repository.*; import org.alfresco.service.cmr.search.ResultSet; import org.alfresco.service.cmr.search.SearchService; import org.alfresco.service.cmr.security.AuthenticationService; @@ -87,28 +84,28 @@ public AlfServicesWrapper() { nodeService = serviceRegistry.getNodeService(); } - public AlfServicesWrapper(HashMap authInfo) { + public AlfServicesWrapper(Map authInfo) { this(); authenticationService.validate((String) authInfo.get(CCConstants.AUTH_TICKET)); } - public HashMap authenticate(String username, String password) { + public Map authenticate(String username, String password) { authenticationService.authenticate(username, password.toCharArray()); String ticket = authenticationService.getCurrentTicket(); - HashMap authInfo = new HashMap(); + Map authInfo = new HashMap<>(); authInfo.put(CCConstants.AUTH_USERNAME, username); authInfo.put(CCConstants.AUTH_TICKET, ticket); return authInfo; } - public HashMap> getUsages(String nodeId) { - HashMap> result = getChildrenByType(nodeId, CCConstants.CCM_TYPE_USAGE); + public Map> getUsages(String nodeId) { + Map> result = getChildrenByType(nodeId, CCConstants.CCM_TYPE_USAGE); return result; } - public HashMap getProperties(NodeRef nodeRef){ + public Map getProperties(NodeRef nodeRef){ Map childPropMap = nodeService.getProperties(nodeRef); - HashMap resultProps = new HashMap(); + Map resultProps = new HashMap<>(); for (QName qname : childPropMap.keySet()) { Serializable object = childPropMap.get(qname); @@ -133,10 +130,10 @@ public HashMap getProperties(NodeRef nodeRef){ } @Override - public HashMap getUsageOnNodeOrParents(String lmsId, String courseId, String objectNodeId, String resourceId) throws Exception { + public Map getUsageOnNodeOrParents(String lmsId, String courseId, String objectNodeId, String resourceId) throws Exception { NodeRef nodeId=new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE,objectNodeId); while(nodeId!=null) { - HashMap usage = getUsage(lmsId, courseId, nodeId.getId(), resourceId); + Map usage = getUsage(lmsId, courseId, nodeId.getId(), resourceId); if(usage!=null) return usage; nodeId=nodeService.getPrimaryParent(nodeId).getParentRef(); @@ -145,10 +142,10 @@ public HashMap getUsageOnNodeOrParents(String lmsId, String cour } @Override - public HashMap getUsage(String lmsId, String courseId, String objectNodeId, String resourceId) throws Exception { - HashMap> children = getChildrenByType(objectNodeId, CCConstants.CCM_TYPE_USAGE); + public Map getUsage(String lmsId, String courseId, String objectNodeId, String resourceId) throws Exception { + Map> children = getChildrenByType(objectNodeId, CCConstants.CCM_TYPE_USAGE); for (String key : children.keySet()) { - HashMap usageNode = children.get(key); + Map usageNode = children.get(key); String tmpAppId = (String) usageNode.get(CCConstants.CCM_PROP_USAGE_APPID); String tmpCourseId = (String) usageNode.get(CCConstants.CCM_PROP_USAGE_COURSEID); // String tmpAppUser = (String)usageNode.get(CCConstants.CCM_PROP_USAGE_APPUSER); @@ -170,13 +167,13 @@ public HashMap getUsage(String lmsId, String courseId, String ob } @Override - public HashMap getUsage(String usageId) throws Exception { + public Map getUsage(String usageId) throws Exception { return getProperties(new NodeRef(storeRef,usageId)); } - public HashMap> getUsagesByCourse(String lmsId, String courseId) throws Exception { - HashMap> result = new HashMap>(); + public Map> getUsagesByCourse(String lmsId, String courseId) throws Exception { + Map> result = new HashMap<>(); // prevent getting all usages by using * as courseId if(courseId.contains("*")){ @@ -190,7 +187,7 @@ public HashMap> getUsagesByCourse(String lmsId, try{ Map tmpprops = nodeService.getProperties(nodeRef); - HashMap props = new HashMap(); + Map props = new HashMap<>(); for (QName key : tmpprops.keySet()) { String propName = key.toString(); Object propValue = tmpprops.get(key); @@ -207,15 +204,15 @@ public HashMap> getUsagesByCourse(String lmsId, } @Override - public HashMap> getUsagesByAppId(String appId) throws Exception { - HashMap> result = new HashMap>(); + public Map> getUsagesByAppId(String appId) throws Exception { + Map> result = new HashMap<>(); String queryString = "TYPE:\"{http://www.campuscontent.de/model/1.0}usage\" AND @ccm\\:usageappid:" + appId; ResultSet resultSet = searchService.query(storeRef, SearchService.LANGUAGE_LUCENE, queryString); for (NodeRef nodeRef : resultSet.getNodeRefs()) { try{ Map tmpprops = nodeService.getProperties(nodeRef); - HashMap props = new HashMap(); + Map props = new HashMap<>(); for (QName key : tmpprops.keySet()) { String propName = key.toString(); Object propValue = tmpprops.get(key); @@ -233,7 +230,7 @@ public HashMap> getUsagesByAppId(String appId) t } @Override - public HashMap> getUsages(String repositoryId, String nodeId, Long from, Long to) throws Exception { + public Map> getUsages(String repositoryId, String nodeId, Long from, Long to) throws Exception { ApplicationInfo appInfo = ApplicationInfoList.getRepositoryInfoById(repositoryId); if(appInfo == null) { throw new Exception("unknown application " +repositoryId); @@ -251,90 +248,87 @@ public HashMap> getUsages(String repositoryId, S - RunAsWork>> runAs = new RunAsWork>>() { - @Override - public HashMap> doWork() throws Exception { - - HashMap> result = new HashMap>(); - - if(ApplicationInfoList.getHomeRepository().getAppId().equals(appInfo.getAppId())) { - String queryString = "TYPE:\"{http://www.campuscontent.de/model/1.0}usage\""; - if(nodeId != null && nodeId.trim().length() > 0) { - queryString += " AND @ccm\\:usageparentnodeid:" + nodeId; - } - if(from != null) { - - String fromFormated = ISO8601DateFormat.format(new Date(from)); - - Long to2 = (to == null) ? new Date().getTime() : to; - String toFormated = ISO8601DateFormat.format(new Date(to2)); - queryString += " AND @cm\\:created:[" + fromFormated + " TO " + toFormated + "]"; - } - - ResultSet resultSet = searchService.query(storeRef, SearchService.LANGUAGE_LUCENE, queryString); - for (NodeRef nodeRef : resultSet.getNodeRefs()) { - - try{ - - HashMap props = getProperties(nodeRef); - ChildAssociationRef childssocRef = nodeService.getPrimaryParent(nodeRef); - props.put(CCConstants.VIRT_PROP_PRIMARYPARENT_NODEID, childssocRef.getParentRef().getId()); - - result.put(nodeRef.getId(), props); - }catch(org.alfresco.service.cmr.repository.InvalidNodeRefException e){ - logger.error("nodeRef: "+nodeRef+" does not exist. maybe an archived usage node:"+e.getMessage()); - } - } - }else { - String queryString = "TYPE:\"{http://www.campuscontent.de/model/1.0}remoteobject\" AND @ccm\\:remoterepositoryid:" + repositoryIdF; - if(nodeId != null && nodeId.trim().length() > 0) { - queryString += " AND @ccm\\:remotenodeid:" + nodeId; - } - if(from != null) { - - String fromFormated = ISO8601DateFormat.format(new Date(from)); - - Long to2 = (to == null) ? new Date().getTime() : to; - String toFormated = ISO8601DateFormat.format(new Date(to2)); - queryString += " AND @cm\\:created:[" + fromFormated + " TO " + toFormated + "]"; - } - - ResultSet resultSet = searchService.query(storeRef, SearchService.LANGUAGE_LUCENE, queryString); - for (NodeRef nodeRef : resultSet.getNodeRefs()) { - - try{ - - List childAssocs = nodeService.getChildAssocs(nodeRef); - for(ChildAssociationRef childRef : childAssocs) { - if(QName.createQName(CCConstants.CCM_TYPE_USAGE).equals(nodeService.getType(childRef.getChildRef()))){ - - HashMap props = getProperties(childRef.getChildRef()); - ChildAssociationRef childssocRef = nodeService.getPrimaryParent(childRef.getChildRef()); - props.put(CCConstants.VIRT_PROP_PRIMARYPARENT_NODEID, childssocRef.getParentRef().getId()); - - result.put(childRef.getChildRef().getId(), props); - } - } - - }catch(org.alfresco.service.cmr.repository.InvalidNodeRefException e){ - logger.error("nodeRef: "+nodeRef+" does not exist. maybe an archived usage node:"+e.getMessage()); - } - } - } - - return result; - } - }; + RunAsWork>> runAs = () -> { + + Map> result = new HashMap<>(); + + if(ApplicationInfoList.getHomeRepository().getAppId().equals(appInfo.getAppId())) { + String queryString = "TYPE:\"{http://www.campuscontent.de/model/1.0}usage\""; + if(nodeId != null && nodeId.trim().length() > 0) { + queryString += " AND @ccm\\:usageparentnodeid:" + nodeId; + } + if(from != null) { + + String fromFormated = ISO8601DateFormat.format(new Date(from)); + + Long to2 = (to == null) ? new Date().getTime() : to; + String toFormated = ISO8601DateFormat.format(new Date(to2)); + queryString += " AND @cm\\:created:[" + fromFormated + " TO " + toFormated + "]"; + } + + ResultSet resultSet = searchService.query(storeRef, SearchService.LANGUAGE_LUCENE, queryString); + for (NodeRef nodeRef : resultSet.getNodeRefs()) { + + try{ + + Map props = getProperties(nodeRef); + ChildAssociationRef childssocRef = nodeService.getPrimaryParent(nodeRef); + props.put(CCConstants.VIRT_PROP_PRIMARYPARENT_NODEID, childssocRef.getParentRef().getId()); + + result.put(nodeRef.getId(), props); + }catch(InvalidNodeRefException e){ + logger.error("nodeRef: "+nodeRef+" does not exist. maybe an archived usage node:"+e.getMessage()); + } + } + }else { + String queryString = "TYPE:\"{http://www.campuscontent.de/model/1.0}remoteobject\" AND @ccm\\:remoterepositoryid:" + repositoryIdF; + if(nodeId != null && nodeId.trim().length() > 0) { + queryString += " AND @ccm\\:remotenodeid:" + nodeId; + } + if(from != null) { + + String fromFormated = ISO8601DateFormat.format(new Date(from)); + + Long to2 = (to == null) ? new Date().getTime() : to; + String toFormated = ISO8601DateFormat.format(new Date(to2)); + queryString += " AND @cm\\:created:[" + fromFormated + " TO " + toFormated + "]"; + } + + ResultSet resultSet = searchService.query(storeRef, SearchService.LANGUAGE_LUCENE, queryString); + for (NodeRef nodeRef : resultSet.getNodeRefs()) { + + try{ + + List childAssocs = nodeService.getChildAssocs(nodeRef); + for(ChildAssociationRef childRef : childAssocs) { + if(QName.createQName(CCConstants.CCM_TYPE_USAGE).equals(nodeService.getType(childRef.getChildRef()))){ + + Map props = getProperties(childRef.getChildRef()); + ChildAssociationRef childssocRef = nodeService.getPrimaryParent(childRef.getChildRef()); + props.put(CCConstants.VIRT_PROP_PRIMARYPARENT_NODEID, childssocRef.getParentRef().getId()); + + result.put(childRef.getChildRef().getId(), props); + } + } + + }catch(InvalidNodeRefException e){ + logger.error("nodeRef: "+nodeRef+" does not exist. maybe an archived usage node:"+e.getMessage()); + } + } + } + + return result; + }; return AuthenticationUtil.runAsSystem(runAs); } - public HashMap> getChildrenByType(String nodeId, String type) { + public Map> getChildrenByType(String nodeId, String type) { return this.getChildrenByType(storeRef, nodeId, type); } - public HashMap> getChildrenByType(StoreRef store, String nodeId, String type) { - HashMap> result = new HashMap>(); + public Map> getChildrenByType(StoreRef store, String nodeId, String type) { + Map> result = new HashMap<>(); List childAssocList = nodeService.getChildAssocs(new NodeRef(store, nodeId),Collections.singleton(QName.createQName(type))); for (ChildAssociationRef child : childAssocList) { result.put(child.getChildRef().getId(), getProperties(child.getChildRef())); @@ -376,7 +370,7 @@ public void removeNode(String nodeID, String fromID) { public boolean hasPermissions(String nodeId, String authority, String[] permissions) throws Exception { - HashMap hasPResult = null; + Map hasPResult = null; try { ApplicationContext applicationContext = AlfAppContextGate.getApplicationContext(); @@ -409,11 +403,11 @@ public boolean hasPermissions(String nodeId, String authority, String[] permissi } - public void updateNode(String nodeId, HashMap _props) { + public void updateNode(String nodeId, Map _props) { this.updateNode(storeRef, nodeId, _props); } - public void updateNode(StoreRef store, String nodeId, HashMap _props) { + public void updateNode(StoreRef store, String nodeId, Map _props) { Map props = transformPropMap(_props); NodeRef nodeRef = new NodeRef(store, nodeId); @@ -426,20 +420,20 @@ public void updateNode(StoreRef store, String nodeId, HashMap _p } - Map transformPropMap(HashMap map) { - Map result = new HashMap(); - for (Object key : map.keySet()) { - result.put(QName.createQName((String) key), (Serializable) map.get(key)); + Map transformPropMap(Map map) { + Map result = new HashMap<>(); + for (String key : map.keySet()) { + result.put(QName.createQName(key), (Serializable)map.get(key)); } return result; } - public String createNode(String parentID, String nodeTypeString, String childAssociation, HashMap _props) { + public String createNode(String parentID, String nodeTypeString, String childAssociation, Map _props) { return this.createNode(storeRef, parentID, nodeTypeString, childAssociation, _props); } public String createNode(StoreRef store, String parentID, String nodeTypeString, String childAssociation, - HashMap _props) { + Map _props) { Map properties = transformPropMap(_props); @@ -454,7 +448,7 @@ public String createPersonAccessElement(String personId, String username, String String accesskey){ logger.info("starting... personId:" + personId + " username:" + username + " applicationId:" + applicationId + " accessAllowed:" + accessAllowed + " accesskey:" + accesskey); - HashMap persAccEleProps = new HashMap(); + Map persAccEleProps = new HashMap<>(); if (accessAllowed == null) { persAccEleProps.put(CCConstants.CM_PROP_PERSONACCESSELEMENT_CCACCESS, new Boolean(false).toString()); } else { @@ -503,20 +497,20 @@ public void sendActivationRequestMail(String receivermail, String applicationId, } @Override - public String createUsage(String parentId, HashMap properties) { - String usageId = this.createNode(parentId, CCConstants.CCM_TYPE_USAGE, CCConstants.CCM_ASSOC_USAGEASPECT_USAGES,(HashMap)properties); + public String createUsage(String parentId, Map properties) { + String usageId = this.createNode(parentId, CCConstants.CCM_TYPE_USAGE, CCConstants.CCM_ASSOC_USAGEASPECT_USAGES,(Map)properties); return usageId; } @Override - public void updateUsage(String usageNodeId, HashMap properties) { + public void updateUsage(String usageNodeId, Map properties) { this.updateNode(usageNodeId, properties); } @Override public void removeUsage(String appId, String courseId, String parentNodeId, String resourceId) throws Exception { logger.info("appId:"+appId +" courseId:"+courseId+ " parentNodeId:"+parentNodeId+" resourceId:"+resourceId); - HashMap usage = this.getUsage(appId, courseId, parentNodeId, resourceId); + Map usage = this.getUsage(appId, courseId, parentNodeId, resourceId); if(usage != null){ String parentId = (String)usage.get(CCConstants.CCM_PROP_USAGE_PARENTNODEID); String usageId = (String)usage.get(CCConstants.SYS_PROP_NODE_UID); @@ -529,12 +523,12 @@ public void removeUsage(String appId, String courseId, String parentNodeId, Stri @Override public boolean removeUsages(String appId, String courseId) throws Exception { - HashMap> usages = this.getUsagesByCourse(appId, courseId); + Map> usages = this.getUsagesByCourse(appId, courseId); boolean allDeleted = true; for(String key: usages.keySet()){ - HashMap props = usages.get(key); + Map props = usages.get(key); String tmpCourseId = (String)props.get(CCConstants.CCM_PROP_USAGE_COURSEID); String tmpPrimaryParentId = (String)props.get(CCConstants.VIRT_PROP_PRIMARYPARENT_NODEID); String tmpAppId = (String)props.get(CCConstants.CCM_PROP_USAGE_APPID); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/usage/Usage.java b/Backend/services/core/src/main/java/org/edu_sharing/service/usage/Usage.java index ef94d262f3..0c05bc7c48 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/usage/Usage.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/usage/Usage.java @@ -182,7 +182,7 @@ public void setModified(Date modified) { public Map toMap(){ - Map result = new HashMap(); + Map result = new HashMap<>(); result.put(CCConstants.CCM_PROP_USAGE_APPID, this.getLmsId()); result.put(CCConstants.CCM_PROP_USAGE_APPUSER, this.getAppUser()); result.put(CCConstants.CCM_PROP_USAGE_APPUSERMAIL, this.getAppUserMail()); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/usage/Usage2Service.java b/Backend/services/core/src/main/java/org/edu_sharing/service/usage/Usage2Service.java index fe74ef0261..7c432c9b1a 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/usage/Usage2Service.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/usage/Usage2Service.java @@ -1,6 +1,5 @@ package org.edu_sharing.service.usage; -import java.io.Serializable; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; @@ -8,7 +7,6 @@ import java.util.List; import java.util.Map; -import info.bliki.html.wikipedia.ThTag; import org.alfresco.model.ContentModel; import org.alfresco.repo.security.authentication.AuthenticationUtil; import org.alfresco.repo.security.authentication.AuthenticationUtil.RunAsWork; @@ -16,7 +14,6 @@ import org.alfresco.service.cmr.repository.MLText; import org.alfresco.service.cmr.repository.NodeRef; import org.alfresco.service.cmr.repository.StoreRef; -import org.alfresco.service.cmr.security.AccessStatus; import org.alfresco.service.cmr.security.PermissionService; import org.alfresco.service.namespace.QName; import org.alfresco.util.ISO8601DateFormat; @@ -57,7 +54,7 @@ public Usage getUsage(String lmsId, String courseId, String parentNodeId, String AuthenticationUtil.RunAsWork runAs = () -> { Usage result = null; - HashMap usage = null; + Map usage = null; try{ usage = usageDao.getUsage(lmsId, courseId, parentNodeId, resourceId); if (usage != null) { @@ -84,10 +81,10 @@ public List getUsagesByCourse(String appId, String courseId) throws Usage AuthenticationUtil.RunAsWork> runAs = new AuthenticationUtil.RunAsWork>(){ @Override public List doWork() throws Exception { - List result = new ArrayList(); + List result = new ArrayList<>(); try{ - HashMap> usages = usageDao.getUsagesByCourse(appId, courseId); - for(Map.Entry> entry : usages.entrySet()){ + Map> usages = usageDao.getUsagesByCourse(appId, courseId); + for(Map.Entry> entry : usages.entrySet()){ result.add(getUsageResult(entry.getValue())); } }catch(Exception e){ @@ -105,12 +102,12 @@ public List doWork() throws Exception { public List getUsages(String appId)throws UsageException{ - List result = new ArrayList(); + List result = new ArrayList<>(); try{ AuthenticationUtil.runAsSystem(()->{ - HashMap> usages = usageDao.getUsagesByAppId(appId); - for(Map.Entry> entry : usages.entrySet()){ + Map> usages = usageDao.getUsagesByAppId(appId); + for(Map.Entry> entry : usages.entrySet()){ result.add(getUsageResult(entry.getValue())); } return null; @@ -127,9 +124,9 @@ public List getUsages(String repositoryId, String nodeId, Long from, Long to) throws Exception { - List result = new ArrayList(); + List result = new ArrayList<>(); - for(Map.Entry> entry : usageDao.getUsages(repositoryId, nodeId, from, to).entrySet()) { + for(Map.Entry> entry : usageDao.getUsages(repositoryId, nodeId, from, to).entrySet()) { result.add(getUsageResult(entry.getValue())); } @@ -150,7 +147,7 @@ public Usage doWork() throws Exception { try{ logger.info("before alfServicesWrapper.hasPermissions"); - HashMap usage = usageDao.getUsage(lmsId, courseId, parentNodeId, resourceId); + Map usage = usageDao.getUsage(lmsId, courseId, parentNodeId, resourceId); //only check publish permission for new content so that an teacher who modifies the course/wysiwyg can safe changes of permission if(usage == null){ @@ -160,7 +157,7 @@ public Usage doWork() throws Exception { usageNodeId=NodeServiceHelper.getProperty(new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE,usageNodeId),CCConstants.CCM_PROP_IO_ORIGINAL); } boolean hasPublishPerm = ((MCAlfrescoClient)RepoFactory.getInstance(ApplicationInfoList.getHomeRepository().getAppId(), - (HashMap)null)).hasPermissions(usageNodeId, user, new String[]{CCConstants.PERMISSION_CC_PUBLISH}); + (Map)null)).hasPermissions(usageNodeId, user, new String[]{CCConstants.PERMISSION_CC_PUBLISH}); if(!hasPublishPerm){ logger.info("User "+user+" has no publish permission on " + usageNodeId); @@ -189,8 +186,8 @@ public Usage doWork() throws Exception { * used by collections */ public Usage setUsageInternal(String repoId, String user, String lmsId, String courseId, String parentNodeId, String userMail, Calendar fromUsed, Calendar toUsed, int distinctPersons, String version, String resourceId, String xmlParams) throws Exception{ - HashMap properties = new HashMap<>(); - HashMap usage = usageDao.getUsage(lmsId, courseId, parentNodeId, resourceId); + Map properties = new HashMap<>(); + Map usage = usageDao.getUsage(lmsId, courseId, parentNodeId, resourceId); String guid = null; NodeRef personRef = serviceRegistry.getPersonService().getPerson(user); if(personRef != null){ @@ -279,14 +276,14 @@ public List getUsageByParentNodeId(String repoId, String user, String par StoreRef.STORE_REF_WORKSPACE_SPACESSTORE.getIdentifier(), parentNodeId, PermissionService.READ)){ - return new ArrayList(); + return new ArrayList<>(); } try{ return AuthenticationUtil.runAsSystem(()->{ - HashMap> usages = usageDao.getUsages(parentNodeId); + Map> usages = usageDao.getUsages(parentNodeId); logger.info("usages.keySet().size():"+usages.keySet().size()); - ArrayList result = new ArrayList(); + ArrayList result = new ArrayList<>(); for (String key : usages.keySet()) { result.add(getUsageResult(usages.get(key))); } @@ -307,7 +304,7 @@ public List getUsageByParentNodeId(String repoId, String user, String par private void addUsagesFromReferenceObjects(String parentNodeId, ArrayList result) { List nodes = CollectionServiceFactory.getLocalService().getReferenceObjects(parentNodeId); for(org.edu_sharing.service.model.NodeRef node : nodes){ - HashMap> usages = usageDao.getUsages(node.getNodeId()); + Map> usages = usageDao.getUsages(node.getNodeId()); for (String key : usages.keySet()) { Usage usage = getUsageResult(usages.get(key)); usage.setType(Usage.Type.INDIRECT); @@ -339,7 +336,7 @@ public Boolean doWork() throws Exception { } - public Usage getUsageResult(HashMap usage) { + public Usage getUsageResult(Map usage) { logger.info("starting"); Usage usageResult = new Usage(); usageResult.setAppUser((String) usage.get(CCConstants.CCM_PROP_USAGE_APPUSER)); diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/usage/UsageDAO.java b/Backend/services/core/src/main/java/org/edu_sharing/service/usage/UsageDAO.java index ec4baeaec0..bb981349d9 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/usage/UsageDAO.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/usage/UsageDAO.java @@ -1,33 +1,33 @@ package org.edu_sharing.service.usage; -import java.util.HashMap; +import java.util.Map; public interface UsageDAO { - public HashMap> getUsages(String nodeId); + Map> getUsages(String nodeId); - HashMap getUsageOnNodeOrParents(String lmsId, String courseId, String objectNodeId, String resourceId) throws Exception; + Map getUsageOnNodeOrParents(String lmsId, String courseId, String objectNodeId, String resourceId) throws Exception; - public HashMap getUsage(String lmsId, String courseId, String objectNodeId, String resourceId) throws Exception; + Map getUsage(String lmsId, String courseId, String objectNodeId, String resourceId) throws Exception; - public HashMap getUsage(String usageId) throws Exception; + Map getUsage(String usageId) throws Exception; - public HashMap> getUsagesByCourse(String lmsId, String courseId) throws Exception; + Map> getUsagesByCourse(String lmsId, String courseId) throws Exception; - public HashMap> getUsagesByAppId(String appId) throws Exception; + Map> getUsagesByAppId(String appId) throws Exception; - public HashMap> getUsages(String repositoryId, - String nodeId, - Long from, - Long to) throws Exception; + Map> getUsages(String repositoryId, + String nodeId, + Long from, + Long to) throws Exception; - public String createUsage(String parentId, HashMap properties); + String createUsage(String parentId, Map properties); - public void updateUsage(String usageNodeId, HashMap properties); + void updateUsage(String usageNodeId, Map properties); - public void removeUsage(String appId, String courseId, String parentNodeId, String resourceId) throws Exception; + void removeUsage(String appId, String courseId, String parentNodeId, String resourceId) throws Exception; - public boolean removeUsages(String appId,String courseId) throws Exception; + boolean removeUsages(String appId, String courseId) throws Exception; } diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/util/AlfrescoDaoHelper.java b/Backend/services/core/src/main/java/org/edu_sharing/service/util/AlfrescoDaoHelper.java index 0947eabf77..f88bddfe79 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/util/AlfrescoDaoHelper.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/util/AlfrescoDaoHelper.java @@ -13,7 +13,7 @@ public static NodeRef marshall(org.edu_sharing.service.model.NodeRef nodeRef){ } public static List marshall(List list){ - List nodeRefs = new ArrayList(); + List nodeRefs = new ArrayList<>(); for(org.edu_sharing.service.model.NodeRef nr : list){ nodeRefs.add(marshall(nr)); } diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/util/FillImpObjPropertiesCache.java b/Backend/services/core/src/main/java/org/edu_sharing/service/util/FillImpObjPropertiesCache.java index d5be995534..aa5e44f6ab 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/util/FillImpObjPropertiesCache.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/util/FillImpObjPropertiesCache.java @@ -1,6 +1,7 @@ package org.edu_sharing.service.util; import java.util.HashMap; +import java.util.Map; import org.apache.log4j.Logger; import org.edu_sharing.repository.client.tools.CCConstants; @@ -30,7 +31,7 @@ public void onApplicationEvent(ContextRefreshedEvent event) { MCAlfrescoAPIClient mcAlfrescoBaseClient = new MCAlfrescoAPIClient(); String companyHomeId = mcAlfrescoBaseClient.getCompanyHomeNodeId(); - HashMap importFolderProps = mcAlfrescoBaseClient.getChild(companyHomeId, CCConstants.CCM_TYPE_MAP, CCConstants.CM_NAME, + Map importFolderProps = mcAlfrescoBaseClient.getChild(companyHomeId, CCConstants.CCM_TYPE_MAP, CCConstants.CM_NAME, OAIPMHLOMImporter.FOLDER_NAME_IMPORTED_OBJECTS); if(importFolderProps == null || importFolderProps.isEmpty()) { @@ -38,7 +39,7 @@ public void onApplicationEvent(ContextRefreshedEvent event) { return; } - HashMap params = new HashMap(); + Map params = new HashMap<>(); params.put("rootFolderId", importFolderProps.get(CCConstants.SYS_PROP_NODE_UID)); params.put("sticky", "true"); try { diff --git a/Backend/services/core/src/main/java/org/edu_sharing/service/version/RepositoryVersionInfo.java b/Backend/services/core/src/main/java/org/edu_sharing/service/version/RepositoryVersionInfo.java index d3d497b0ec..30f7dfab07 100644 --- a/Backend/services/core/src/main/java/org/edu_sharing/service/version/RepositoryVersionInfo.java +++ b/Backend/services/core/src/main/java/org/edu_sharing/service/version/RepositoryVersionInfo.java @@ -32,7 +32,7 @@ public static class VersionTimestamp implements Serializable { public static class VersionMaven implements Serializable { - public HashMap bom; + public Map bom; public VersionProject project; public static class VersionProject implements Serializable { @@ -41,4 +41,4 @@ public static class VersionProject implements Serializable { public String version; } } -} \ No newline at end of file +} diff --git a/Backend/services/core/src/test/java/org/edu_sharing/repository/server/importer/RecordHandlerLOMTest.java b/Backend/services/core/src/test/java/org/edu_sharing/repository/server/importer/RecordHandlerLOMTest.java index 60917c6025..15891f965f 100644 --- a/Backend/services/core/src/test/java/org/edu_sharing/repository/server/importer/RecordHandlerLOMTest.java +++ b/Backend/services/core/src/test/java/org/edu_sharing/repository/server/importer/RecordHandlerLOMTest.java @@ -29,6 +29,7 @@ import java.util.ArrayList; import java.util.HashMap; +import java.util.List; import java.util.Map; import javax.xml.xpath.XPath; @@ -48,15 +49,15 @@ public class RecordHandlerLOMTest implements RecordHandlerInterface { private PersistentHandlerInterface persistentHandler = new PersistentHandlerDB(); - ArrayList keys = new ArrayList(); + List keys = new ArrayList<>(); - ArrayList> allDS = new ArrayList>(); + List> allDS =new ArrayList<>(); @Override public void handleRecord(Node nodeRecord, String cursor, String set) throws Throwable { // TODO Auto-generated method stub - HashMap toSafe = new HashMap(); + Map toSafe = new HashMap<>(); Node node = (Node) xpath.evaluate("metadata/lom", nodeRecord, XPathConstants.NODE); this.handleNode(node, "", toSafe); @@ -78,7 +79,7 @@ public void handleRecord(Node nodeRecord, String cursor, String set) throws Thro } - private void handleNode(Node nodeRecord, String path, HashMap toSafe) throws Exception { + private void handleNode(Node nodeRecord, String path, Map toSafe) throws Exception { NodeList metadataNodeList = (NodeList) xpath.evaluate("*", nodeRecord, XPathConstants.NODESET); for (int i = 0; i < metadataNodeList.getLength(); i++) { Node child = metadataNodeList.item(i); @@ -102,7 +103,7 @@ private void handleNode(Node nodeRecord, String path, HashMap to } @Override - public HashMap getProperties() { + public Map getProperties() { // TODO Auto-generated method stub return null; } diff --git a/Backend/services/core/src/test/java/org/edu_sharing/repository/server/jobs/quartz/RemoveNodeVersionsJobTest.java b/Backend/services/core/src/test/java/org/edu_sharing/repository/server/jobs/quartz/RemoveNodeVersionsJobTest.java index cb0fd10508..68db975e74 100644 --- a/Backend/services/core/src/test/java/org/edu_sharing/repository/server/jobs/quartz/RemoveNodeVersionsJobTest.java +++ b/Backend/services/core/src/test/java/org/edu_sharing/repository/server/jobs/quartz/RemoveNodeVersionsJobTest.java @@ -39,16 +39,16 @@ class RemoveNodeVersionsJobTest { public String blocked1Label = RemoveNodeVersionsJob.BLOCKED_VERSION_LABELS.get(0); public String blocked2Label = RemoveNodeVersionsJob.BLOCKED_VERSION_LABELS.get(1); - private NodeRef node = new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, "current"); - private NodeRef nodeV1 = new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, "v1"); - private NodeRef nodeV2 = new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, "v2"); - private NodeRef nodeV3 = new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, "v3"); - private NodeRef nodeV4 = new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, "v4"); - private NodeRef nodeV5 = new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, "v5"); - private NodeRef nodeV6 = new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, "v6"); + private final NodeRef node = new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, "current"); + private final NodeRef nodeV1 = new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, "v1"); + private final NodeRef nodeV2 = new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, "v2"); + private final NodeRef nodeV3 = new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, "v3"); + private final NodeRef nodeV4 = new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, "v4"); + private final NodeRef nodeV5 = new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, "v5"); + private final NodeRef nodeV6 = new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, "v6"); - private NodeRef nodeBlocked1 = new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, "blocked1"); - private NodeRef nodeBlocked2 = new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, "blocked2"); + private final NodeRef nodeBlocked1 = new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, "blocked1"); + private final NodeRef nodeBlocked2 = new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, "blocked2"); @Mock private Usage2Service usage2Service; @@ -337,4 +337,4 @@ void GetUsagesThrowsException() throws Exception { // then verify(versionService, never()).deleteVersion(nodeArgumentCaptor.capture(), versionArgumentCaptor.capture()); } -} \ No newline at end of file +} diff --git a/Backend/services/core/src/test/java/org/edu_sharing/repository/server/jobs/quartz/Test.java b/Backend/services/core/src/test/java/org/edu_sharing/repository/server/jobs/quartz/Test.java index a5429cf84c..590ad0d4c8 100644 --- a/Backend/services/core/src/test/java/org/edu_sharing/repository/server/jobs/quartz/Test.java +++ b/Backend/services/core/src/test/java/org/edu_sharing/repository/server/jobs/quartz/Test.java @@ -7,6 +7,7 @@ import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathFactory; +import lombok.Getter; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.edu_sharing.repository.server.importer.PersistentHandlerInterface; @@ -60,9 +61,11 @@ public boolean exists(String replId) { private static class TestRecordHandler implements RecordHandlerInterface{ - HashMap replicationIdCounter = new HashMap(); + @Getter + Map replicationIdCounter = new HashMap<>(); - HashMap replicationSourceCounter = new HashMap(); + @Getter + Map replicationSourceCounter = new HashMap<>(); Log logger = LogFactory.getLog(RecordHandlerLOM.class); XPathFactory pfactory = XPathFactory.newInstance(); @@ -70,9 +73,10 @@ private static class TestRecordHandler implements RecordHandlerInterface{ - int counter = 0; + @Getter + int counter = 0; @Override - public HashMap getProperties() { + public Map getProperties() { // TODO Auto-generated method stub return null; } @@ -99,18 +103,7 @@ public void handleRecord(Node nodeRecord, String cursor, String set) throws Thro replicationSourceCounter.put(lomCatalogId, sourceCounter++); } } - - public int getCounter() { - return counter; - } - - public HashMap getReplicationIdCounter() { - return replicationIdCounter; - } - - public HashMap getReplicationSourceCounter() { - return replicationSourceCounter; - } - } + + } } diff --git a/Backend/services/core/src/test/java/org/edu_sharing/service/feedback/FeedbackServiceImplTest.java b/Backend/services/core/src/test/java/org/edu_sharing/service/feedback/FeedbackServiceImplTest.java index 3816aab992..7893c59055 100644 --- a/Backend/services/core/src/test/java/org/edu_sharing/service/feedback/FeedbackServiceImplTest.java +++ b/Backend/services/core/src/test/java/org/edu_sharing/service/feedback/FeedbackServiceImplTest.java @@ -65,7 +65,7 @@ void setUp() { authorityServiceHelperMockedStatic = Mockito.mockStatic(AuthorityServiceHelper.class); authorityServiceFactoryMockedStatic = Mockito.mockStatic(AuthorityServiceFactory.class); AuthorityServiceImpl authorityServiceMock = Mockito.mock(AuthorityServiceImpl.class); - authorityServiceFactoryMockedStatic.when(() -> AuthorityServiceFactory.getLocalService()).thenReturn(authorityServiceMock); + authorityServiceFactoryMockedStatic.when(AuthorityServiceFactory::getLocalService).thenReturn(authorityServiceMock); Mockito.lenient().when(authorityServiceMock.isGuest()).thenReturn(false); authenticationUtilMockedStatic = Mockito.mockStatic(AuthenticationUtil.class); contextMockedStatic = Mockito.mockStatic(Context.class); @@ -76,7 +76,7 @@ void setUp() { authorityServiceHelperMockedStatic.when(() -> AuthorityServiceHelper.getAuthorityNodeRef(userId)).thenReturn(userNodeRef); authenticationUtilMockedStatic.when(AuthenticationUtil::getFullyAuthenticatedUser).thenReturn(userId); authenticationUtilMockedStatic.when(AuthenticationUtil.runAsSystem(any())).thenAnswer(invocation -> - ((AuthenticationUtil.RunAsWork) invocation.getArgument(0)).doWork() + ((AuthenticationUtil.RunAsWork) invocation.getArgument(0)).doWork() ); authenticationUtilMockedStatic.when( (MockedStatic.Verification) AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.SYSTEM_USER_NAME) @@ -93,15 +93,14 @@ void teardown() { contextMockedStatic.close(); } - @SneakyThrows @RepeatedTest(value = 5, name = RepeatedTest.LONG_DISPLAY_NAME) - void getFeedback() { + void getFeedback() throws Throwable { String nodeId = UUID.randomUUID().toString(); Map> expected = new HashMap<>(); - HashMap> expectedData = getSampleData(); - for(int i = 0; i < 100; i++) { + Map> expectedData = getSampleData(); + for (int i = 0; i < 100; i++) { String childId = UUID.randomUUID().toString(); - expected.put(childId, new HashMap(){{ + expected.put(childId, new HashMap<>() {{ put(CCConstants.CCM_PROP_MATERIAL_FEEDBACK_AUTHORITY, UUID.randomUUID().toString()); put(CCConstants.CCM_PROP_MATERIAL_FEEDBACK_DATA, new Gson().toJson(expectedData, new TypeToken(){}.getType())); put(CCConstants.CM_PROP_C_CREATED, new Date((long) (Math.random() * Long.MAX_VALUE))); @@ -130,7 +129,7 @@ void getFeedback() { List> expectedSorted = expected.values().stream().sorted( (a, b) -> ((Date) b.get(CCConstants.CM_PROP_C_MODIFIED)).compareTo((Date) a.get(CCConstants.CM_PROP_C_MODIFIED)) ).collect(Collectors.toList()); - for(int i = 0; i < result.size(); i++) { + for (int i = 0; i < result.size(); i++) { FeedbackData actual = result.get(i); Map expectedEntry = expectedSorted.get(i); assertEquals(expectedEntry.get(CCConstants.CCM_PROP_MATERIAL_FEEDBACK_AUTHORITY), actual.getAuthority()); @@ -140,22 +139,20 @@ void getFeedback() { } } - @NotNull - private HashMap> getSampleData() { - HashMap> expectedData = new HashMap<>(); + private Map> getSampleData() { + Map> expectedData = new HashMap<>(); expectedData.put("key1", new ArrayList<>(Arrays.asList("value1", UUID.randomUUID().toString()))); expectedData.put("key2", new ArrayList<>(Arrays.asList("value1", "value2", UUID.randomUUID().toString()))); return expectedData; } - @Test @RepeatedTest(value = 5, name = RepeatedTest.LONG_DISPLAY_NAME) void addFeedbackMultiple() { String nodeId = UUID.randomUUID().toString(); String newNodeId = UUID.randomUUID().toString(); - HashMap> testData = getSampleData(); + Map> testData = getSampleData(); - HashMap expectedMap = new HashMap() {{ + Map expectedMap = new HashMap<>() {{ put( CCConstants.CCM_PROP_MATERIAL_FEEDBACK_AUTHORITY, DigestUtils.sha1Hex(userId + userEsId) @@ -188,14 +185,14 @@ void addFeedbackMultiple() { expectedMap.put(CCConstants.CCM_PROP_MATERIAL_FEEDBACK_AUTHORITY, DigestUtils.sha1Hex(sessionId + userEsId)); assertEquals(new FeedbackResult(newNodeId, false), underTest.addFeedback(nodeId, testData)); } - @Test + @RepeatedTest(value = 5, name = RepeatedTest.LONG_DISPLAY_NAME) void addFeedbackSingle() { String nodeId = UUID.randomUUID().toString(); NodeRef updateNodeRef = new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, UUID.randomUUID().toString()); - HashMap> testData = getSampleData(); + Map> testData = getSampleData(); - HashMap expectedMap = new HashMap() {{ + Map expectedMap = new HashMap<>() {{ put( CCConstants.CCM_PROP_MATERIAL_FEEDBACK_AUTHORITY, DigestUtils.sha1Hex(userId + userEsId) @@ -227,16 +224,15 @@ void addFeedbackSingle() { ); } - @Test @RepeatedTest(value = 5, name = RepeatedTest.LONG_DISPLAY_NAME) void deleteUserData() { try (MockedStatic cmisSearchHelperMockedStatic = Mockito.mockStatic(CMISSearchHelper.class)) { - Map filters=new HashMap() {{ + Map filters = new HashMap<>() {{ put(CCConstants.CCM_PROP_MATERIAL_FEEDBACK_AUTHORITY, DigestUtils.sha1Hex(userId + userEsId)); }}; List list = new ArrayList<>(); int randListSize = (int) (1 + Math.random() * 100); - for(int i = 0;i < randListSize; i++) { + for (int i = 0; i < randListSize; i++) { list.add(new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, UUID.randomUUID().toString())); } cmisSearchHelperMockedStatic.when(() -> CMISSearchHelper.fetchNodesByTypeAndFilters(eq(CCConstants.CCM_TYPE_MATERIAL_FEEDBACK), eq(filters))).thenReturn( @@ -263,15 +259,15 @@ void deleteUserData() { void changeUserData() { try (MockedStatic cmisSearchHelperMockedStatic = Mockito.mockStatic(CMISSearchHelper.class)) { String newUserId = UUID.randomUUID().toString(); - Map filtersObfuscate=new HashMap() {{ + Map filtersObfuscate = new HashMap<>() {{ put(CCConstants.CCM_PROP_MATERIAL_FEEDBACK_AUTHORITY, DigestUtils.sha1Hex(userId + userEsId)); }}; - Map filtersFull=new HashMap() {{ + Map filtersFull = new HashMap<>() {{ put(CCConstants.CCM_PROP_MATERIAL_FEEDBACK_AUTHORITY, userId); }}; List list = new ArrayList<>(); int randListSize = (int) (1 + Math.random() * 100); - for(int i = 0;i < randListSize; i++) { + for (int i = 0; i < randListSize; i++) { list.add(new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, UUID.randomUUID().toString())); } cmisSearchHelperMockedStatic.when(() -> CMISSearchHelper.fetchNodesByTypeAndFilters(eq(CCConstants.CCM_TYPE_MATERIAL_FEEDBACK), eq(filtersFull))).thenReturn( @@ -308,6 +304,5 @@ void changeUserData() { ); } - } -} \ No newline at end of file +} diff --git a/Backend/services/core/src/test/java/org/edu_sharing/service/permission/PermissionCheckingTest.java b/Backend/services/core/src/test/java/org/edu_sharing/service/permission/PermissionCheckingTest.java index 0dbd122c57..ea8f727706 100644 --- a/Backend/services/core/src/test/java/org/edu_sharing/service/permission/PermissionCheckingTest.java +++ b/Backend/services/core/src/test/java/org/edu_sharing/service/permission/PermissionCheckingTest.java @@ -230,7 +230,7 @@ void singleNodeRef_failedNodePermissionTest() throws InsufficientPermissionExcep // given String authority = "Muster"; NodeRefImpl nodeA = new NodeRefImpl("1"); - nodeA.setPermissions(new HashMap(){{ + nodeA.setPermissions(new HashMap<>(){{ put("someNodePermission", false); }}); @@ -256,7 +256,7 @@ void singleNodeRef_successNodePermissionTest() throws InsufficientPermissionExce // given String authority = "Muster"; NodeRefImpl nodeA = new NodeRefImpl("1"); - nodeA.setPermissions(new HashMap(){{ + nodeA.setPermissions(new HashMap<>(){{ put("someNodePermission", true); }}); diff --git a/Backend/services/core/src/test/java/org/edu_sharing/service/rendering/RenderingServiceImplTest.java b/Backend/services/core/src/test/java/org/edu_sharing/service/rendering/RenderingServiceImplTest.java index c8841b3e93..d949455e78 100644 --- a/Backend/services/core/src/test/java/org/edu_sharing/service/rendering/RenderingServiceImplTest.java +++ b/Backend/services/core/src/test/java/org/edu_sharing/service/rendering/RenderingServiceImplTest.java @@ -64,7 +64,7 @@ void setUp() { List connectors = new ArrayList<>(); Connector connector = new Connector(); connector.setId("test_not_editable"); - connector.setFiletypes(Arrays.asList( + connector.setFiletypes(List.of( fileTypeNotEditable )); connector.setHasViewMode(true); @@ -72,7 +72,7 @@ void setUp() { connector = new Connector(); connector.setId("test_mime_basic_view"); - connector.setFiletypes(Arrays.asList( + connector.setFiletypes(List.of( fileTypeBasic )); connector.setHasViewMode(true); @@ -110,7 +110,7 @@ void teardown() { @RepeatedTest(value = 5, name = RepeatedTest.LONG_DISPLAY_NAME) void getAvailableEditorsWithVersion() { List editors = underTest.getAvailableEditors(UUID.randomUUID().toString(), - String.valueOf(new Integer((int) (Math.random() * 10000))), + String.valueOf(Integer.valueOf((int) (Math.random() * 10000))), UUID.randomUUID().toString() ); assertEquals(0, editors.size()); @@ -195,4 +195,4 @@ void getAvailableEditors() { assertEquals("test_mime_zip_specific", actual.get(1).getId()); } -} \ No newline at end of file +} diff --git a/Backend/services/core/src/test/java/org/edu_sharing/service/search/SearchServiceDDBImplTest.java b/Backend/services/core/src/test/java/org/edu_sharing/service/search/SearchServiceDDBImplTest.java index a06b82168f..3dd29e7597 100644 --- a/Backend/services/core/src/test/java/org/edu_sharing/service/search/SearchServiceDDBImplTest.java +++ b/Backend/services/core/src/test/java/org/edu_sharing/service/search/SearchServiceDDBImplTest.java @@ -18,7 +18,7 @@ import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.context.ApplicationContext; -import java.util.HashMap; +import java.util.Map; import static org.junit.jupiter.api.Assertions.*; @@ -28,10 +28,8 @@ class SearchServiceDDBImplTest { private SearchServiceDDBImpl underTestSearch; private MockedStatic applicationInfoListMockedStatic; private MockedStatic alfAppContextGateMockedStatic; - private String apiKey = ""; + private final String apiKey = ""; private NodeServiceDDBImpl underTestNode; - private String nodeId1 = "2HJYZQEWG4DK3GK5LGPEGJJYRTOPYM7T"; - private String nodeId2 = "P5HVKHUWVSTR7QXJ3TF5RP47GJU34WOP"; @BeforeEach void setUp() { @@ -39,7 +37,7 @@ void setUp() { alfAppContextGateMockedStatic = Mockito.mockStatic(AlfAppContextGate.class); ApplicationContext applicationContextMock = Mockito.mock(ApplicationContext.class); Mockito.when(applicationContextMock.getBean(ArgumentMatchers.anyString())).thenReturn(null); - alfAppContextGateMockedStatic.when(() -> AlfAppContextGate.getApplicationContext()).thenReturn(applicationContextMock); + alfAppContextGateMockedStatic.when(AlfAppContextGate::getApplicationContext).thenReturn(applicationContextMock); applicationInfoListMockedStatic = Mockito.mockStatic(ApplicationInfoList.class); ApplicationInfo dummyInfo = Mockito.mock(ApplicationInfo.class); @@ -64,7 +62,7 @@ void searchDDB() { throw new RuntimeException(e); } });*/ - assertTrue(result.getData().size() > 0); + assertFalse(result.getData().isEmpty()); } catch (Exception e) { throw new RuntimeException(e); } @@ -72,7 +70,8 @@ void searchDDB() { @Test void fetchNode() { try { - HashMap result1 = underTestNode.getProperties(null, null, this.nodeId1); + String nodeId1 = "2HJYZQEWG4DK3GK5LGPEGJJYRTOPYM7T"; + Map result1 = underTestNode.getProperties(null, null, nodeId1); assertEquals("Mathes, Alban", result1.get(CCConstants.LOM_PROP_GENERAL_TITLE)); assertEquals("Hierarchie: Indigenatsgesuche\n" + "Geburtsdatum: 19.07.1860 - Antragsdatum: 1899 - Religion: ev - Indexbegriff Person: Gottschämmer, Barbara - Indexbegriff Person: Mathes, Barbara - Indexbegriff Person: Mathes, Elsa Martha - Indexbegriff Person: Mathes, Rudolf - Indexbegriff Person: Mathes, Wilhelmina - Indexbegriff Ort: Geburtsort: Schönheide - Indexbegriff Ort: Geburtsort: Sachsen - Indexbegriff Sache: Klassifikation C-Bestände: Gesuche 1899", result1.get(CCConstants.LOM_PROP_GENERAL_DESCRIPTION)); @@ -80,7 +79,8 @@ void fetchNode() { // assertEquals(4, ((List)result1.get(CCConstants.LOM_PROP_GENERAL_KEYWORD)).size()); - HashMap result2 = underTestNode.getProperties(null, null, this.nodeId2); + String nodeId2 = "P5HVKHUWVSTR7QXJ3TF5RP47GJU34WOP"; + Map result2 = underTestNode.getProperties(null, null, nodeId2); assertEquals("Mathes, Philipp", result2.get(CCConstants.LOM_PROP_GENERAL_TITLE)); assertEquals(VCardTool.nameToVCard("Hessisches Hauptstaatsarchiv"), result2.get(CCConstants.CCM_PROP_IO_REPL_LIFECYCLECONTRIBUTER_PUBLISHER)); assertEquals("Hierarchie: Herzogtum Nassau: Amt Wiesbaden >> 30 Freiwillige Gerichtsbarkeit >> 30.16 Wiesbaden\n" + @@ -90,10 +90,10 @@ void fetchNode() { assertEquals("Wed Mar 01 14:00:16 CET 2023", result2.get(CCConstants.CM_PROP_C_MODIFIED).toString()); assertEquals(CCConstants.COMMON_LICENSE_CC_ZERO, result2.get(CCConstants.CCM_PROP_IO_COMMONLICENSE_KEY)); - HashMap result3 = underTestNode.getProperties(null, null, "7TB7U4SGT5F5ONT6HI4JDUD6HWMWGP7H"); + Map result3 = underTestNode.getProperties(null, null, "7TB7U4SGT5F5ONT6HI4JDUD6HWMWGP7H"); assertEquals("100 DDR-Aktfotos :die schönsten Frauen", result3.get(CCConstants.LOM_PROP_GENERAL_TITLE)); } catch (Throwable e) { throw new RuntimeException(e); } } -} \ No newline at end of file +} diff --git a/Backend/services/soap/server/src/main/java/org/edu_sharing/webservices/alfresco/extension/InstanceUsage.java b/Backend/services/soap/server/src/main/java/org/edu_sharing/webservices/alfresco/extension/InstanceUsage.java index 10e6669812..28037936f0 100644 --- a/Backend/services/soap/server/src/main/java/org/edu_sharing/webservices/alfresco/extension/InstanceUsage.java +++ b/Backend/services/soap/server/src/main/java/org/edu_sharing/webservices/alfresco/extension/InstanceUsage.java @@ -53,9 +53,9 @@ public void start() throws Exception{ private void count(String parentId) throws RemoteException { System.out.println("Instance:" + naw.getProperties(parentId).get(CCConstants.CM_NAME)); - HashMap nodes = naw.getChildren(parentId, null); + Map nodes = naw.getChildren(parentId, null); for(Map.Entry entry : nodes.entrySet()) { - HashMap nodeProps = (HashMap)entry.getValue(); + Map nodeProps = (HashMap<>)entry.getValue(); String type = (String)nodeProps.get(CCConstants.NODETYPE); System.out.println("nodeType:" + type + " " + nodeProps.get(CCConstants.CM_NAME) + " size:"+size + " MB:" + ((size /1000)/1000) +" Date:" + new Date()); diff --git a/Backend/services/soap/server/src/main/java/org/edu_sharing/webservices/alfresco/extension/NativeAlfrescoWrapperSoapBindingImpl.java b/Backend/services/soap/server/src/main/java/org/edu_sharing/webservices/alfresco/extension/NativeAlfrescoWrapperSoapBindingImpl.java index 7a6325cc32..e0a9dfdc98 100644 --- a/Backend/services/soap/server/src/main/java/org/edu_sharing/webservices/alfresco/extension/NativeAlfrescoWrapperSoapBindingImpl.java +++ b/Backend/services/soap/server/src/main/java/org/edu_sharing/webservices/alfresco/extension/NativeAlfrescoWrapperSoapBindingImpl.java @@ -277,7 +277,7 @@ private Object getValue(String property, String _value) { Map transformKeysToQName(HashMap map){ try { - Map result = new HashMap(); + Map result = new HashMap<>(); for (Object key : map.keySet()) { result.put(QName.createQName((String) key), (Serializable) map.get(key)); } @@ -290,7 +290,7 @@ Map transformKeysToQName(HashMap map){ Map transformPropMap(HashMap map) { try { - Map result = new HashMap(); + Map result = new HashMap<>(); for (Object key : map.keySet()) { String value = (String) map.get(key); // test if its xml @@ -386,7 +386,7 @@ private String[] search(String store, String luceneQuery, String permission) thr logger.info("found " + resultSet.length() + " nodes"); List resultNodeRefs = resultSet.getNodeRefs(); - List nodeIds = new ArrayList(); + List nodeIds = new ArrayList<>(); for (NodeRef nodeRef : resultNodeRefs) { if (permission != null && !permission.trim().equals("")) { @@ -428,7 +428,7 @@ public RepositoryNode[] searchNodes(String store, String luceneQuery, String per StoreRef storeRef = new StoreRef(store); String[] nodeIds = this.search(store, luceneQuery, permission); - List searchResults = new ArrayList(); + List searchResults = new ArrayList<>(); if (nodeIds != null) { MCAlfrescoAPIClient mcAlfrescoAPIClient = new MCAlfrescoAPIClient(); @@ -437,7 +437,7 @@ public RepositoryNode[] searchNodes(String store, String luceneQuery, String per RepositoryNode rn = new RepositoryNode(); rn.setNodeId(nodeId); - List resultProps = new ArrayList(); + List resultProps = new ArrayList<>(); if (propertiesToReturn != null && propertiesToReturn.length > 0) { @@ -523,10 +523,10 @@ public SearchResult searchSolr(String query, int startIdx, int nrOfresults, Stri if(nativeResult != null){ SearchResult remoteResult = new SearchResult(); - HashMap> nodes = nativeResult.getData(); + Map> nodes = nativeResult.getData(); RepositoryNode[] remoteNodes = new RepositoryNode[nodes.size()]; int i = 0; - for(HashMap localProps : nodes.values() ){ + for(Map localProps : nodes.values() ){ String nodeId = (String)localProps.get(CCConstants.SYS_PROP_NODE_UID); KeyValue[] remoteProps = new KeyValue[localProps.size()]; int j = 0; @@ -545,7 +545,7 @@ public SearchResult searchSolr(String query, int startIdx, int nrOfresults, Stri if(nativeFacettes != null){ - List remoteFacettes = new ArrayList(); + List remoteFacettes = new ArrayList<>(); for(Map.Entry> entry : nativeFacettes.entrySet()){ Facette remoteFacette = new Facette(); @@ -612,12 +612,12 @@ public RepositoryNode[] getVersionHistory(String nodeId) throws RemoteException try { MCAlfrescoAPIClient mcAlfrescoAPIClient = new MCAlfrescoAPIClient(); - HashMap> versionHistory = mcAlfrescoAPIClient.getVersionHistory(nodeId); + Map> versionHistory = mcAlfrescoAPIClient.getVersionHistory(nodeId); - List result = new ArrayList(); + List result = new ArrayList<>(); if(versionHistory != null){ - for(Map.Entry> entry : versionHistory.entrySet()){ - List keyValueList = new ArrayList(); + for(Map.Entry> entry : versionHistory.entrySet()){ + List keyValueList = new ArrayList<>(); for(Object propKey : entry.getValue().keySet()){ keyValueList.add(new KeyValue((String)propKey, (String)entry.getValue().get(propKey))); } @@ -731,12 +731,12 @@ public SearchResult findGroups(String searchWord, String eduGroupNodeId, int fro SearchResult sr = new SearchResult(); sr.setStartIDX(apiResult.getStartIDX()); sr.setNodeCount(apiResult.getNodeCount()); - List repoNodes = new ArrayList(); + List repoNodes = new ArrayList<>(); sr.setData(repoNodes.toArray(new RepositoryNode[repoNodes.size()])); for(Group group: apiResult.getData()){ RepositoryNode repoNode = new RepositoryNode(); repoNode.setNodeId(group.getNodeId()); - List props = new ArrayList(); + List props = new ArrayList<>(); props.add(new KeyValue(CCConstants.CM_PROP_AUTHORITY_AUTHORITYDISPLAYNAME, group.getDisplayName())); props.add(new KeyValue(CCConstants.CM_PROP_AUTHORITY_AUTHORITYNAME, group.getName())); props.add(new KeyValue(CCConstants.SYS_PROP_NODE_UID, group.getNodeId())); @@ -770,12 +770,12 @@ public SearchResult findUsers(KeyValue[] searchProps, String eduGroupNodeId, int SearchResult sr = new SearchResult(); sr.setStartIDX(apiResult.getStartIDX()); sr.setNodeCount(apiResult.getNodeCount()); - List repoNodes = new ArrayList(); + List repoNodes = new ArrayList<>(); sr.setData(repoNodes.toArray(new RepositoryNode[repoNodes.size()])); for(User user: apiResult.getData()){ RepositoryNode repoNode = new RepositoryNode(); repoNode.setNodeId(user.getNodeId()); - List props = new ArrayList(); + List props = new ArrayList<>(); props.add(new KeyValue(CCConstants.CM_PROP_PERSON_EMAIL, user.getEmail())); props.add(new KeyValue(CCConstants.CM_PROP_PERSON_FIRSTNAME, user.getGivenName())); props.add(new KeyValue(CCConstants.CM_PROP_PERSON_LASTNAME, user.getSurname())); @@ -800,7 +800,7 @@ public KeyValue[] getEduGroupContextOfNode(String nodeId) throws RemoteException MCAlfrescoAPIClient mcAlfrescoAPIClient = new MCAlfrescoAPIClient(); Group group = mcAlfrescoAPIClient.getEduGroupContextOfNode(nodeId); - List props = new ArrayList(); + List props = new ArrayList<>(); if(group != null){ props.add(new KeyValue(CCConstants.CM_PROP_AUTHORITY_AUTHORITYDISPLAYNAME, group.getDisplayName())); props.add(new KeyValue(CCConstants.CM_PROP_AUTHORITY_AUTHORITYNAME, group.getName())); @@ -1487,12 +1487,12 @@ public UserDetails[] getUserDetails(String[] userNames) try { MCAlfrescoAPIClient mcAlfrescoAPIClient = new MCAlfrescoAPIClient(); - List result = new ArrayList(); + List result = new ArrayList<>(); for (String userName : userNames) { if (userName == null) { continue; } - HashMap userInfo = mcAlfrescoAPIClient.getUserInfo(userName); + Map userInfo = mcAlfrescoAPIClient.getUserInfo(userName); if (userInfo == null) { continue; } @@ -1521,7 +1521,7 @@ public void setUserDetails(UserDetails[] userDetails) throws RemoteException { if (userDetail == null) { continue; } - HashMap userInfo = new HashMap(); + Map userInfo = new HashMap<>(); userInfo.put(CCConstants.PROP_USERNAME, userDetail.getUserName()); userInfo.put(CCConstants.PROP_USER_FIRSTNAME, userDetail.getFirstName()); userInfo.put(CCConstants.PROP_USER_LASTNAME, userDetail.getLastName()); @@ -1572,7 +1572,7 @@ public GroupDetails[] getGroupDetails(String[] groupNames) try { MCAlfrescoAPIClient mcAlfrescoAPIClient = new MCAlfrescoAPIClient(); - List result = new ArrayList(); + List result = new ArrayList<>(); for (String groupName : groupNames) { if (groupName == null) { continue; diff --git a/Backend/services/soap/server/src/main/java/org/edu_sharing/webservices/authbyapp/AuthbyappSoapBindingImpl.java b/Backend/services/soap/server/src/main/java/org/edu_sharing/webservices/authbyapp/AuthbyappSoapBindingImpl.java index 8223097728..322a184a8a 100644 --- a/Backend/services/soap/server/src/main/java/org/edu_sharing/webservices/authbyapp/AuthbyappSoapBindingImpl.java +++ b/Backend/services/soap/server/src/main/java/org/edu_sharing/webservices/authbyapp/AuthbyappSoapBindingImpl.java @@ -52,7 +52,7 @@ public org.edu_sharing.webservices.authentication.AuthenticationResult authentic log.info("Client ipAddress:"+ipAddress); log.info("AuthClass:"+eduAuthenticationService.getClass().getName()); - HashMap ssoDataMap = new HashMap(); + Map ssoDataMap = new HashMap<>(); try{ @@ -79,7 +79,7 @@ public org.edu_sharing.webservices.authentication.AuthenticationResult authentic * Attention if you put an username that does not exist, alfresco creates a ne person object without an user object in user store * watch out for Alfresco class PersonServiceImpl */ - HashMap userProps = eduAuthenticationService.getPersonProperties(eduAuthenticationService.getCurrentUserName()); + Map userProps = eduAuthenticationService.getPersonProperties(eduAuthenticationService.getCurrentUserName()); String localemail = userProps.get(CCConstants.CM_PROP_PERSON_EMAIL); String localFirstname = userProps.get(CCConstants.CM_PROP_PERSON_FIRSTNAME); String localLastname = userProps.get(CCConstants.CM_PROP_PERSON_LASTNAME); diff --git a/Backend/services/soap/server/src/main/java/org/edu_sharing/webservices/authentication/AuthenticationSoapBindingImpl.java b/Backend/services/soap/server/src/main/java/org/edu_sharing/webservices/authentication/AuthenticationSoapBindingImpl.java index 341a68af5f..ab2ef62911 100644 --- a/Backend/services/soap/server/src/main/java/org/edu_sharing/webservices/authentication/AuthenticationSoapBindingImpl.java +++ b/Backend/services/soap/server/src/main/java/org/edu_sharing/webservices/authentication/AuthenticationSoapBindingImpl.java @@ -77,7 +77,7 @@ public AuthenticationResult authenticateByApp(java.lang.String applicationId, ja * Attention if you put an username that does not exist, alfresco creates a ne person object without an user object in user store * watch out for Alfresco class PersonServiceImpl */ - HashMap userProps = eduAuthenticationService.getPersonProperties(eduAuthenticationService.getCurrentUserName()); + Map userProps = eduAuthenticationService.getPersonProperties(eduAuthenticationService.getCurrentUserName()); String localemail = userProps.get(CCConstants.CM_PROP_PERSON_EMAIL); String localFirstname = userProps.get(CCConstants.CM_PROP_PERSON_FIRSTNAME); String localLastname = userProps.get(CCConstants.CM_PROP_PERSON_LASTNAME); @@ -120,7 +120,7 @@ public AuthenticationResult authenticateByTrustedApp(String applicationId, Strin try{ - HashMap ssoDataMap = new HashMap(); + Map ssoDataMap = new HashMap<>(); //add sso data for(KeyValue kv : ssoData){ @@ -145,7 +145,7 @@ public AuthenticationResult authenticateByTrustedApp(String applicationId, Strin * Attention if you put an username that does not exist, alfresco creates a ne person object without an user object in user store * watch out for Alfresco class PersonServiceImpl */ - HashMap userProps = eduAuthenticationService.getPersonProperties(eduAuthenticationService.getCurrentUserName()); + Map userProps = eduAuthenticationService.getPersonProperties(eduAuthenticationService.getCurrentUserName()); String localemail = userProps.get(CCConstants.CM_PROP_PERSON_EMAIL); String localFirstname = userProps.get(CCConstants.CM_PROP_PERSON_FIRSTNAME); String localLastname = userProps.get(CCConstants.CM_PROP_PERSON_LASTNAME); diff --git a/Backend/services/soap/server/src/main/java/org/edu_sharing/webservices/crud/CrudSoapBindingImpl.java b/Backend/services/soap/server/src/main/java/org/edu_sharing/webservices/crud/CrudSoapBindingImpl.java index 11c371a0ae..49d4421905 100644 --- a/Backend/services/soap/server/src/main/java/org/edu_sharing/webservices/crud/CrudSoapBindingImpl.java +++ b/Backend/services/soap/server/src/main/java/org/edu_sharing/webservices/crud/CrudSoapBindingImpl.java @@ -91,7 +91,7 @@ public java.lang.String create(java.lang.String username, java.lang.String ticke PostMethod method = new PostMethod(servletUrl); - ArrayList partsList = new ArrayList(); + ArrayList partsList = new ArrayList<>(); partsList.add(new StringPart(CCConstants.AUTH_USERNAME, username)); partsList.add(new StringPart(CCConstants.AUTH_TICKET, ticket)); partsList.add(new StringPart(CCConstants.NODETYPE, nodeType)); @@ -165,7 +165,7 @@ public java.lang.String update(java.lang.String username, java.lang.String ticke PostMethod method = new PostMethod(servletUrl); - ArrayList partsList = new ArrayList(); + ArrayList partsList = new ArrayList<>(); partsList.add(new StringPart(CCConstants.AUTH_USERNAME, username)); partsList.add(new StringPart(CCConstants.AUTH_TICKET, ticket)); diff --git a/Backend/services/soap/server/src/main/java/org/edu_sharing/webservices/render/RenderInfoSoapBindingImpl.java b/Backend/services/soap/server/src/main/java/org/edu_sharing/webservices/render/RenderInfoSoapBindingImpl.java index 40b3eac657..6f762833b1 100644 --- a/Backend/services/soap/server/src/main/java/org/edu_sharing/webservices/render/RenderInfoSoapBindingImpl.java +++ b/Backend/services/soap/server/src/main/java/org/edu_sharing/webservices/render/RenderInfoSoapBindingImpl.java @@ -58,7 +58,7 @@ public RenderInfoResult getRenderInfoLMS(String userName, String nodeId, String // now done when delegating to render @RenderProxy UsageDAO usageDao = new AlfServicesWrapper(); if(lmsId!=null && courseId!=null) { - HashMap usageMap = usageDao.getUsageOnNodeOrParents(lmsId, courseId, nodeId, resourceId); + Map usageMap = usageDao.getUsageOnNodeOrParents(lmsId, courseId, nodeId, resourceId); if (usageMap != null) { result.setUsage(transform(new UsageService().getUsageResult(usageMap))); } @@ -137,7 +137,7 @@ private RenderInfoResult getBaseData(String userName, String nodeId, String vers RenderInfoResult rir = new RenderInfoResult(); - HashMap userInfo = client.getUserInfo(userName); + Map userInfo = client.getUserInfo(userName); if(userInfo == null){ throw new RemoteException(EXCEPTION_USER_DOES_NOT_EXISTS); } @@ -158,15 +158,15 @@ private RenderInfoResult getBaseData(String userName, String nodeId, String vers String finalUserName = userName; LogTime.log("Fetching permissions for node "+nodeId,()-> { - HashMap perms = permissionService.hasAllPermissions(StoreRef.PROTOCOL_WORKSPACE,StoreRef.STORE_REF_WORKSPACE_SPACESSTORE.getIdentifier(),nodeId, finalUserName, new String[]{CCConstants.PERMISSION_READ,CCConstants.PERMISSION_CC_PUBLISH}); + Map perms = permissionService.hasAllPermissions(StoreRef.PROTOCOL_WORKSPACE,StoreRef.STORE_REF_WORKSPACE_SPACESSTORE.getIdentifier(),nodeId, finalUserName, new String[]{CCConstants.PERMISSION_READ,CCConstants.PERMISSION_CC_PUBLISH}); rir.setPermissions(PermissionServiceHelper.getPermissionsAsString(perms).toArray(new String[0])); rir.setPublishRight(new Boolean(perms.get(CCConstants.PERMISSION_CC_PUBLISH))); rir.setUserReadAllowed(new Boolean(perms.get(PermissionService.READ))); }); //this does not work anymore in alfresco-5.0.d: - //HashMap permsGuest = client.hasAllPermissions(nodeId, PermissionService.ALL_AUTHORITIES, new String[]{PermissionService.READ}); - HashMap permsGuest = permissionService.hasAllPermissions(StoreRef.PROTOCOL_WORKSPACE,StoreRef.STORE_REF_WORKSPACE_SPACESSTORE.getIdentifier(),nodeId, PermissionService.GUEST_AUTHORITY, new String[]{PermissionService.READ}); + //Map permsGuest = client.hasAllPermissions(nodeId, PermissionService.ALL_AUTHORITIES, new String[]{PermissionService.READ}); + Map permsGuest = permissionService.hasAllPermissions(StoreRef.PROTOCOL_WORKSPACE,StoreRef.STORE_REF_WORKSPACE_SPACESSTORE.getIdentifier(),nodeId, PermissionService.GUEST_AUTHORITY, new String[]{PermissionService.READ}); rir.setGuestReadAllowed(new Boolean(permsGuest.get(PermissionService.READ))); HashMap versionProps = null; @@ -191,8 +191,8 @@ public Boolean doWork() throws Exception { } else if(version != null && !version.trim().equals("") && !version.trim().equals("-1")){ - HashMap> versionHIstory = client.getVersionHistory(nodeId); - for(Map.Entry> entry : versionHIstory.entrySet()){ + Map> versionHIstory = client.getVersionHistory(nodeId); + for(Map.Entry> entry : versionHIstory.entrySet()){ HashMap tmpVersionProps = entry.getValue(); String vlable = (String)tmpVersionProps.get(CCConstants.CM_PROP_VERSIONABLELABEL); @@ -249,7 +249,7 @@ public Boolean doWork() throws Exception { // 4.0: Fetch actual metadata from the remote object appInfo=ApplicationInfoList.getRepositoryInfoById((String) props.get(CCConstants.CCM_PROP_REMOTEOBJECT_REPOSITORYID)); String remoteId=(String) props.get(CCConstants.CCM_PROP_REMOTEOBJECT_NODEID); - HashMap propsNew = NodeServiceFactory.getNodeService(appInfo.getAppId()).getProperties(StoreRef.PROTOCOL_WORKSPACE, StoreRef.STORE_REF_WORKSPACE_SPACESSTORE.getIdentifier(), remoteId); + Map propsNew = NodeServiceFactory.getNodeService(appInfo.getAppId()).getProperties(StoreRef.PROTOCOL_WORKSPACE, StoreRef.STORE_REF_WORKSPACE_SPACESSTORE.getIdentifier(), remoteId); props.putAll(propsNew); } rir.setIconUrl(new MimeTypesV2(appInfo).getIcon(nodeType,props,Arrays.asList(aspects))); @@ -345,11 +345,11 @@ public Boolean doWork() throws Exception { String toolInstanceNodeRef = client.getProperty(MCAlfrescoAPIClient.storeRef, nodeId, CCConstants.CCM_PROP_TOOL_OBJECT_TOOLINSTANCEREF); String nodeIdToolInstance = new NodeRef(toolInstanceNodeRef).getId(); - HashMap propsToolInstance = client.getProperties(MCAlfrescoAPIClient.storeRef.getProtocol(), + Map propsToolInstance = client.getProperties(MCAlfrescoAPIClient.storeRef.getProtocol(), MCAlfrescoAPIClient.storeRef.getIdentifier(), nodeIdToolInstance); - List propsResultToolInstance = new ArrayList(); + List propsResultToolInstance = new ArrayList<>(); for(Map.Entry entry : propsToolInstance.entrySet()) { KeyValue kv = new KeyValue(entry.getKey(),(String)entry.getValue()); propsResultToolInstance.add(kv); @@ -383,7 +383,7 @@ private Map processProperties(String type, Map p */ private KeyValue[] convertProperties(Map propertiesIn) { - List propsresult = new ArrayList(); + List propsresult = new ArrayList<>(); //MetadataSetV2 mds = MetadataReaderV2.getMetadataset(ApplicationInfoList.getRepositoryInfoById(appId),CCConstants.metadatasetdefault_id); for(Map.Entry entry : propertiesIn.entrySet()){ @@ -399,8 +399,8 @@ private List> getChildNodes(String nodeId) throws Throwable return NodeServiceHelper.getSubobjects(NodeServiceFactory.getLocalService(),nodeId); } - private static HashMap removeUTF16Chars(Map props){ - HashMap propsClean = new HashMap(props); + private static Map removeUTF16Chars(Map props){ + Map propsClean = new HashMap(props); for(Map.Entry set : propsClean.entrySet()){ if(set.getValue() instanceof String){ String s= (String) set.getValue(); diff --git a/Backend/services/soap/server/src/main/java/org/edu_sharing/webservices/usage/UsageSoapBindingImpl.java b/Backend/services/soap/server/src/main/java/org/edu_sharing/webservices/usage/UsageSoapBindingImpl.java index 033cba4d70..c3e4b8f396 100644 --- a/Backend/services/soap/server/src/main/java/org/edu_sharing/webservices/usage/UsageSoapBindingImpl.java +++ b/Backend/services/soap/server/src/main/java/org/edu_sharing/webservices/usage/UsageSoapBindingImpl.java @@ -66,7 +66,7 @@ public org.edu_sharing.webservices.usage.UsageResult[] getUsageByParentNodeId(ja org.edu_sharing.service.usage.UsageService usageService = new org.edu_sharing.service.usage.UsageService(getRequestIp(), null, repositoryTicket); ArrayList serviceResults = usageService.getUsageByParentNodeId(parentNodeId); - ArrayList result = new ArrayList(); + ArrayList result = new ArrayList<>(); for (org.edu_sharing.service.usage.Usage serviceResult : serviceResults) { result.add(transform(serviceResult)); diff --git a/Backend/services/soap/server/src/test/java/org/edu_sharing/webservices/alfresco/extension/TestMain.java b/Backend/services/soap/server/src/test/java/org/edu_sharing/webservices/alfresco/extension/TestMain.java index 55161d4df0..1f5ae95b00 100644 --- a/Backend/services/soap/server/src/test/java/org/edu_sharing/webservices/alfresco/extension/TestMain.java +++ b/Backend/services/soap/server/src/test/java/org/edu_sharing/webservices/alfresco/extension/TestMain.java @@ -61,11 +61,11 @@ public static void main(String[] args){ int counterDatabase = 0; int counterSolr = 0; - HashMap nrFolders = naw.getChildren("8fbbf231-8bfe-4495-b374-6fe5463a1171", CCConstants.CCM_TYPE_MAP); + Map< naw.getChildren("8fbbf231-8bfe-4495-b374-6fe5463a1171", CCConstants.CCM_TYPE_MAP); for(Map.Entry entry : nrFolders.entrySet()) { Map nrFolder = (Map)entry.getValue(); System.out.println("nrfolder:" + nrFolder.get(CCConstants.CM_NAME)); - HashMap ios = naw.getChildren(entry.getKey(), CCConstants.CCM_TYPE_IO); + Map< naw.getChildren(entry.getKey(), CCConstants.CCM_TYPE_IO); for(Map.Entry ioEntry : ios.entrySet()) { counterDatabase++; Map ioProps = (Map)ioEntry.getValue(); @@ -102,20 +102,20 @@ public static void main(String[] args){ if(true) return; String root = naw.getRepositoryRoot(); - HashMap> children = (HashMap>) naw.getChildren(root,null); - for(Map.Entry> entry : children.entrySet()) { + Map> children = (Map>) naw.getChildren(root,null); + for(Map.Entry> entry : children.entrySet()) { String name = (String)entry.getValue().get(CCConstants.CM_NAME); if(name.equals("Company Home")) { - HashMap> chchildren = (HashMap>) naw.getChildren(entry.getKey(),null); - for(Map.Entry> chentry : chchildren.entrySet()) { + Map> chchildren = (Map>) naw.getChildren(entry.getKey(),null); + for(Map.Entry> chentry : chchildren.entrySet()) { String chName = (String)chentry.getValue().get(CCConstants.CM_NAME); if(chName.equals("User Homes")) { - HashMap> uhchildren = (HashMap>) naw.getChildren(chentry.getKey(),null); + Map> uhchildren = (Map>) naw.getChildren(chentry.getKey(),null); System.out.println(uhchildren.size()); int i = 0; - for(Map.Entry> uhentry : uhchildren.entrySet()) { + for(Map.Entry> uhentry : uhchildren.entrySet()) { String uhName = (String)uhentry.getValue().get(CCConstants.CM_NAME); System.out.println(uhName); if(InetAddressValidator.getInstance().isValid(uhName)){ @@ -142,14 +142,14 @@ public static void main(String[] args){ if(true) return; - HashMap test = naw.getProperties("defedcc4-fcf6-4182-b575-f137739c22aa"); + Map test = naw.getProperties("defedcc4-fcf6-4182-b575-f137739c22aa"); for(Map.Entry entry : test.entrySet()){ System.out.println("prop:"+entry.getKey()+" value:"+entry.getValue()); } - HashMap hasPermissionsResult = naw.hasPermissions("admin", new String[]{"Read"}, "ef84a120-2e3f-4dcb-9b43-67f7505bc576"); + Map hasPermissionsResult = naw.hasPermissions("admin", new String[]{"Read"}, "ef84a120-2e3f-4dcb-9b43-67f7505bc576"); System.out.println("HAS PERMISSIONSRESULT"); @@ -206,7 +206,7 @@ public static void main(String[] args){ public static void testThread(){ int maxThreads = 5; - List list = new ArrayList(); + List list = new ArrayList<>(); for(int i = 0; i < maxThreads; i++) { final int fi = i; @@ -222,7 +222,7 @@ public void run() { final NativeAlfrescoWrapper naw = new NativeAlfrescoWrapperServiceLocator(AuthenticationUtils.getEngineConfiguration()).getNativeAlfrescoWrapper(new URL("http://localhost:8080/edu-sharing/services/NativeAlfrescoWrapper?wsdl")); - ArrayList l = new ArrayList(); + ArrayList l = new ArrayList<>(); for(int i = 0; i < 10; i++) { UserDetails ud = new UserDetails(); diff --git a/Backend/services/soap/server/src/test/java/org/edu_sharing/webservices/crud/Test.java b/Backend/services/soap/server/src/test/java/org/edu_sharing/webservices/crud/Test.java index 38bab2a53c..f8173eae24 100644 --- a/Backend/services/soap/server/src/test/java/org/edu_sharing/webservices/crud/Test.java +++ b/Backend/services/soap/server/src/test/java/org/edu_sharing/webservices/crud/Test.java @@ -52,7 +52,7 @@ public static void main(String[] args) { Crud crud = locator.getcrud(); - HashMap properties = new HashMap(); + Map properties = new HashMap<>(); properties.put(CCConstants.CM_PROP_C_TITLE, "3AddUser.jpg"+System.currentTimeMillis()); properties.put(CCConstants.LOM_PROP_GENERAL_TITLE, "3AddUser.jpg"+System.currentTimeMillis()); properties.put(CCConstants.CCM_PROP_IO_OBJECTTYPE, "0"); diff --git a/Backend/transform/src/main/java/org/edu_sharing/alfresco/transformer/executors/VideoThumbnailExecutor.java b/Backend/transform/src/main/java/org/edu_sharing/alfresco/transformer/executors/VideoThumbnailExecutor.java index 44786893f4..67ccee9283 100644 --- a/Backend/transform/src/main/java/org/edu_sharing/alfresco/transformer/executors/VideoThumbnailExecutor.java +++ b/Backend/transform/src/main/java/org/edu_sharing/alfresco/transformer/executors/VideoThumbnailExecutor.java @@ -5,10 +5,9 @@ import org.alfresco.transform.base.executors.RuntimeExec; import org.alfresco.transform.base.util.CustomTransformerFileAdaptor; import org.alfresco.transform.common.RequestParamMap; -import org.alfresco.transform.exceptions.TransformException; import org.apache.commons.lang3.StringUtils; -import org.edu_sharing.alfresco.transformer.extractors.VideoMetadataExtractor; +import org.edu_sharing.alfresco.transformer.executors.tools.Commands; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; @@ -69,7 +68,7 @@ protected RuntimeExec createTransformCommand() { public void transform(String sourceMimetype, String targetMimetype, Map transformOptions, File sourceFile, File targetFile, TransformManager transformManager) throws Exception { logger.info("sourceMimetype:"+sourceMimetype+" targetMimetype:"+targetMimetype+" sourceFile:"+sourceFile +" targetFile:"+targetFile); if(transformOptions != null) - transformOptions.entrySet().stream().forEach(e -> System.out.println("o:"+ e.getKey() + " "+e.getValue())); + transformOptions.forEach((key, value) -> System.out.println("o:" + key + " " + value)); List comandAndArgs = null; try { @@ -89,7 +88,7 @@ public void transform(String sourceMimetype, String targetMimetype, Map options = new HashMap<>(); + Map options = new HashMap<>(); options.put("options",StringUtils.join(comandAndArgs," ")); this.run(options,targetFile,timeout); }catch (IOException e){ @@ -106,11 +105,7 @@ public String getTransformerName() { @Override protected RuntimeExec createCheckCommand() { - RuntimeExec runtimeExec = new RuntimeExec(); - Map commandsAndArguments = new HashMap<>(); - commandsAndArguments.put(".*", new String[] { "ffmpeg", "-version" }); - runtimeExec.setCommandsAndArguments(commandsAndArguments); - return runtimeExec; + return Commands.getFFMPegRuntimeExec(); } }