001/* 002 * Copyright 2020 Anyware Services 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package org.ametys.plugins.workspaces.documents.onlyoffice; 018 019import java.text.SimpleDateFormat; 020import java.util.Date; 021import java.util.Map; 022import java.util.concurrent.ConcurrentHashMap; 023 024import org.apache.avalon.framework.activity.Initializable; 025import org.apache.avalon.framework.component.Component; 026import org.apache.commons.lang3.StringUtils; 027 028import org.ametys.runtime.plugin.component.AbstractLogEnabled; 029 030/** 031 * Manager for key/token used in OnlyOffice 032 */ 033public class OnlyOfficeKeyManager extends AbstractLogEnabled implements Component, Initializable 034{ 035 /** The Avalon role */ 036 public static final String ROLE = OnlyOfficeKeyManager.class.getName(); 037 038 private Map<String, String> _onlyOfficeKeyStorage; 039 040 public void initialize() throws Exception 041 { 042 _onlyOfficeKeyStorage = new ConcurrentHashMap<>(); 043 } 044 045 /** 046 * Get the OnlyOffice key associated with the resource 047 * If a key exist for the resourceId, return it and increment _nbHolders 048 * If no key exist for the resourceId, create a new key, put at 1 the _nbHolders and return the key 049 * @param resourceId id of the resource to look 050 * @return the OnlyOffice key 051 */ 052 public synchronized String getKey(String resourceId) 053 { 054 String tokenKey = _resourceIdToTokenKey(resourceId); 055 return _onlyOfficeKeyStorage.computeIfAbsent(tokenKey, this::createKey); 056 } 057 058 /** 059 * Create the OnlyOffice key 060 * @param tokenKey id of the resource associate to the key 061 * @return the new key 062 */ 063 protected String createKey(String tokenKey) 064 { 065 String currentTime = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new Date()); 066 return tokenKey + "." + currentTime; 067 } 068 069 /** 070 * Remove OnlyOffice key 071 * @param resourceId id of the resource 072 */ 073 public void removeKey(String resourceId) 074 { 075 String tokenKey = _resourceIdToTokenKey(resourceId); 076 _onlyOfficeKeyStorage.remove(tokenKey); 077 } 078 079 private String _resourceIdToTokenKey(String ressourceId) 080 { 081 return StringUtils.substringAfter(ressourceId, "://"); 082 } 083}