001/*
002 * This library is part of OpenCms -
003 * the Open Source Content Management System
004 *
005 * Copyright (c) Alkacon Software GmbH & Co. KG (http://www.alkacon.com)
006 *
007 * This library is free software; you can redistribute it and/or
008 * modify it under the terms of the GNU Lesser General Public
009 * License as published by the Free Software Foundation; either
010 * version 2.1 of the License, or (at your option) any later version.
011 *
012 * This library is distributed in the hope that it will be useful,
013 * but WITHOUT ANY WARRANTY; without even the implied warranty of
014 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
015 * Lesser General Public License for more details.
016 *
017 * For further information about Alkacon Software, please see the
018 * company website: http://www.alkacon.com
019 *
020 * For further information about OpenCms, please see the
021 * project website: http://www.opencms.org
022 *
023 * You should have received a copy of the GNU Lesser General Public
024 * License along with this library; if not, write to the Free Software
025 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
026 */
027
028package org.opencms.jsp.userdata;
029
030import org.opencms.file.CmsObject;
031import org.opencms.main.CmsLog;
032import org.opencms.main.OpenCms;
033import org.opencms.util.CmsFileUtil;
034
035import java.io.File;
036import java.io.FileInputStream;
037import java.io.FileOutputStream;
038import java.util.Optional;
039import java.util.concurrent.TimeUnit;
040
041import org.apache.commons.lang3.StringUtils;
042import org.apache.commons.logging.Log;
043
044/**
045 * Class which handles loading/saving user data requests.
046 *
047 * <p>Currently stores user data requests in a special RFS directory, with their ID as a filename.
048 * Expired user data requests are removed each hour.
049 */
050public class CmsUserDataRequestStore {
051
052    /** Logger instance for this class. */
053    private static final Log LOG = CmsLog.getLog(CmsUserDataRequestStore.class);
054
055    /** The admin CMS object. */
056    @SuppressWarnings("unused")
057    private CmsObject m_adminCms;
058
059    /** Folder to store requests in. */
060    private File m_folder;
061
062    /**
063     * Creates a new instance.
064     */
065    public CmsUserDataRequestStore() {
066
067        LOG.debug("Creating user data request store.");
068
069    }
070
071    /**
072     * Checks if the key is a valid user data request key.
073     *
074     * @param key the key to check
075     * @return true if the key is valid
076     */
077    public static boolean isValidKey(String key) {
078
079        return StringUtils.isAlphanumeric(key);
080    }
081
082    /**
083     * Removes expired user data requests.
084     */
085    public void cleanup() {
086
087        File[] files = m_folder.listFiles();
088        if (files != null) {
089            for (File file : files) {
090                String key = file.getName();
091                try {
092                    CmsUserDataRequestInfo info = load(key).orElse(null);
093                    if ((info != null) && info.isExpired()) {
094                        file.delete();
095                    }
096                } catch (Exception e) {
097                    LOG.error(e.getLocalizedMessage(), e);
098                }
099
100            }
101        }
102    }
103
104    /**
105     * Initializes the store with an admin CMS object.
106     *
107     * @param adminCms the admin CMS object
108     */
109    public void initialize(CmsObject adminCms) {
110
111        m_adminCms = adminCms;
112        m_folder = new File(OpenCms.getSystemInfo().getAbsoluteRfsPathRelativeToWebInf("userdata-requests"));
113        if (!m_folder.exists()) {
114            m_folder.mkdir();
115        }
116        OpenCms.getExecutor().scheduleWithFixedDelay(() -> {
117            cleanup();
118        }, 30, 30, TimeUnit.MINUTES);
119    }
120
121    /**
122     * Loads the user data request with the given id.
123     *
124     * @param key the id
125     * @return the user data request with the id, or null if it was not found
126     */
127    public Optional<CmsUserDataRequestInfo> load(String key) {
128
129        if (!isValidKey(key)) {
130            return Optional.empty();
131        }
132        File child = new File(m_folder, key);
133        if (child.exists() && child.isFile()) {
134            try (FileInputStream stream = new FileInputStream(child)) {
135                byte[] data = CmsFileUtil.readFully(stream, false);
136                return Optional.of(new CmsUserDataRequestInfo(new String(data, "UTF-8")));
137            } catch (Exception e) {
138                LOG.error(e.getLocalizedMessage(), e);
139                return Optional.empty();
140            }
141        } else {
142            LOG.info("user data request " + key + " not found.");
143            return Optional.empty();
144        }
145    }
146
147    /**
148     * Saves the user data request, with the id taken from the user data request itself.
149     *
150     * @param info the user data request to save
151     */
152    public void save(CmsUserDataRequestInfo info) {
153
154        if (!isValidKey(info.getId())) {
155            return;
156        }
157        File child = new File(m_folder, info.getId());
158        try (FileOutputStream out = new FileOutputStream(child)) {
159            out.write(info.toJson().getBytes("UTF-8"));
160        } catch (Exception e) {
161            throw new RuntimeException(e);
162        }
163    }
164
165}