    001/*
    002 * Licensed to the Apache Software Foundation (ASF) under one or more
    003 * contributor license agreements.  See the NOTICE file distributed with
    004 * this work for additional information regarding copyright ownership.
    005 * The ASF licenses this file to You under the Apache License, Version 2.0
    006 * (the "License"); you may not use this file except in compliance with
    007 * the License.  You may obtain a copy of the License at
    008 *
    009 *      http://www.apache.org/licenses/LICENSE-2.0
    010 *
    011 * Unless required by applicable law or agreed to in writing, software
    012 * distributed under the License is distributed on an "AS IS" BASIS,
    013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    014 * See the License for the specific language governing permissions and
    015 * limitations under the License.
    016 */
    017package org.apache.commons.pool2.impl;
    018
    019import java.io.PrintWriter;
    020import java.lang.ref.WeakReference;
    021import java.security.AccessController;
    022import java.security.PrivilegedAction;
    023import java.text.DateFormat;
    024import java.text.SimpleDateFormat;
    025import java.util.ArrayList;
    026import java.util.List;
    027
    028/**
    029 * CallStack strategy using a {@link SecurityManager}. Obtaining the current call stack is much faster via a
    030 * SecurityManger, but access to the underlying method may be restricted by the current SecurityManager. In environments
    031 * where a SecurityManager cannot be created, {@link ThrowableCallStack} should be used instead.
    032 *
    033 * @see RuntimePermission
    034 * @see SecurityManager#getClassContext()
    035 * @since 2.4.3
    036 */
    037public class SecurityManagerCallStack implements CallStack {
    038
    039    private final String messageFormat;
    040    //@GuardedBy("dateFormat")
    041    private final DateFormat dateFormat;
    042    private final PrivateSecurityManager securityManager;
    043
    044    private volatile Snapshot snapshot;
    045
    046    /**
    047     * Create a new instance.
    048     *
    049     * @param messageFormat message format
    050     * @param useTimestamp whether to format the dates in the output message or not
    051     */
    052    public SecurityManagerCallStack(final String messageFormat, final boolean useTimestamp) {
    053        this.messageFormat = messageFormat;
    054        this.dateFormat = useTimestamp ? new SimpleDateFormat(messageFormat) : null;
    055        this.securityManager = AccessController.doPrivileged((PrivilegedAction<PrivateSecurityManager>) () -> new PrivateSecurityManager());
    056    }
    057
    058    @Override
    059    public boolean printStackTrace(final PrintWriter writer) {
    060        final Snapshot snapshotRef = this.snapshot;
    061        if (snapshotRef == null) {
    062            return false;
    063        }
    064        final String message;
    065        if (dateFormat == null) {
    066            message = messageFormat;
    067        } else {
    068            synchronized (dateFormat) {
    069                message = dateFormat.format(Long.valueOf(snapshotRef.timestamp));
    070            }
    071        }
    072        writer.println(message);
    073        for (final WeakReference<Class<?>> reference : snapshotRef.stack) {
    074            writer.println(reference.get());
    075        }
    076        return true;
    077    }
    078
    079    @Override
    080    public void fillInStackTrace() {
    081        snapshot = new Snapshot(securityManager.getCallStack());
    082    }
    083
    084    @Override
    085    public void clear() {
    086        snapshot = null;
    087    }
    088
    089    /**
    090     * A custom security manager.
    091     */
    092    private static class PrivateSecurityManager extends SecurityManager {
    093        /**
    094         * Get the class stack.
    095         *
    096         * @return class stack
    097         */
    098        private List<WeakReference<Class<?>>> getCallStack() {
    099            final Class<?>[] classes = getClassContext();
    100            final List<WeakReference<Class<?>>> stack = new ArrayList<>(classes.length);
    101            for (final Class<?> klass : classes) {
    102                stack.add(new WeakReference<Class<?>>(klass));
    103            }
    104            return stack;
    105        }
    106    }
    107
    108    /**
    109     * A snapshot of a class stack.
    110     */
    111    private static class Snapshot {
    112        private final long timestamp = System.currentTimeMillis();
    113        private final List<WeakReference<Class<?>>> stack;
    114
    115        /**
    116         * Create a new snapshot with a class stack.
    117         *
    118         * @param stack class stack
    119         */
    120        private Snapshot(final List<WeakReference<Class<?>>> stack) {
    121            this.stack = stack;
    122        }
    123    }
    124}