Search in sources :

Example 11 with Time

use of org.apache.wicket.util.time.Time in project wicket by apache.

the class PageAccessSynchronizerTest method runContentionTest.

/**
 * @param pages
 * @param workers
 * @param duration
 * @throws Exception
 */
public void runContentionTest(final int pages, final int workers, final Duration duration) throws Exception {
    final PageAccessSynchronizer sync = new PageAccessSynchronizer(Duration.seconds(1));
    final AtomicInteger[] counts = new AtomicInteger[pages];
    for (int i = 0; i < counts.length; i++) {
        counts[i] = new AtomicInteger();
    }
    final AtomicInteger hits = new AtomicInteger();
    final String[] error = new String[1];
    class Worker extends Thread {

        @Override
        public void run() {
            Random random = new Random();
            Time start = Time.now();
            while (start.elapsedSince().lessThan(duration) && error[0] == null) {
                logger.info("{} elapsed: {}, duration: {}", new Object[] { Thread.currentThread().getName(), start.elapsedSince(), duration });
                int page1 = random.nextInt(counts.length);
                int page2 = random.nextInt(counts.length);
                int count = 0;
                while (page2 == page1 && count < 100) {
                    page2 = random.nextInt(counts.length);
                    count++;
                }
                if (page2 == page1) {
                    throw new RuntimeException("orly?");
                }
                try {
                    sync.lockPage(page1);
                    sync.lockPage(page2);
                    // have locks, increment the count
                    counts[page1].incrementAndGet();
                    counts[page2].incrementAndGet();
                    hits.incrementAndGet();
                    // hold the lock for some time
                    try {
                        Thread.sleep(50);
                    } catch (InterruptedException e) {
                        error[0] = "Worker :" + Thread.currentThread().getName() + " interrupted";
                    }
                    // decrement the counts
                    counts[page1].decrementAndGet();
                    counts[page2].decrementAndGet();
                // release lock
                } catch (CouldNotLockPageException e) {
                // ignore
                } finally {
                    sync.unlockAllPages();
                }
            }
        }
    }
    class Monitor extends Thread {

        volatile boolean stop = false;

        @Override
        public void run() {
            while (!stop && error[0] == null) {
                for (int i = 0; i < counts.length; i++) {
                    int count = counts[i].get();
                    if (count < 0 || count > 1) {
                        error[0] = "Detected count of: " + count + " for page: " + i;
                        return;
                    }
                }
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    error[0] = "Monitor thread interrupted";
                }
            }
        }
    }
    Monitor monitor = new Monitor();
    monitor.setName("monitor");
    monitor.start();
    Worker[] bots = new Worker[workers];
    for (int i = 0; i < bots.length; i++) {
        bots[i] = new Worker();
        bots[i].setName("worker " + i);
        bots[i].start();
    }
    for (Worker bot : bots) {
        bot.join();
    }
    monitor.stop = true;
    monitor.join();
    assertNull(error[0], error[0]);
    assertTrue(hits.get() >= counts.length);
}
Also used : Time(org.apache.wicket.util.time.Time) Random(java.util.Random) AtomicInteger(java.util.concurrent.atomic.AtomicInteger)

Example 12 with Time

use of org.apache.wicket.util.time.Time in project wicket by apache.

the class ConnectionsTest method getLastModified.

/**
 * https://issues.apache.org/jira/browse/WICKET-5838
 */
@Test
public void getLastModified() throws Exception {
    URL url = new URL("http://wicket.apache.org/learn/books/wia.png");
    Time lastModified = Connections.getLastModified(url);
    assertThat(lastModified, is(notNullValue()));
    assertThat(lastModified.getMilliseconds(), is(not(0L)));
}
Also used : Time(org.apache.wicket.util.time.Time) URL(java.net.URL) Test(org.junit.Test)

Example 13 with Time

use of org.apache.wicket.util.time.Time in project wicket by apache.

the class LastModifiedTest method getLastModified.

/**
 * XXX: DOC ME
 *
 * @throws IOException
 */
@Test
public void getLastModified() throws IOException {
    File file = File.createTempFile("wicket-io-utils-test", "lastmodified");
    assertTrue(file.exists());
    try {
        long lm = file.lastModified();
        // it could be the case that the current system does not support last-modified at all
        if (lm != 0) {
            final Time expected = Time.millis(lm);
            assertEquals(expected, Files.getLastModified(file));
            assertEquals(expected, Connections.getLastModified(new URL("file:" + file.getAbsolutePath())));
        }
    } finally {
        Files.remove(file);
    }
}
Also used : Time(org.apache.wicket.util.time.Time) File(java.io.File) URL(java.net.URL) Test(org.junit.Test)

Example 14 with Time

use of org.apache.wicket.util.time.Time in project wicket by apache.

the class PackageResource method newResourceResponse.

/**
 * creates a new resource response based on the request attributes
 *
 * @param attributes
 *            current request attributes from client
 * @return resource response for answering request
 */
@Override
protected ResourceResponse newResourceResponse(Attributes attributes) {
    final ResourceResponse resourceResponse = new ResourceResponse();
    final IResourceStream resourceStream = getResourceStream();
    // bail out if resource stream could not be found
    if (resourceStream == null) {
        return sendResourceError(resourceResponse, HttpServletResponse.SC_NOT_FOUND, "Unable to find resource");
    }
    // add Last-Modified header (to support HEAD requests and If-Modified-Since)
    final Time lastModified = resourceStream.lastModifiedTime();
    resourceResponse.setLastModified(lastModified);
    if (resourceResponse.dataNeedsToBeWritten(attributes)) {
        String contentType = resourceStream.getContentType();
        if (contentType == null && Application.exists()) {
            contentType = Application.get().getMimeType(path);
        }
        // set Content-Type (may be null)
        resourceResponse.setContentType(contentType);
        // set content encoding (may be null)
        resourceResponse.setTextEncoding(getTextEncoding());
        // supports accept range
        resourceResponse.setAcceptRange(ContentRangeType.BYTES);
        try {
            // read resource data to get the content length
            InputStream inputStream = resourceStream.getInputStream();
            byte[] bytes = null;
            // send Content-Length header
            if (readBuffered) {
                bytes = IOUtils.toByteArray(inputStream);
                resourceResponse.setContentLength(bytes.length);
            } else {
                resourceResponse.setContentLength(resourceStream.length().bytes());
            }
            // get content range information
            RequestCycle cycle = RequestCycle.get();
            Long startbyte = cycle.getMetaData(CONTENT_RANGE_STARTBYTE);
            Long endbyte = cycle.getMetaData(CONTENT_RANGE_ENDBYTE);
            // send response body with resource data
            PartWriterCallback partWriterCallback = new PartWriterCallback(bytes != null ? new ByteArrayInputStream(bytes) : inputStream, resourceResponse.getContentLength(), startbyte, endbyte);
            // If read buffered is set to false ensure the part writer callback is going to
            // close the input stream
            resourceResponse.setWriteCallback(partWriterCallback.setClose(!readBuffered));
        } catch (IOException e) {
            log.debug(e.getMessage(), e);
            return sendResourceError(resourceResponse, 500, "Unable to read resource stream");
        } catch (ResourceStreamNotFoundException e) {
            log.debug(e.getMessage(), e);
            return sendResourceError(resourceResponse, 500, "Unable to open resource stream");
        } finally {
            try {
                if (readBuffered) {
                    IOUtils.close(resourceStream);
                }
            } catch (IOException e) {
                log.warn("Unable to close the resource stream", e);
            }
        }
    }
    return resourceResponse;
}
Also used : IResourceStream(org.apache.wicket.util.resource.IResourceStream) ByteArrayInputStream(java.io.ByteArrayInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) RequestCycle(org.apache.wicket.request.cycle.RequestCycle) Time(org.apache.wicket.util.time.Time) IOException(java.io.IOException) ResourceStreamNotFoundException(org.apache.wicket.util.resource.ResourceStreamNotFoundException)

Example 15 with Time

use of org.apache.wicket.util.time.Time in project wicket by apache.

the class AbstractResource method setResponseHeaders.

/**
 * Sets the response header of resource response to the response received from the attributes
 *
 * @param resourceResponse
 *            the resource response to get the header fields from
 * @param attributes
 *            the attributes to get the response from to which the header information are going
 *            to be applied
 */
protected void setResponseHeaders(final ResourceResponse resourceResponse, final Attributes attributes) {
    Response response = attributes.getResponse();
    if (response instanceof WebResponse) {
        WebResponse webResponse = (WebResponse) response;
        // 1. Last Modified
        Time lastModified = resourceResponse.getLastModified();
        if (lastModified != null) {
            webResponse.setLastModifiedTime(lastModified);
        }
        // 2. Caching
        configureCache(resourceResponse, attributes);
        if (resourceResponse.getErrorCode() != null) {
            webResponse.sendError(resourceResponse.getErrorCode(), resourceResponse.getErrorMessage());
            return;
        }
        if (resourceResponse.getStatusCode() != null) {
            webResponse.setStatus(resourceResponse.getStatusCode());
        }
        if (!resourceResponse.dataNeedsToBeWritten(attributes)) {
            webResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
            return;
        }
        // 3. Content Disposition
        String fileName = resourceResponse.getFileName();
        ContentDisposition disposition = resourceResponse.getContentDisposition();
        if (ContentDisposition.ATTACHMENT == disposition) {
            webResponse.setAttachmentHeader(fileName);
        } else if (ContentDisposition.INLINE == disposition) {
            webResponse.setInlineHeader(fileName);
        }
        // 4. Mime Type (+ encoding)
        String mimeType = resourceResponse.getContentType();
        if (mimeType != null) {
            final String encoding = resourceResponse.getTextEncoding();
            if (encoding == null) {
                webResponse.setContentType(mimeType);
            } else {
                webResponse.setContentType(mimeType + "; charset=" + encoding);
            }
        }
        // 5. Accept Range
        ContentRangeType acceptRange = resourceResponse.getAcceptRange();
        if (acceptRange != null) {
            webResponse.setAcceptRange(acceptRange.getTypeName());
        }
        long contentLength = resourceResponse.getContentLength();
        boolean contentRangeApplied = false;
        // 6. Content Range
        // for more information take a look here:
        // http://stackoverflow.com/questions/8293687/sample-http-range-request-session
        // if the content range header has been set directly
        // to the resource response use it otherwise calculate it
        String contentRange = resourceResponse.getContentRange();
        if (contentRange != null) {
            webResponse.setContentRange(contentRange);
        } else {
            // moment
            if (contentLength != -1 && ContentRangeType.BYTES.equals(acceptRange)) {
                contentRangeApplied = setResponseContentRangeHeaderFields(webResponse, attributes, contentLength);
            }
        }
        // 7. Content Length
        if (contentLength != -1 && !contentRangeApplied) {
            webResponse.setContentLength(contentLength);
        }
        // add custom headers and values
        final HttpHeaderCollection headers = resourceResponse.getHeaders();
        for (String name : headers.getHeaderNames()) {
            checkHeaderAccess(name);
            for (String value : headers.getHeaderValues(name)) {
                webResponse.addHeader(name, value);
            }
        }
    }
}
Also used : HttpServletResponse(javax.servlet.http.HttpServletResponse) WebResponse(org.apache.wicket.request.http.WebResponse) Response(org.apache.wicket.request.Response) WebResponse(org.apache.wicket.request.http.WebResponse) Time(org.apache.wicket.util.time.Time) HttpHeaderCollection(org.apache.wicket.request.HttpHeaderCollection)

Aggregations

Time (org.apache.wicket.util.time.Time)21 Test (org.junit.Test)6 IOException (java.io.IOException)5 IResourceStream (org.apache.wicket.util.resource.IResourceStream)5 ResourceStreamNotFoundException (org.apache.wicket.util.resource.ResourceStreamNotFoundException)4 Duration (org.apache.wicket.util.time.Duration)4 ByteArrayInputStream (java.io.ByteArrayInputStream)2 InputStream (java.io.InputStream)2 URL (java.net.URL)2 LocalDateTime (java.time.LocalDateTime)2 File (java.io.File)1 Locale (java.util.Locale)1 Random (java.util.Random)1 TimeZone (java.util.TimeZone)1 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)1 HttpServletRequest (javax.servlet.http.HttpServletRequest)1 HttpServletResponse (javax.servlet.http.HttpServletResponse)1 HttpHeaderCollection (org.apache.wicket.request.HttpHeaderCollection)1 Response (org.apache.wicket.request.Response)1 RequestCycle (org.apache.wicket.request.cycle.RequestCycle)1