/*
 * Copyright 2014 Hippo B.V. (http://www.onehippo.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.onehippo.forge.webservices.jaxrs;

import java.lang.reflect.Field;

import javax.jcr.LoginException;
import javax.jcr.Session;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;

import org.apache.cxf.rs.security.cors.CrossOriginResourceSharing;
import org.apache.jackrabbit.api.stats.RepositoryStatistics;
import org.apache.jackrabbit.core.RepositoryContext;
import org.apache.jackrabbit.core.RepositoryImpl;
import org.apache.jackrabbit.core.stats.RepositoryStatisticsImpl;
import org.hippoecm.repository.impl.RepositoryDecorator;
import org.onehippo.forge.webservices.jaxrs.jcr.util.RepositoryConnectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Resource for showing statistics http://wiki.apache.org/jackrabbit/Statistics
 *
 * @author Jeroen Reijn
 */
@Api(value = "_stats", description = "Accessing the root of a Hippo instance returns meta information about the instance. The response is a JSON structure containing information about the server, including a welcome message and the version of the server.")
@Path(value = "_stats")
@CrossOriginResourceSharing(allowAllOrigins = true)
public class StatsResource {

    @Context
    private HttpServletRequest request;

    private RepositoryStatisticsImpl statistics;

    private static Logger log = LoggerFactory.getLogger(StatsResource.class);

    @ApiOperation(
            value = "Display statistics about the repository instance; nr of sessions, queries, bundle operations",
            notes = "",
            position = 1)
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Response getInstanceInformation() {
        Session session = null;
        RepositoryStatistics repositoryStatistics = null;
        try {
            session = RepositoryConnectionUtils.createSession(request);
            repositoryStatistics = getStatistics(session);
        } catch (LoginException e) {
            log.warn("An exception occurred while trying to login: {}", e);
        } finally {
            RepositoryConnectionUtils.cleanupSession(session);
        }
        return Response.ok(repositoryStatistics).build();
    }

    private RepositoryStatistics getStatistics(Session session) {
        if (statistics == null) {
            try {
                Field contextField = RepositoryImpl.class.getDeclaredField("context");
                if (!contextField.isAccessible()) {
                    contextField.setAccessible(true);
                }
                RepositoryContext respositoryContext = (RepositoryContext) contextField.get(RepositoryDecorator.unwrap(session.getRepository()));
                this.statistics = respositoryContext.getRepositoryStatistics();
            } catch (SecurityException e) {
                throw new IllegalArgumentException(e);
            } catch (NoSuchFieldException e) {
                throw new IllegalArgumentException(e);
            } catch (IllegalAccessException e) {
                throw new IllegalArgumentException(e);
            }
            return statistics;
        } else {
            return statistics;
        }
    }

}

@@ -849,16 +849,46 @@
 s.Path;%0A
+import javax.ws.rs.PathParam;%0A
 import j
@@ -908,16 +908,16 @@
 oduces;%0A
-
 import j
@@ -1237,16 +1237,67 @@
 istics;%0A
+import org.apache.jackrabbit.api.stats.TimeSeries;%0A
 import o
@@ -2361,16 +2361,20 @@
 Display 
+all 
 statisti
@@ -3106,16 +3106,938 @@
 %0A    %7D%0A%0A
+    @ApiOperation(%0A            value = %22Display specific statistics based on the key about the repository instance%22,%0A            notes = %22%22,%0A            position = 2)%0A    @GET%0A    @Path(%22/type/%7Bkey%7D%22)%0A    @Produces(MediaType.APPLICATION_JSON)%0A    public Response getInstanceInformationByKey(@PathParam(%22key%22) String key) %7B%0A        Session session = null;%0A        TimeSeries timeSeries = null;%0A        try %7B%0A            session = RepositoryConnectionUtils.createSession(request);%0A            RepositoryStatistics repositoryStatistics = getStatistics(session);%0A            timeSeries = repositoryStatistics.getTimeSeries(RepositoryStatistics.Type.getType(key));%0A        %7D catch (LoginException e) %7B%0A            log.warn(%22An exception occurred while trying to login: %7B%7D%22, e);%0A        %7D finally %7B%0A            RepositoryConnectionUtils.cleanupSession(session);%0A        %7D%0A        return Response.ok(timeSeries).build();%0A    %7D%0A%0A%0A
     priv
@@ -4393,17 +4393,16 @@
 ntext re
-s
 pository
@@ -4538,17 +4538,16 @@
 ics = re
-s
 pository

Add filtering to repository statistics