This is an automated email from the ASF dual-hosted git repository.
cziegeler pushed a commit to branch master
in repository
https://gitbox.apache.org/repos/asf/sling-org-apache-sling-engine.git
The following commit(s) were added to refs/heads/master by this push:
new 832228b SLING-11206 : Add support for buidling RequestProgressTracker
832228b is described below
commit 832228b9dc2c45504946ffe9a9be90227ee34d2c
Author: Carsten Ziegeler <[email protected]>
AuthorDate: Tue Mar 15 12:54:07 2022 +0100
SLING-11206 : Add support for buidling RequestProgressTracker
---
pom.xml | 4 +-
.../apache/sling/engine/impl/SlingHttpContext.java | 5 +-
.../debug/RequestProgressTrackerLogFilter.java | 11 +-
.../engine/impl/request/FastMessageFormat.java | 105 -------
.../sling/engine/impl/request/RequestData.java | 35 ++-
.../impl/request/SlingRequestProgressTracker.java | 333 ---------------------
.../debug/RequestProgressTrackerLogFilterTest.java | 6 +-
.../engine/impl/request/FastMessageFormatTest.java | 82 -----
.../request/SlingRequestProgressTrackerTest.java | 137 ---------
9 files changed, 31 insertions(+), 687 deletions(-)
diff --git a/pom.xml b/pom.xml
index 97067b5..cb642d6 100644
--- a/pom.xml
+++ b/pom.xml
@@ -28,7 +28,7 @@
</parent>
<artifactId>org.apache.sling.engine</artifactId>
- <version>2.8.1-SNAPSHOT</version>
+ <version>2.9.0-SNAPSHOT</version>
<name>Apache Sling Engine Implementation</name>
<description>
@@ -116,7 +116,7 @@
<dependency>
<groupId>org.apache.sling</groupId>
<artifactId>org.apache.sling.api</artifactId>
- <version>2.24.0</version>
+ <version>2.25.0-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>
diff --git a/src/main/java/org/apache/sling/engine/impl/SlingHttpContext.java
b/src/main/java/org/apache/sling/engine/impl/SlingHttpContext.java
index 5e7ce25..25f4b99 100644
--- a/src/main/java/org/apache/sling/engine/impl/SlingHttpContext.java
+++ b/src/main/java/org/apache/sling/engine/impl/SlingHttpContext.java
@@ -25,11 +25,11 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.sling.api.request.RequestProgressTracker;
+import org.apache.sling.api.request.builder.Builders;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.auth.core.AuthenticationSupport;
import org.apache.sling.commons.mime.MimeTypeService;
import org.apache.sling.engine.impl.parameters.ParameterSupport;
-import org.apache.sling.engine.impl.request.SlingRequestProgressTracker;
import org.osgi.service.http.context.ServletContextHelper;
import org.osgi.service.http.whiteboard.annotations.RequireHttpWhiteboard;
import org.slf4j.Logger;
@@ -119,7 +119,8 @@ class SlingHttpContext extends ServletContextHelper {
public boolean handleSecurity(HttpServletRequest request,
HttpServletResponse response) throws IOException {
- final SlingRequestProgressTracker t = new
SlingRequestProgressTracker(request);
+ final RequestProgressTracker t = Builders.newRequestProgressTracker();
+ t.log("Method={0}, PathInfo={1}", request.getMethod(),
request.getPathInfo());
request.setAttribute(RequestProgressTracker.class.getName(), t);
final String timerName = "handleSecurity";
t.startTimer(timerName);
diff --git
a/src/main/java/org/apache/sling/engine/impl/debug/RequestProgressTrackerLogFilter.java
b/src/main/java/org/apache/sling/engine/impl/debug/RequestProgressTrackerLogFilter.java
index 6798beb..1b19ca3 100644
---
a/src/main/java/org/apache/sling/engine/impl/debug/RequestProgressTrackerLogFilter.java
+++
b/src/main/java/org/apache/sling/engine/impl/debug/RequestProgressTrackerLogFilter.java
@@ -33,7 +33,6 @@ import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.request.RequestPathInfo;
import org.apache.sling.api.request.RequestProgressTracker;
import org.apache.sling.engine.EngineConstants;
-import org.apache.sling.engine.impl.request.SlingRequestProgressTracker;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.propertytypes.ServiceDescription;
@@ -167,14 +166,8 @@ public class RequestProgressTrackerLogFilter implements
Filter {
}
private boolean allowDuration(final RequestProgressTracker rpt) {
- if (rpt instanceof SlingRequestProgressTracker) {
- final long duration = ((SlingRequestProgressTracker)
rpt).getDuration() / NANOSEC_TO_MSEC;
- return configuration.minDurationMs() <= duration && duration <=
configuration.maxDurationMs();
- } else {
- log.debug("Logged requests can only be filtered by duration if the
SlingRequestProgressTracker is used.");
- return true;
- }
-
+ final long duration = rpt.getDuration() / NANOSEC_TO_MSEC;
+ return configuration.minDurationMs() <= duration && duration <=
configuration.maxDurationMs();
}
/**
diff --git
a/src/main/java/org/apache/sling/engine/impl/request/FastMessageFormat.java
b/src/main/java/org/apache/sling/engine/impl/request/FastMessageFormat.java
deleted file mode 100644
index e7a8dc9..0000000
--- a/src/main/java/org/apache/sling/engine/impl/request/FastMessageFormat.java
+++ /dev/null
@@ -1,105 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.apache.sling.engine.impl.request;
-
-import java.text.DateFormat;
-import java.text.MessageFormat;
-import java.text.NumberFormat;
-import java.util.Date;
-
-/**
- * Fast MessageFormat implementation which is not thread-safe. It is based on
the assumptions that
- * <ul>
- * <li>most formats do not contain format types and styles</li>
- * <li>do not use escaping</li>
- * <li>format elements are in order</li>
- * </ul>
- *
- * If one of these assumptions fails, then it falls back to the original
{@link MessageFormat}.<br>
- * To increase the benefit of this implementation, every instance should be
reused as often as possible.
- */
-public class FastMessageFormat {
-
- // Reusable formats instances. Cannot be static because these classes are
not thread safe.
- private NumberFormat numberFormat;
- private DateFormat dateFormat;
-
- private NumberFormat getNumberFormat() {
- if (numberFormat == null) {
- numberFormat = NumberFormat.getNumberInstance();
- }
- return numberFormat;
- }
-
- private DateFormat getDateFormat() {
- if (dateFormat == null) {
- dateFormat = DateFormat.getDateTimeInstance(DateFormat.SHORT,
DateFormat.SHORT);
- }
- return dateFormat;
- }
-
- /**
- * Use this method exactly like {@link MessageFormat#format(String,
Object...)}.
- *
- * @param pattern the pattern to use
- * @param arguments the objects to format
- * @return the string which has been formatted.
- *
- * @see MessageFormat#format(String, Object...)
- */
- public String format(String pattern, Object... arguments) {
- if (arguments == null || arguments.length == 0) {
- return pattern;
- } else {
- if (pattern.indexOf('\'') != -1) {
- // Escaping is not supported, fall back
- return MessageFormat.format(pattern, arguments);
- } else {
- StringBuilder message = new StringBuilder();
- int previousEnd = 0;
- for (int i = 0; i < arguments.length; i++) {
- String placeholder = '{' + String.valueOf(i);
- int placeholderIndex = pattern.indexOf(placeholder);
- // -1 or before previous placeholder || format element
with type/style
- if (placeholderIndex < previousEnd
- || pattern.charAt(placeholderIndex +
placeholder.length()) != '}') {
- // Type, style and random order are not supported,
fall back
- return MessageFormat.format(pattern, arguments);
- } else {
- // Format argument if necessary
- Object argument = arguments[i];
- if (argument instanceof Number) {
- argument = getNumberFormat().format(argument);
- } else if (argument instanceof Date) {
- argument = getDateFormat().format(argument);
- }
-
- // Append previous part of the string and formatted
argument
- message.append(pattern.substring(previousEnd,
placeholderIndex));
- message.append(argument);
- previousEnd = placeholderIndex + placeholder.length()
+ 1;
- }
- }
- message.append(pattern.substring(previousEnd,
pattern.length()));
- return message.toString();
- }
- }
- }
-
-}
diff --git
a/src/main/java/org/apache/sling/engine/impl/request/RequestData.java
b/src/main/java/org/apache/sling/engine/impl/request/RequestData.java
index 835bf47..bb60ffb 100644
--- a/src/main/java/org/apache/sling/engine/impl/request/RequestData.java
+++ b/src/main/java/org/apache/sling/engine/impl/request/RequestData.java
@@ -44,6 +44,7 @@ import org.apache.sling.api.request.RequestPathInfo;
import org.apache.sling.api.request.RequestProgressTracker;
import org.apache.sling.api.request.RequestUtil;
import org.apache.sling.api.request.TooManyCallsException;
+import org.apache.sling.api.request.builder.Builders;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.servlets.ServletResolver;
@@ -130,23 +131,23 @@ public class RequestData {
private final long startTimestamp;
/** The original servlet Servlet Request Object */
- private HttpServletRequest servletRequest;
+ private final HttpServletRequest servletRequest;
/** The original servlet Servlet Response object */
- private HttpServletResponse servletResponse;
+ private final HttpServletResponse servletResponse;
/** The original servlet Servlet Request Object */
- private SlingHttpServletRequest slingRequest;
+ private final SlingHttpServletRequest slingRequest;
/** The original servlet Servlet Response object */
- private SlingHttpServletResponse slingResponse;
+ private final SlingHttpServletResponse slingResponse;
/** The parameter support class */
private ParameterSupport parameterSupport;
private ResourceResolver resourceResolver;
- private RequestProgressTracker requestProgressTracker;
+ private final RequestProgressTracker requestProgressTracker;
/** the current ContentData */
private ContentData currentContentData;
@@ -222,16 +223,22 @@ public class RequestData {
this.slingResponse = new SlingHttpServletResponseImpl(this,
servletResponse);
- // Getting the RequestProgressTracker from the request attributes like
- // this should not be generally used, it's just a way to pass it from
- // its creation point to here, so it's made available via
- // the Sling request's getRequestProgressTracker method.
- final Object o =
request.getAttribute(RequestProgressTracker.class.getName());
- if (o instanceof RequestProgressTracker) {
- this.requestProgressTracker = (RequestProgressTracker)o;
+ // Use tracker from SlingHttpServletRequest
+ if ( request instanceof SlingHttpServletRequest ) {
+ this.requestProgressTracker =
((SlingHttpServletRequest)request).getRequestProgressTracker();
} else {
- log.warn("RequestProgressTracker not found in request attributes");
- this.requestProgressTracker = new
SlingRequestProgressTracker(request);
+ // Getting the RequestProgressTracker from the request attributes
like
+ // this should not be generally used, it's just a way to pass it
from
+ // its creation point to here, so it's made available via
+ // the Sling request's getRequestProgressTracker method.
+ final Object o =
request.getAttribute(RequestProgressTracker.class.getName());
+ if (o instanceof RequestProgressTracker) {
+ this.requestProgressTracker = (RequestProgressTracker)o;
+ } else {
+ log.warn("RequestProgressTracker not found in request
attributes");
+ this.requestProgressTracker =
Builders.newRequestProgressTracker();
+ this.requestProgressTracker.log("Method={0}, PathInfo={1}",
request.getMethod(), request.getPathInfo());
+ }
}
}
diff --git
a/src/main/java/org/apache/sling/engine/impl/request/SlingRequestProgressTracker.java
b/src/main/java/org/apache/sling/engine/impl/request/SlingRequestProgressTracker.java
deleted file mode 100644
index df2c237..0000000
---
a/src/main/java/org/apache/sling/engine/impl/request/SlingRequestProgressTracker.java
+++ /dev/null
@@ -1,333 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.apache.sling.engine.impl.request;
-
-import java.io.PrintWriter;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import javax.servlet.http.HttpServletRequest;
-
-import org.apache.sling.api.request.RequestProgressTracker;
-
-/**
- * The <code>SlingRequestProgressTracker</code> class provides the
- * functionality to track the progress of request processing. Instances of this
- * class are provided through the
- * {@link
org.apache.sling.api.SlingHttpServletRequest#getRequestProgressTracker()}
- * method.
- * <p>
- * The following functionality is provided:
- * <ol>
- * <li>Track the progress of request processing through the
- * {@link #log(String)} and {@link #log(String, Object...)} methods.
- * <li>Ability to measure and track processing times of parts of request
- * processing through the {@link #startTimer(String)} and
- * {@link #logTimer(String)} methods.
- * <li>Dumping the recording messages through the
- * {@link #dump(PrintWriter)} method.
- * <li>Resetting the tracker through the {@link #reset()} method.
- * </ol>
- * <p>
- * <b>Tracking Request Processing</b>
- * <p>
- * As the request being processed, certain steps may be tracked by calling
- * either of the <code>log</code> methods. A tracking entry consists of a time
- * stamp managed by this class, and a tracking message noting the actual step
being
- * tracked.
- * <p>
- * <b>Timing Processing Steps</b>
- * </p>
- * Certain steps during request processing may need to be timed in that the
time
- * required for processing should be recorded. Instances of this class maintain
- * a map of named timers. Each timer is started (initialized or reset) by
- * calling the {@link #startTimer(String)} method. This method just records the
- * starting time of the named timer.
- * <p>
- * To record the number of milliseconds ellapsed since a timer has been
started,
- * the {@link #logTimer(String)} method may be called. This method logs the
- * tracking entry with message
- * consisting of the name of the timer and the number of milliseconds ellapsed
- * since the timer was last {@link #startTimer(String) started}. The
- * {@link #logTimer(String)} method may be called multiple times to record
- * several timed steps.
- * <p>
- * Additional information can be logged using the {@link #logTimer(String,
String, Object...)}
- * method.
- * <p>
- * Calling the {@link #startTimer(String)} method with the name of timer which
- * already exists, resets the start time of the named timer to the current
- * system time.
- * <p>
- * <b>Dumping Tracking Entries</b>
- * <p>
- * The {@link #dump(PrintWriter)} methods writes all tracking entries to the
given
- * <code>PrintWriter</code>. Each entry is written on a single line
- * consisting of the following fields:
- * <ol>
- * <li>The number of milliseconds since the last {@link #reset()} (or creation)
- * of this timer.
- * <li>The absolute time of the timer in parenthesis.
- * <li>The entry message
- * </ol>
- */
-public class SlingRequestProgressTracker implements RequestProgressTracker {
-
- /**
- * The name of the timer tracking the processing time of the complete
- * process.
- */
- private static final String REQUEST_PROCESSING_TIMER = "Request
Processing";
-
- /** Prefix for log messages */
- private static final String LOG_PREFIX = "LOG ";
-
- /** Prefix for comment messages */
- private static final String COMMENT_PREFIX = "COMMENT ";
-
- /** TIMER_END format explanation */
- private static final String TIMER_END_FORMAT = "{<elapsed
microseconds>,<timer name>} <optional message>";
-
- /** The leading nanosecond number is left-padded with white-space to this
width. */
- private static final int PADDING_WIDTH = 7;
-
- /**
- * The system time at creation of this instance or the last {@link
#reset()}.
- */
- private long processingStart;
-
- /**
- * The system time when {@link #done()} was called or -1 while processing
is in progress.
- */
- private long processingEnd;
-
- /**
- * The list of tracking entries.
- */
- private final List<TrackingEntry> entries = new ArrayList<TrackingEntry>();
- /**
- * Map of named timers indexed by timer name storing the system time of
- * start of the respective timer.
- */
- private final Map<String, Long> namedTimerEntries = new HashMap<String,
Long>();
-
- private final FastMessageFormat messageFormat = new FastMessageFormat();
-
- /**
- * Creates a new request progress tracker.
- */
- public SlingRequestProgressTracker() {
- this(null);
- }
-
- /**
- * Creates a new request progress tracker and logs initial messages about
the supplied request.
- *
- * @param request the request
- */
- public SlingRequestProgressTracker(HttpServletRequest request) {
- reset();
- if(request != null) {
- log("Method={0}, PathInfo={1}", request.getMethod(),
request.getPathInfo());
- }
- }
-
- /**
- * Resets this timer by removing all current entries and timers and adds an
- * initial timer entry
- */
- public void reset() {
- // remove all entries
- entries.clear();
- namedTimerEntries.clear();
-
- // enter initial messages
- processingStart = startTimerInternal(REQUEST_PROCESSING_TIMER);
- processingEnd = -1;
-
- entries.add(new TrackingEntry(COMMENT_PREFIX + "timer_end format is "
+ TIMER_END_FORMAT));
- }
-
- /**
- * @see org.apache.sling.api.request.RequestProgressTracker#getMessages()
- */
- public Iterator<String> getMessages() {
- return new Iterator<String>() {
- private final Iterator<TrackingEntry> entryIter =
entries.iterator();
-
- public boolean hasNext() {
- return entryIter.hasNext();
- }
-
- public String next() {
- // throws NoSuchElementException if no entries any more
- final TrackingEntry entry = entryIter.next();
- final long offset = entry.getTimeStamp() - getTimeStamp();
- return formatMessage(offset, entry.getMessage());
- }
-
- public void remove() {
- throw new UnsupportedOperationException("remove");
- }
- };
- }
-
- private String formatMessage(long offset, String message) {
- // Set exact length to avoid array copies within StringBuilder
- final StringBuilder sb = new StringBuilder(PADDING_WIDTH + 1 +
message.length() + 1);
- final String offsetStr = Long.toString(offset / 1000);
- for (int i = PADDING_WIDTH - offsetStr.length(); i > 0; i--) {
- sb.append(' ');
- }
- sb.append(offsetStr).append(' ').append(message).append('\n');
- return sb.toString();
- }
-
- /**
- * Dumps the process timer entries to the given writer, one entry per line.
- * See the class comments for the rough format of each message line.
- */
- public void dump(final PrintWriter writer) {
- logTimer(REQUEST_PROCESSING_TIMER,
- "Dumping SlingRequestProgressTracker Entries");
-
- final StringBuilder sb = new StringBuilder();
- final Iterator<String> messages = getMessages();
- while (messages.hasNext()) {
- sb.append(messages.next());
- }
- writer.print(sb.toString());
- }
-
- /** Creates an entry with the given message. */
- public void log(String message) {
- entries.add(new TrackingEntry(LOG_PREFIX + message));
- }
-
- /** Creates an entry with the given entry tag and message */
- public void log(String format, Object... args) {
- String message = messageFormat.format(format, args);
- entries.add(new TrackingEntry(LOG_PREFIX + message));
- }
-
- /**
- * Starts a named timer. If a timer of the same name already exists, it is
- * reset to the current time.
- */
- public void startTimer(String name) {
- startTimerInternal(name);
- }
-
- /**
- * Start the named timer and returns the start time in milliseconds.
- * Logs a message with format
- * <pre>
- * TIMER_START{<name>} <optional message>
- * </pre>
- */
- private long startTimerInternal(String name) {
- long timer = System.nanoTime();
- namedTimerEntries.put(name, timer);
- entries.add(new TrackingEntry(timer, "TIMER_START{" + name + "}"));
- return timer;
- }
-
- /**
- * Log a timer entry, including start, end and elapsed time.
- */
- public void logTimer(String name) {
- if (namedTimerEntries.containsKey(name)) {
- logTimerInternal(name, null, namedTimerEntries.get(name));
- }
- }
-
- /**
- * Log a timer entry, including start, end and elapsed time.
- */
- public void logTimer(String name, String format, Object... args) {
- if (namedTimerEntries.containsKey(name)) {
- logTimerInternal(name, messageFormat.format(format, args),
namedTimerEntries.get(name));
- }
- }
-
- /**
- * Log a timer entry, including start, end and elapsed time using
TIMER_END_FORMAT
- */
- private void logTimerInternal(String name, String msg, long startTime) {
- final StringBuilder sb = new StringBuilder();
- sb.append("TIMER_END{");
- sb.append((System.nanoTime() - startTime) / 1000);
- sb.append(',');
- sb.append(name);
- sb.append('}');
- if(msg != null) {
- sb.append(' ');
- sb.append(msg);
- }
- entries.add(new TrackingEntry(sb.toString()));
- }
-
- public void done() {
- if(processingEnd != -1) return;
- logTimer(REQUEST_PROCESSING_TIMER, REQUEST_PROCESSING_TIMER);
- processingEnd = System.nanoTime();
- }
-
- private long getTimeStamp() {
- return processingStart;
- }
-
- public long getDuration() {
- if (processingEnd != -1) {
- return processingEnd - processingStart;
- }
- return System.nanoTime() - processingStart;
- }
-
- /** Process tracker entry keeping timestamp, tag and message */
- private static class TrackingEntry {
-
- // creation time stamp
- private final long timeStamp;
-
- // tracking message
- private final String message;
-
- TrackingEntry(String message) {
- this.timeStamp = System.nanoTime();
- this.message = message;
- }
-
- TrackingEntry(long timeStamp, String message) {
- this.timeStamp = timeStamp;
- this.message = message;
- }
-
- long getTimeStamp() {
- return timeStamp;
- }
-
- String getMessage() {
- return message;
- }
- }
-}
diff --git
a/src/test/java/org/apache/sling/engine/impl/debug/RequestProgressTrackerLogFilterTest.java
b/src/test/java/org/apache/sling/engine/impl/debug/RequestProgressTrackerLogFilterTest.java
index 9c6ae42..5415779 100644
---
a/src/test/java/org/apache/sling/engine/impl/debug/RequestProgressTrackerLogFilterTest.java
+++
b/src/test/java/org/apache/sling/engine/impl/debug/RequestProgressTrackerLogFilterTest.java
@@ -24,7 +24,7 @@ import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import org.apache.sling.api.request.RequestProgressTracker;
-import org.apache.sling.engine.impl.request.SlingRequestProgressTracker;
+import org.apache.sling.api.request.builder.Builders;
import org.junit.Test;
/** Partial tests of RequestProgressTrackerLogFilter */
@@ -69,7 +69,7 @@ public class RequestProgressTrackerLogFilterTest {
public void verifySlingRequestProgressTrackerDurationIsNanos() throws
Exception {
// Verify that SlingRequestProgressTracker duration is based on nano
time
final long startMsec = System.currentTimeMillis();
- final SlingRequestProgressTracker rpt = new
SlingRequestProgressTracker();
+ final RequestProgressTracker rpt =
Builders.newRequestProgressTracker();
Thread.sleep(10);
final long rptElapsed = rpt.getDuration();
final long elapsedMsec = System.currentTimeMillis() - startMsec;
@@ -85,7 +85,7 @@ public class RequestProgressTrackerLogFilterTest {
final Method allowDuration =
filter.getClass().getDeclaredMethod("allowDuration",
RequestProgressTracker.class);
allowDuration.setAccessible(true);
- final SlingRequestProgressTracker rpt = new
SlingRequestProgressTracker();
+ final RequestProgressTracker rpt =
Builders.newRequestProgressTracker();
final int delta = 2;
Thread.sleep(delta * 2);
rpt.done();
diff --git
a/src/test/java/org/apache/sling/engine/impl/request/FastMessageFormatTest.java
b/src/test/java/org/apache/sling/engine/impl/request/FastMessageFormatTest.java
deleted file mode 100644
index a52951e..0000000
---
a/src/test/java/org/apache/sling/engine/impl/request/FastMessageFormatTest.java
+++ /dev/null
@@ -1,82 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.apache.sling.engine.impl.request;
-
-import org.junit.Test;
-
-import java.text.MessageFormat;
-import java.util.Arrays;
-import java.util.Calendar;
-import java.util.Date;
-
-import static org.junit.Assert.assertEquals;
-
-public class FastMessageFormatTest {
-
- @Test
- public void testFormat() {
- FormatTest[] tests = {
- // Data types
- new FormatTest("{0}", 1),
- new FormatTest("{0}", Integer.MAX_VALUE),
- new FormatTest("{0}", Long.MAX_VALUE),
- new FormatTest("{0}", Math.PI),
- new FormatTest("{0}", 123456.123456),
- new FormatTest("{0}", Float.MAX_VALUE),
- new FormatTest("{0}", new Date()),
- new FormatTest("{0}", Calendar.getInstance()),
- new FormatTest("{0}", true),
- new FormatTest("{0}", false),
- new FormatTest("{0}", new int[] {1,2,3}),
- new FormatTest("{0}", (Object) new Integer[] {1,2,3}),
- new FormatTest("{0}", Arrays.asList(1, 2, 3)),
- new FormatTest("{0}", "text"),
-
- // Patterns
- new FormatTest("{0}{0}", 1, 2),
- new FormatTest("a{0}b{1}c", 1, 2),
- new FormatTest("a{0}b{1}c{2}d", 1, 2, 3),
- new FormatTest("a{0}bb{1}ccc{2}dddd", 10, 20, 30),
- new FormatTest("c{1}b{0}a", 1, 2),
- new FormatTest("c{1}b{0}a{1}c", 1, 2),
-
- // Type/style
- new FormatTest("c{0,number,#.##}b{0}a{1}c", 1, 2),
- new FormatTest("{0,number,#.##}", 1.2345),
-
- // Escaping
- new FormatTest("'{0}'", 1)
- };
-
- FastMessageFormat fastMessageFormat = new FastMessageFormat();
- for (FormatTest test : tests) {
- String expected = MessageFormat.format(test.pattern, test.args);
- String actual = fastMessageFormat.format(test.pattern, test.args);
- assertEquals(expected, actual);
- }
- }
-
- private static class FormatTest {
- final String pattern;
- final Object[] args;
- public FormatTest(String pattern, Object... args) {
- this.pattern = pattern;
- this.args = args;
- }
- }
-
-}
diff --git
a/src/test/java/org/apache/sling/engine/impl/request/SlingRequestProgressTrackerTest.java
b/src/test/java/org/apache/sling/engine/impl/request/SlingRequestProgressTrackerTest.java
deleted file mode 100644
index 8c50830..0000000
---
a/src/test/java/org/apache/sling/engine/impl/request/SlingRequestProgressTrackerTest.java
+++ /dev/null
@@ -1,137 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.apache.sling.engine.impl.request;
-
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-import static org.junit.Assert.assertEquals;
-
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.PrintWriter;
-import java.io.StringReader;
-import java.io.StringWriter;
-import java.util.Iterator;
-
-import org.junit.Before;
-import org.junit.Test;
-
-public class SlingRequestProgressTrackerTest {
-
- private SlingRequestProgressTracker tracker;
-
- @Before
- public void setup() {
- tracker = new SlingRequestProgressTracker();
- }
-
- private void addTestData() {
- tracker.startTimer("foo");
- tracker.log("one {0}, two {1}, three {2}", "eins", "zwei", "drei");
- tracker.startTimer("bar");
- tracker.logTimer("bar");
- tracker.logTimer("foo");
- tracker.done();
- }
-
- @Test
- public void messageFormatting() {
- final String[] expected = {
- "TIMER_START{Request Processing}\n",
- "COMMENT timer_end format is {<elapsed microseconds>,<timer
name>} <optional message>\n",
- "TIMER_START{foo}\n",
- "LOG one eins, two zwei, three drei\n",
- "TIMER_START{bar}\n",
- "TIMER_END{?,bar}\n",
- "TIMER_END{?,foo}\n",
- "TIMER_END{?,Request Processing} Request Processing\n"
- };
-
- addTestData();
- final Iterator<String> messages = tracker.getMessages();
- int messageCounter = 0;
- while (messages.hasNext()) {
- final String m = messages.next();
- final String e = expected[messageCounter++];
- if (e.startsWith("TIMER_END{")) {
- // account for the counter in the string
- assertEquals(substringAfter(e, ','), substringAfter(m, ','));
- } else {
- // strip off counter
- assertEquals(e, m.substring(8));
- }
- }
-
- assertEquals(expected.length, messageCounter);
- }
-
- @Test
- public void dump() throws IOException {
- addTestData();
- final StringWriter w = new StringWriter();
- tracker.dump(new PrintWriter(w));
- w.flush();
- final String result = w.toString();
-
- final String [] expected = {
- "TIMER_START{Request Processing}",
- "TIMER_START{foo}",
- "Dumping SlingRequestProgressTracker Entries"
- };
- for(String exp : expected) {
- if(!result.contains(exp)) {
- fail("Expected result to contain [" + exp + "] but was [" +
result + "]");
- }
- }
-
- int lineCount = 0;
- final BufferedReader br = new BufferedReader(new StringReader(result));
- while(br.readLine() != null) {
- lineCount++;
- }
- assertEquals(9, lineCount);
- }
-
- @Test
- public void duration() throws InterruptedException {
- Thread.sleep(50);
- tracker.log("after the wait");
- assertTrue(tracker.getDuration() >= 50);
- }
-
- @Test
- public void durationWithDone() throws InterruptedException {
- Thread.sleep(25);
- tracker.done();
- final long d = tracker.getDuration();
- assertTrue(d >= 25);
- Thread.sleep(25);
- tracker.log("Some more stuff");
- assertEquals(d, tracker.getDuration());
- }
-
- @Test(expected=UnsupportedOperationException.class)
- public void removeFails() {
- tracker.getMessages().remove();
- }
-
- private String substringAfter(String string, char ch) {
- final int pos = string.indexOf(ch);
- return string.substring(pos);
- }
-
-}