Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make sure AutoCloseable resources are closed #127

Merged
merged 1 commit into from
Aug 16, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@
public class RuntimeExtensionBindingTest {

// Basic verification that binding works as expected. ITs will exercise this more thoroughly.
@SuppressWarnings("resource")
@Test
@Ignore
public void bindingTest() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -356,32 +356,35 @@ private void commonTests(final URI object) throws Exception {
responseFromService.setHeader(customHeader, customHeaderValue);

// Perform the request!
final FcrepoResponse response = client.post(
append(exposedServiceEndpoint, String.join("?", additionalPath, query))).slug(slug).perform();
try (FcrepoResponse response = client.post(
append(exposedServiceEndpoint, String.join("?", additionalPath, query))).slug(slug).perform()) {

// Make sure the host header in the response to client matches request host from client
assertEquals(exposedServiceEndpoint.getAuthority(), URI.create(requestToService.getHeader(Exchange.HTTP_URL,
String.class)).getAuthority());
// Make sure the host header in the response to client matches request host from client
assertEquals(exposedServiceEndpoint.getAuthority(), URI.create(requestToService.getHeader(
Exchange.HTTP_URL,
String.class)).getAuthority());

// Make sure the body returned by the service is received
assertEquals(BODY, IOUtils.toString(response.getBody(), "UTF-8"));
// Make sure the body returned by the service is received
assertEquals(BODY, IOUtils.toString(response.getBody(), "UTF-8"));

// Make sure the status code is what we want
assertEquals(HttpStatus.SC_ACCEPTED, response.getStatusCode());
// Make sure the status code is what we want
assertEquals(HttpStatus.SC_ACCEPTED, response.getStatusCode());

// Make sure the query components are passed to the service
assertEquals(query, requestToService.getHeader(Exchange.HTTP_QUERY));
// Make sure the query components are passed to the service
assertEquals(query, requestToService.getHeader(Exchange.HTTP_QUERY));

// Make sure the path components are passed on
assertEquals(additionalPath, requestToService.getHeader(Exchange.HTTP_PATH));
// Make sure the path components are passed on
assertEquals(additionalPath, requestToService.getHeader(Exchange.HTTP_PATH));

// Make sure a client-provided header is passed along
assertEquals(slug, requestToService.getHeader("Slug"));
// Make sure a client-provided header is passed along
assertEquals(slug, requestToService.getHeader("Slug"));

// Make sure that a server-provided header is passed back to client
assertEquals(customHeaderValue, response.getHeaderValue(customHeader));
// Make sure that a server-provided header is passed back to client
assertEquals(customHeaderValue, response.getHeaderValue(customHeader));

// Make sure the exposed service URI relayed to our service, in the expected header.
assertEquals(exposedServiceEndpoint.toString(), requestToService.getHeader(HTTP_HEADER_EXPOSED_SERVICE_URI));
// Make sure the exposed service URI relayed to our service, in the expected header.
assertEquals(exposedServiceEndpoint.toString(), requestToService.getHeader(
HTTP_HEADER_EXPOSED_SERVICE_URI));
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -80,12 +80,13 @@ public void serviceLinkHeaderTest() throws Exception {

final URI object = client.post(objectContainer).slug(testMethodName()).perform().getLocation();

final FcrepoResponse response = client.get(
routing.of(REQUEST_URI).interceptUriFor(object)).perform();
try (final FcrepoResponse response = client.get(
routing.of(REQUEST_URI).interceptUriFor(object)).perform()) {

assertEquals(1, response.getLinkHeaders("service").size());
assertEquals(routing.of(REQUEST_URI).serviceDocFor(object),
response.getLinkHeaders("service").get(0));
assertEquals(1, response.getLinkHeaders("service").size());
assertEquals(routing.of(REQUEST_URI).serviceDocFor(object),
response.getLinkHeaders("service").get(0));
}
}

// Verify that if an intercepting extension throws a 4xx code, it aborts the request and returns service response.
Expand All @@ -106,10 +107,11 @@ public void incomingInterceptRespomseCodeTest() throws Exception {
final URI object = postFromTestResource("objects/object_InterceptingServiceIT.ttl",
objectContainer_intercept);

final FcrepoResponse response = FcrepoClient.client().build().get(object).perform();
try (FcrepoResponse response = FcrepoClient.client().build().get(object).perform()) {

assertEquals(RESPONSE_CODE, response.getStatusCode());
assertEquals(LOCATION, response.getHeaderValue("Location"));
assertEquals(RESPONSE_CODE, response.getStatusCode());
assertEquals(LOCATION, response.getHeaderValue("Location"));
}
}

@Test
Expand Down Expand Up @@ -217,10 +219,11 @@ public void outgoingHeaderTest() throws Exception {
final URI object = postFromTestResource("objects/object_InterceptingServiceIT.ttl",
objectContainer_intercept);

final FcrepoResponse response = client.get(object).accept("application/n-triples").perform();
try (final FcrepoResponse response = client.get(object).accept("application/n-triples").perform()) {

assertEquals(TEST_HEADER_VALUE, response.getHeaderValue(TEST_HEADER));
assertTrue(IOUtils.toString(response.getBody(), "UTF-8").contains(TEST_OBJECT_TYPE));
assertEquals(TEST_HEADER_VALUE, response.getHeaderValue(TEST_HEADER));
assertTrue(IOUtils.toString(response.getBody(), "UTF-8").contains(TEST_OBJECT_TYPE));
}
}

@Test
Expand All @@ -242,10 +245,10 @@ public void outgoingBodyTest() throws Exception {
final URI object = postFromTestResource("objects/object_InterceptingServiceIT.ttl",
objectContainer_intercept);

final FcrepoResponse response = client.get(object).perform();

assertTrue(IOUtils.toString(response.getBody(), "UTF-8").equals(BODY));
try (final FcrepoResponse response = client.get(object).perform()) {

assertTrue(IOUtils.toString(response.getBody(), "UTF-8").equals(BODY));
}
}

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,7 @@ public default WebResource testResource(String path) {
* @param path the resource path relative to {@link #testResources}
* @return the resulting WebResource
*/
@SuppressWarnings("resource")
public default WebResource testResource(String path, String contentType) {
final File file = new File(testResources, path);
try {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -292,11 +292,12 @@ public void ontologyEmbeddedExtensionTest() throws Exception {

// Now update it without issue
optionsResponse.set(optionsResponse.get() + triple("", RDF_TYPE, TEST_TYPE));
final FcrepoResponse response = textPost(LOADER_URI, serviceEndpoint);
assertEquals(origLocation, response.getHeaderValue("Location"));
try (FcrepoResponse response = textPost(LOADER_URI, serviceEndpoint)) {
assertEquals(origLocation, response.getHeaderValue("Location"));

// Now assure that our new triple is present in its representation
IOUtils.toString(response.getBody(), "utf8").contains(TEST_TYPE);
// Now assure that our new triple is present in its representation
IOUtils.toString(response.getBody(), "utf8").contains(TEST_TYPE);
}
}

@Test
Expand All @@ -323,19 +324,20 @@ public void extensionUpdateTest() throws Exception {
// Now alter the content of the available extension doc, the loader should slurp up the
// changes
optionsResponse.set(optionsResponse.get() + triple("", RDF_TYPE, TEST_TYPE));
final FcrepoResponse response = textPost(LOADER_URI, serviceEndpoint);
try (final FcrepoResponse response = textPost(LOADER_URI, serviceEndpoint)) {

// Make sure the extension document URI didn't change (i.e. we're working with one
// persisted extension doc, rather than creating a new one each time.
assertEquals(uri, response.getHeaderValue("Location"));
// Make sure the extension document URI didn't change (i.e. we're working with one
// persisted extension doc, rather than creating a new one each time.
assertEquals(uri, response.getHeaderValue("Location"));

// Now, verify that the extension doc has our new statement
IOUtils.toString(response.getBody(), "utf8").contains(TEST_TYPE);
// Now, verify that the extension doc has our new statement
IOUtils.toString(response.getBody(), "utf8").contains(TEST_TYPE);

update();
update();

// Make sure we only have ONE entry in the service registry for our service
assertEquals(1, countServiceRegistryEntries(SERVICE_CANONICAL_URI));
// Make sure we only have ONE entry in the service registry for our service
assertEquals(1, countServiceRegistryEntries(SERVICE_CANONICAL_URI));
}
}

private final FcrepoResponse textPost(final String uri, final String content) throws Exception {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,34 @@

package org.fcrepo.apix.integration;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.atomic.AtomicBoolean;

import javax.inject.Inject;

import org.fcrepo.client.FcrepoOperationFailedException;
import org.fcrepo.client.FcrepoResponse;

import org.apache.camel.CamelContext;
import org.apache.camel.builder.AdviceWithRouteBuilder;
import org.apache.camel.model.ModelCamelContext;
import org.apache.commons.io.input.NullInputStream;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.rdf.model.ResourceFactory;
import org.fcrepo.client.FcrepoOperationFailedException;
import org.fcrepo.client.FcrepoResponse;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
Expand All @@ -37,24 +57,6 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.inject.Inject;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.atomic.AtomicBoolean;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

/**
* Integration tests relating to streaming content proxied by API-X
*
Expand Down Expand Up @@ -104,7 +106,7 @@ public static void initMessageDigest() throws NoSuchAlgorithmException {
}

/**
* Creates a container and a binary resource of 2MiB + 1 bytes long. Retrieves checksum of the resource.
* Creates a container and a binary resource of 2MiB + 1 bytes long. Retrieves checksum of the resource.
*
* @throws FcrepoOperationFailedException if unexpected things go wrong
* @throws IOException if unexpected things go wrong
Expand All @@ -116,11 +118,11 @@ public void initBinaryResources() throws FcrepoOperationFailedException, IOExcep

// Create container if it doesn't already exist
if (!resourceExists(binaryContainer)) {
try (FcrepoResponse r = client.put(binaryContainer)
.body(
new FileInputStream(
new File(testResources, "objects/binary_container.ttl")), "text/turtle")
.perform()) {
try (FileInputStream body = new FileInputStream(
new File(testResources, "objects/binary_container.ttl"));
FcrepoResponse r = client.put(binaryContainer)
.body(body, "text/turtle")
.perform()) {
assertEquals("Failed to create binary container '" + binaryContainer + "'",
201, r.getStatusCode());
}
Expand All @@ -130,11 +132,11 @@ public void initBinaryResources() throws FcrepoOperationFailedException, IOExcep
final URI expectedBinaryResource = appendToPath(binaryContainer, "large-binary");
if (!resourceExists(expectedBinaryResource)) {
LOG.warn("Expected resource did not exist {}", expectedBinaryResource);
try {
try (InputStream body = new NullInputStream((2 * 1024 * 1024) + 1)) {
binaryResource = postFromStream(
new NullInputStream((2 * 1024 * 1024) + 1), binaryContainer,
body, binaryContainer,
"application/octet-stream", "large-binary");
} catch (Exception e) {
} catch (final Exception e) {
fail(String.format("Failed to create binary LDPR: %s", e.getMessage()));
}
} else {
Expand All @@ -147,7 +149,7 @@ public void initBinaryResources() throws FcrepoOperationFailedException, IOExcep
.get(appendToPath(binaryResource, "/fcr:metadata"))
.accept("application/rdf+xml")
.perform().getBody(),
null)
null)
.listObjectsOfProperty(
ResourceFactory
.createProperty("http://www.loc.gov/premis/rdf/v1#", "hasMessageDigest"))
Expand All @@ -169,7 +171,7 @@ public void verifyContextAndRoute() {
}

/**
* Verify the binary can be retrieved from Fedora. The request should <em>not</em> be intercepted.
* Verify the binary can be retrieved from Fedora. The request should <em>not</em> be intercepted.
*
* @throws Exception if unexpected things go wrong
*/
Expand All @@ -179,6 +181,7 @@ public void testRetrieveLargeBinaryFromFedora() throws Exception {
// Record 'true' if the intercepting route is triggered
final AtomicBoolean intercepted = new AtomicBoolean(false);
ctx.getRouteDefinition(INTERCEPT_ROUTE_ID).adviceWith((ModelCamelContext) ctx, new AdviceWithRouteBuilder() {

@Override
public void configure() throws Exception {
weaveAddFirst().process((ex) -> intercepted.set(true));
Expand All @@ -190,7 +193,7 @@ public void configure() throws Exception {
final String actualDigest;

try (FcrepoResponse r = client.get(binaryResource).perform();
DigestInputStream body = new DigestInputStream(r.getBody(), sha1)) {
DigestInputStream body = new DigestInputStream(r.getBody(), sha1)) {
actualSize = drain(body);
actualDigest = asHex(body.getMessageDigest().digest());
}
Expand All @@ -205,8 +208,8 @@ public void configure() throws Exception {
}

/**
* Verify the binary can be retrieved through the API-X proxy. The request should be intercepted and proxied
* by API-X.
* Verify the binary can be retrieved through the API-X proxy. The request should be intercepted and proxied by
* API-X.
*
* @throws Exception if unexpected things go wrong
*/
Expand All @@ -216,6 +219,7 @@ public void testRetrieveLargeBinaryFromApix() throws Exception {
// Record 'true' if the intercepting route is triggered
final AtomicBoolean intercepted = new AtomicBoolean(false);
ctx.getRouteDefinition(INTERCEPT_ROUTE_ID).adviceWith((ModelCamelContext) ctx, new AdviceWithRouteBuilder() {

@Override
public void configure() throws Exception {
weaveAddFirst().process((ex) -> intercepted.set(true));
Expand All @@ -228,7 +232,7 @@ public void configure() throws Exception {

final URI proxiedResource = proxied(binaryResource);
try (FcrepoResponse r = KarafIT.attempt(30, () -> client.get(proxiedResource).perform());
DigestInputStream body = new DigestInputStream(r.getBody(), sha1)) {
DigestInputStream body = new DigestInputStream(r.getBody(), sha1)) {
actualSize = drain(body);
actualDigest = asHex(body.getMessageDigest().digest());
}
Expand All @@ -254,7 +258,7 @@ private boolean resourceExists(final URI resource) throws IOException {
if (r.getStatusCode() == 200) {
return true;
}
} catch (FcrepoOperationFailedException e) {
} catch (final FcrepoOperationFailedException e) {
// Probably the resource doesn't exist.
LOG.debug("Error retrieving resource '" + resource + "': " + e.getMessage(), e);
}
Expand Down Expand Up @@ -312,9 +316,9 @@ private static URI proxied(final URI toProxy) throws URISyntaxException {
}

/**
* Appends the path to the URI. All other components of the URI are preserved.
* Appends the path to the URI. All other components of the URI are preserved.
*
* @param uri the URI with the path being appended to
* @param uri the URI with the path being appended to
* @param toAppend the path to be appended to the URI
* @return a new URI with a path component ending with {@code toAppend}
* @throws URISyntaxException
Expand All @@ -336,9 +340,8 @@ private static URI appendToPath(final URI uri, final String toAppend) throws URI
* @return true if the supplied URI will be proxied by API-X, false otherwise
*/
private static boolean isProxied(final URI uri) {
return uri.getScheme().equals(APIX_BASE_URI.getScheme())
&& uri.getHost().equals(APIX_BASE_URI.getHost())
&& uri.getPort() == APIX_BASE_URI.getPort();
return uri.getScheme().equals(APIX_BASE_URI.getScheme()) && uri.getHost().equals(APIX_BASE_URI.getHost()) &&
uri.getPort() == APIX_BASE_URI.getPort();
}

}
Loading