You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@stanbol.apache.org by sf...@apache.org on 2011/03/05 21:14:21 UTC
svn commit: r1078342 - in /incubator/stanbol/trunk/commons:
stanboltools/offline/src/main/java/org/apache/stanbol/commons/stanboltools/offline/
testing/http/src/main/java/org/apache/stanbol/commons/testing/http/
testing/jarexec/src/main/java/org/apache...
Author: sfermigier
Date: Sat Mar 5 20:14:20 2011
New Revision: 1078342
URL: http://svn.apache.org/viewvc?rev=1078342&view=rev
Log:
Format, fix javadoc.
Modified:
incubator/stanbol/trunk/commons/stanboltools/offline/src/main/java/org/apache/stanbol/commons/stanboltools/offline/Activator.java
incubator/stanbol/trunk/commons/testing/http/src/main/java/org/apache/stanbol/commons/testing/http/Request.java
incubator/stanbol/trunk/commons/testing/http/src/main/java/org/apache/stanbol/commons/testing/http/RequestBuilder.java
incubator/stanbol/trunk/commons/testing/http/src/main/java/org/apache/stanbol/commons/testing/http/RequestDocumentor.java
incubator/stanbol/trunk/commons/testing/http/src/main/java/org/apache/stanbol/commons/testing/http/RequestExecutor.java
incubator/stanbol/trunk/commons/testing/http/src/main/java/org/apache/stanbol/commons/testing/http/RetryLoop.java
incubator/stanbol/trunk/commons/testing/jarexec/src/main/java/org/apache/stanbol/commons/testing/jarexec/JarExecutor.java
incubator/stanbol/trunk/commons/testing/stanbol/src/main/java/org/apache/stanbol/commons/testing/stanbol/StanbolTestBase.java
Modified: incubator/stanbol/trunk/commons/stanboltools/offline/src/main/java/org/apache/stanbol/commons/stanboltools/offline/Activator.java
URL: http://svn.apache.org/viewvc/incubator/stanbol/trunk/commons/stanboltools/offline/src/main/java/org/apache/stanbol/commons/stanboltools/offline/Activator.java?rev=1078342&r1=1078341&r2=1078342&view=diff
==============================================================================
--- incubator/stanbol/trunk/commons/stanboltools/offline/src/main/java/org/apache/stanbol/commons/stanboltools/offline/Activator.java (original)
+++ incubator/stanbol/trunk/commons/stanboltools/offline/src/main/java/org/apache/stanbol/commons/stanboltools/offline/Activator.java Sat Mar 5 20:14:20 2011
@@ -22,35 +22,36 @@ import org.osgi.framework.ServiceRegistr
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-/** Activator for the offline mnode bundle */
+/**
+ * Activator for the offline mode bundle
+ */
public class Activator implements BundleActivator {
+
private final Logger log = LoggerFactory.getLogger(getClass());
public static final String OFFLINE_MODE_PROPERTY = "org.apache.stanbol.offline.mode";
- private ServiceRegistration serviceReg = null;
-
+ private ServiceRegistration serviceReg;
+
@Override
public void start(BundleContext context) throws Exception {
final String s = System.getProperty(OFFLINE_MODE_PROPERTY);
Object svc = null;
String svcName = null;
-
- if("true".equals(s)) {
+
+ if ("true".equals(s)) {
svc = new OfflineMode() {};
svcName = OfflineMode.class.getName();
- log.info("OfflineMode activated by {}={}",
- OFFLINE_MODE_PROPERTY, s);
+ log.info("OfflineMode activated by {}={}", OFFLINE_MODE_PROPERTY, s);
} else {
svc = new OnlineMode() {};
svcName = OnlineMode.class.getName();
- log.info("Offline mode is not set by {}, OnlineMode activated",
- OFFLINE_MODE_PROPERTY);
+ log.info("Offline mode is not set by {}, OnlineMode activated", OFFLINE_MODE_PROPERTY);
}
serviceReg = context.registerService(svcName, svc, null);
}
@Override
public void stop(BundleContext context) throws Exception {
- if(serviceReg != null) {
+ if (serviceReg != null) {
serviceReg.unregister();
serviceReg = null;
}
Modified: incubator/stanbol/trunk/commons/testing/http/src/main/java/org/apache/stanbol/commons/testing/http/Request.java
URL: http://svn.apache.org/viewvc/incubator/stanbol/trunk/commons/testing/http/src/main/java/org/apache/stanbol/commons/testing/http/Request.java?rev=1078342&r1=1078341&r2=1078342&view=diff
==============================================================================
--- incubator/stanbol/trunk/commons/testing/http/src/main/java/org/apache/stanbol/commons/testing/http/Request.java (original)
+++ incubator/stanbol/trunk/commons/testing/http/src/main/java/org/apache/stanbol/commons/testing/http/Request.java Sat Mar 5 20:14:20 2011
@@ -23,28 +23,30 @@ import org.apache.http.client.methods.Ht
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.StringEntity;
-/** Request class with convenience with... methods to
- * add headers, parameters etc.
+/**
+ * Request class with convenience withXxx methods to
+ * add headers, parameters, etc.
*/
public class Request {
+
private final HttpUriRequest request;
private String username;
private String password;
private boolean redirects = true;
-
+
Request(HttpUriRequest r) {
request = r;
}
-
+
public HttpUriRequest getRequest() {
return request;
}
-
+
public Request withHeader(String name, String value) {
request.addHeader(name, value);
return this;
}
-
+
public Request withCredentials(String username, String password) {
this.username = username;
this.password = password;
@@ -55,34 +57,33 @@ public class Request {
redirects = followRedirectsAutomatically;
return this;
}
-
+
private HttpEntityEnclosingRequestBase getHttpEntityEnclosingRequestBase() {
- if(request instanceof HttpEntityEnclosingRequestBase) {
- return (HttpEntityEnclosingRequestBase)request;
+ if (request instanceof HttpEntityEnclosingRequestBase) {
+ return (HttpEntityEnclosingRequestBase) request;
} else {
- throw new IllegalStateException(
- "Request is not an HttpEntityEnclosingRequestBase: "
- + request.getClass().getName());
+ throw new IllegalStateException("Request is not an HttpEntityEnclosingRequestBase: "
+ + request.getClass().getName());
}
}
public Request withContent(String content) throws UnsupportedEncodingException {
return withEntity(new StringEntity(content, "UTF-8"));
}
-
- public Request withEntity(HttpEntity e) throws UnsupportedEncodingException {
+
+ public Request withEntity(HttpEntity e) {
getHttpEntityEnclosingRequestBase().setEntity(e);
return this;
}
-
+
public String getUsername() {
return username;
}
-
+
public String getPassword() {
return password;
}
-
+
public boolean getRedirects() {
return redirects;
}
Modified: incubator/stanbol/trunk/commons/testing/http/src/main/java/org/apache/stanbol/commons/testing/http/RequestBuilder.java
URL: http://svn.apache.org/viewvc/incubator/stanbol/trunk/commons/testing/http/src/main/java/org/apache/stanbol/commons/testing/http/RequestBuilder.java?rev=1078342&r1=1078341&r2=1078342&view=diff
==============================================================================
--- incubator/stanbol/trunk/commons/testing/http/src/main/java/org/apache/stanbol/commons/testing/http/RequestBuilder.java (original)
+++ incubator/stanbol/trunk/commons/testing/http/src/main/java/org/apache/stanbol/commons/testing/http/RequestBuilder.java Sat Mar 5 20:14:20 2011
@@ -26,65 +26,71 @@ import org.apache.http.client.methods.Ht
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.message.BasicNameValuePair;
-/** Convenience builder for Request objects */
+/**
+ * Convenience builder for Request objects.
+ */
public class RequestBuilder {
+
private final String baseUrl;
-
+
public RequestBuilder(String baseUrl) {
this.baseUrl = baseUrl;
}
-
- /** Build a GET request to specified path with optional query
- * parameters. See {@link #buildUrl(String, String...)} for
- * queryParameters semantics.
+
+ /**
+ * Build a GET request to specified path with optional query
+ * parameters. See {@link #buildUrl(String, String...)} for
+ * queryParameters semantics.
*/
- public Request buildGetRequest(String path, String...queryParameters) {
+ public Request buildGetRequest(String path, String... queryParameters) {
return new Request(new HttpGet(buildUrl(path, queryParameters)));
}
-
- /** Build a POST request to specified path with optional query
- * parameters. See {@link #buildUrl(String, String...)} for
- * queryParameters semantics.
+
+ /**
+ * Build a POST request to specified path with optional query
+ * parameters. See {@link #buildUrl(String, String...)} for
+ * queryParameters semantics.
*/
public Request buildPostRequest(String path) {
return new Request(new HttpPost(buildUrl(path)));
}
-
- /** Wrap supplied HTTP request */
+
+ /**
+ * Wrap supplied HTTP request
+ */
public Request buildOtherRequest(HttpRequestBase r) {
return new Request(r);
}
-
- /** Build an URL from our base path, supplied path and optional
- * query parameters.
- * @param queryParameters an even number of Strings, each pair
- * of values represents the key and value of a query parameter.
- * Keys and values are encoded by this method.
+
+ /**
+ * Build an URL from our base path, supplied path and optional
+ * query parameters.
+ *
+ * @param queryParameters an even number of Strings, each pair
+ * of values represents the key and value of a query parameter.
+ * Keys and values are encoded by this method.
*/
- public String buildUrl(String path, String...queryParameters) {
+ public String buildUrl(String path, String... queryParameters) {
final StringBuilder sb = new StringBuilder();
-
- if(queryParameters == null || queryParameters.length == 0) {
+
+ if (queryParameters == null || queryParameters.length == 0) {
sb.append(baseUrl);
sb.append(path);
-
- } else if(queryParameters.length % 2 != 0) {
- throw new IllegalArgumentException(
- "Invalid number of queryParameters arguments ("
- + queryParameters.length
- + "), must be even"
- );
+
+ } else if (queryParameters.length % 2 != 0) {
+ throw new IllegalArgumentException("Invalid number of queryParameters arguments ("
+ + queryParameters.length + "), must be even");
} else {
final List<NameValuePair> p = new ArrayList<NameValuePair>();
- for(int i=0 ; i < queryParameters.length; i+=2) {
- p.add(new BasicNameValuePair(queryParameters[i], queryParameters[i+1]));
+ for (int i = 0; i < queryParameters.length; i += 2) {
+ p.add(new BasicNameValuePair(queryParameters[i], queryParameters[i + 1]));
}
sb.append(baseUrl);
sb.append(path);
sb.append("?");
sb.append(URLEncodedUtils.format(p, "UTF-8"));
}
-
+
return sb.toString();
}
}
Modified: incubator/stanbol/trunk/commons/testing/http/src/main/java/org/apache/stanbol/commons/testing/http/RequestDocumentor.java
URL: http://svn.apache.org/viewvc/incubator/stanbol/trunk/commons/testing/http/src/main/java/org/apache/stanbol/commons/testing/http/RequestDocumentor.java?rev=1078342&r1=1078341&r2=1078342&view=diff
==============================================================================
--- incubator/stanbol/trunk/commons/testing/http/src/main/java/org/apache/stanbol/commons/testing/http/RequestDocumentor.java (original)
+++ incubator/stanbol/trunk/commons/testing/http/src/main/java/org/apache/stanbol/commons/testing/http/RequestDocumentor.java Sat Mar 5 20:14:20 2011
@@ -28,27 +28,29 @@ import org.apache.http.Header;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
-/** Generate RESTful API documentation based on actual requests
- * executed during integration tests, enhanced with user-supplied
- * bits of documentation.
+/**
+ * Generate RESTful API documentation based on actual requests
+ * executed during integration tests, enhanced with user-supplied
+ * bits of documentation.
*/
public class RequestDocumentor {
+
public static final String OUTPUT_BASE = "./target/" + RequestDocumentor.class.getSimpleName();
private final String name;
-
+
public RequestDocumentor(String name) {
this.name = name;
}
-
+
public String toString() {
return getClass().getSimpleName() + " (" + name + ")";
}
-
- void generateDocumentation(RequestExecutor executor, String [] metadata) throws IOException {
+
+ void generateDocumentation(RequestExecutor executor, String[] metadata) throws IOException {
final File f = getOutputFile();
final File dir = f.getParentFile();
dir.mkdirs();
- if(!dir.isDirectory()) {
+ if (!dir.isDirectory()) {
throw new IOException("Failed to create output folder " + dir.getAbsolutePath());
}
final PrintWriter pw = new PrintWriter(new FileWriter(f, true));
@@ -60,21 +62,22 @@ public class RequestDocumentor {
pw.close();
}
}
-
+
protected File getOutputFile() {
return new File(OUTPUT_BASE + "/" + name + ".txt");
}
-
- protected void documentRequest(PrintWriter pw, RequestExecutor executor, String [] metadataArray) throws IOException {
+
+ protected void documentRequest(PrintWriter pw, RequestExecutor executor, String[] metadataArray)
+ throws IOException {
// Convert metadata to more convenient Map
final Map<String, String> m = new HashMap<String, String>();
- if(metadataArray.length % 2 != 0) {
+ if (metadataArray.length % 2 != 0) {
throw new IllegalArgumentException("Metadata array must be of even size, got " + metadataArray.length);
}
- for(int i=0 ; i < metadataArray.length; i += 2) {
- m.put(metadataArray[i], metadataArray[i+1]);
+ for (int i = 0; i < metadataArray.length; i += 2) {
+ m.put(metadataArray[i], metadataArray[i + 1]);
}
-
+
// TODO use velocity or other templates? Just a rough prototype for now
// Also need to filter overly long input/output, binary etc.
pw.println();
@@ -87,39 +90,39 @@ public class RequestDocumentor {
pw.print("\n=== ");
pw.print("REQUEST");
pw.println(" ===");
-
+
pw.print("Method: ");
pw.println(executor.getRequest().getMethod());
pw.print("URI: ");
pw.println(executor.getRequest().getURI());
-
- final Header [] allHeaders = executor.getRequest().getAllHeaders();
- if(allHeaders != null && allHeaders.length > 0) {
+
+ final Header[] allHeaders = executor.getRequest().getAllHeaders();
+ if (allHeaders != null && allHeaders.length > 0) {
pw.println("Headers:");
- for(Header h : allHeaders) {
+ for (Header h : allHeaders) {
pw.print(h.getName());
pw.print(":");
pw.println(h.getValue());
}
}
-
- if(executor.getRequest() instanceof HttpEntityEnclosingRequestBase) {
- final HttpEntityEnclosingRequestBase heb = (HttpEntityEnclosingRequestBase)executor.getRequest();
- if(heb.getEntity() != null) {
+
+ if (executor.getRequest() instanceof HttpEntityEnclosingRequestBase) {
+ final HttpEntityEnclosingRequestBase heb = (HttpEntityEnclosingRequestBase) executor.getRequest();
+ if (heb.getEntity() != null) {
pw.print("Content-Type:");
pw.println(heb.getEntity().getContentType().getValue());
pw.println("Content:");
final InputStream is = heb.getEntity().getContent();
final byte[] buffer = new byte[16384];
int count = 0;
- while( (count = is.read(buffer, 0, buffer.length)) > 0) {
+ while ((count = is.read(buffer, 0, buffer.length)) > 0) {
// TODO encoding??
pw.write(new String(buffer, 0, count));
}
pw.println();
}
}
-
+
pw.print("\n=== ");
pw.print("RESPONSE");
pw.println(" ===");
@@ -127,7 +130,7 @@ public class RequestDocumentor {
pw.println(executor.getResponse().getEntity().getContentType().getValue());
pw.println("Content:");
pw.println(executor.getContent());
-
+
pw.println("====================================================================================");
}
}
Modified: incubator/stanbol/trunk/commons/testing/http/src/main/java/org/apache/stanbol/commons/testing/http/RequestExecutor.java
URL: http://svn.apache.org/viewvc/incubator/stanbol/trunk/commons/testing/http/src/main/java/org/apache/stanbol/commons/testing/http/RequestExecutor.java?rev=1078342&r1=1078341&r2=1078342&view=diff
==============================================================================
--- incubator/stanbol/trunk/commons/testing/http/src/main/java/org/apache/stanbol/commons/testing/http/RequestExecutor.java (original)
+++ incubator/stanbol/trunk/commons/testing/http/src/main/java/org/apache/stanbol/commons/testing/http/RequestExecutor.java Sat Mar 5 20:14:20 2011
@@ -47,69 +47,64 @@ import org.apache.http.protocol.Executio
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
-/** Executes a Request and provides convenience methods
- * to validate the results.
+/**
+ * Executes a Request and provides convenience methods
+ * to validate the results.
*/
public class RequestExecutor {
+
private final DefaultHttpClient httpClient;
- private HttpUriRequest request;
+ private HttpUriRequest request;
private HttpResponse response;
private HttpEntity entity;
private String content;
-
+
/**
* HttpRequestInterceptor for preemptive authentication, based on httpclient
* 4.0 example
*/
- private static class PreemptiveAuthInterceptor implements
- HttpRequestInterceptor {
+ private static class PreemptiveAuthInterceptor implements HttpRequestInterceptor {
- public void process(HttpRequest request, HttpContext context)
- throws HttpException, IOException {
+ public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
- AuthState authState =
- (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
- CredentialsProvider credsProvider =
- (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER);
- HttpHost targetHost =
- (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
+ AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
+ CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER);
+ HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
// If not auth scheme has been initialized yet
if (authState.getAuthScheme() == null) {
- AuthScope authScope =
- new AuthScope(targetHost.getHostName(), targetHost.getPort());
+ AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
// Obtain credentials matching the target host
Credentials creds = credsProvider.getCredentials(authScope);
// If found, generate BasicScheme preemptively
- if(creds != null) {
+ if (creds != null) {
authState.setAuthScheme(new BasicScheme());
authState.setCredentials(creds);
}
}
}
}
-
+
public RequestExecutor(DefaultHttpClient client) {
httpClient = client;
}
-
+
public String toString() {
- if(request == null) {
+ if (request == null) {
return "Request";
}
return request.getMethod() + " request to " + request.getURI();
}
-
+
public RequestExecutor execute(Request r) throws ClientProtocolException, IOException {
clear();
request = r.getRequest();
-
+
// Optionally setup for basic authentication
- if(r.getUsername() != null) {
- httpClient.getCredentialsProvider().setCredentials(
- AuthScope.ANY,
+ if (r.getUsername() != null) {
+ httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials(r.getUsername(), r.getPassword()));
// And add request interceptor to have preemptive authentication
@@ -118,14 +113,14 @@ public class RequestExecutor {
httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, null);
httpClient.removeRequestInterceptorByClass(PreemptiveAuthInterceptor.class);
}
-
+
// Setup redirects
httpClient.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, r.getRedirects());
-
+
// Execute request
response = httpClient.execute(request);
entity = response.getEntity();
- if(entity != null) {
+ if (entity != null) {
// We fully read the content every time, not super efficient but
// how can we read it on demand while avoiding a (boring) cleanup()
// method on this class?
@@ -134,7 +129,7 @@ public class RequestExecutor {
}
return this;
}
-
+
protected void clear() {
request = null;
entity = null;
@@ -142,45 +137,50 @@ public class RequestExecutor {
content = null;
}
- /** Verify that response matches supplied status */
+ /**
+ * Verify that response matches supplied status
+ */
public RequestExecutor assertStatus(int expected) {
assertNotNull(this.toString(), response);
assertEquals(this + ": expecting status " + expected, expected, response.getStatusLine().getStatusCode());
return this;
}
-
- /** Verify that response matches supplied content type */
+
+ /**
+ * Verify that response matches supplied content type
+ */
public RequestExecutor assertContentType(String expected) {
assertNotNull(this.toString(), response);
- if(entity == null) {
+ if (entity == null) {
fail(this + ": no entity in response, cannot check content type");
}
-
+
// Remove whatever follows semicolon in content-type
String contentType = entity.getContentType().getValue();
- if(contentType != null) {
+ if (contentType != null) {
contentType = contentType.split(";")[0].trim();
}
-
+
// And check for match
assertEquals(this + ": expecting content type " + expected, expected, contentType);
return this;
}
- /** For each supplied regexp, fail unless content contains at
- * least one line that matches.
- * Regexps are automatically prefixed/suffixed with .* so as
- * to have match partial lines.
+ /**
+ * For each supplied regexp, fail unless content contains at
+ * least one line that matches.
+ * Regexps are automatically prefixed/suffixed with .* so as
+ * to have match partial lines.
*/
public RequestExecutor assertContentRegexp(String... regexp) {
assertNotNull(this.toString(), response);
nextPattern:
- for(String expr : regexp) {
+ for (String expr : regexp) {
final Pattern p = Pattern.compile(".*" + expr + ".*");
final LineIterator it = new LineIterator(new StringReader(content));
- while(it.hasNext()) {
- final String line = it.nextLine();
- if(p.matcher(line).matches()) {
+ while (it.hasNext()) {
+ final String line = it.nextLine();
+ if (p.matcher(line).matches()) {
continue nextPattern;
}
}
@@ -189,18 +189,20 @@ public class RequestExecutor {
return this;
}
- /** For each supplied string, fail unless content contains it */
- public RequestExecutor assertContentContains(String... expected) throws ParseException, IOException {
+ /**
+ * For each supplied string, fail unless content contains it
+ */
+ public RequestExecutor assertContentContains(String... expected) throws ParseException {
assertNotNull(this.toString(), response);
- for(String exp : expected) {
- if(!content.contains(exp)) {
+ for (String exp : expected) {
+ if (!content.contains(exp)) {
fail(this + ": content does not contain '" + exp + "', content=\n" + content);
}
}
return this;
}
-
- public void generateDocumentation(RequestDocumentor documentor, String...metadata) throws IOException {
+
+ public void generateDocumentation(RequestDocumentor documentor, String... metadata) throws IOException {
documentor.generateDocumentation(this, metadata);
}
Modified: incubator/stanbol/trunk/commons/testing/http/src/main/java/org/apache/stanbol/commons/testing/http/RetryLoop.java
URL: http://svn.apache.org/viewvc/incubator/stanbol/trunk/commons/testing/http/src/main/java/org/apache/stanbol/commons/testing/http/RetryLoop.java?rev=1078342&r1=1078341&r2=1078342&view=diff
==============================================================================
--- incubator/stanbol/trunk/commons/testing/http/src/main/java/org/apache/stanbol/commons/testing/http/RetryLoop.java (original)
+++ incubator/stanbol/trunk/commons/testing/http/src/main/java/org/apache/stanbol/commons/testing/http/RetryLoop.java Sat Mar 5 20:14:20 2011
@@ -18,62 +18,73 @@ package org.apache.stanbol.commons.testi
import static org.junit.Assert.fail;
-/** Convenience class for retrying tests
- * until timeout or success.
+/**
+ * Convenience class for retrying tests
+ * until timeout or success.
*/
public class RetryLoop {
-
+
private final long timeout;
-
- /** Interface for conditions to check, isTrue will be called
- * repeatedly until success or timeout */
- static public interface Condition {
- /** Used in failure messages to describe what was expected */
+
+ /**
+ * Interface for conditions to check, isTrue will be called
+ * repeatedly until success or timeout
+ */
+ public static interface Condition {
+
+ /**
+ * Used in failure messages to describe what was expected
+ */
String getDescription();
-
- /** If true we stop retrying. The RetryLoop retries on AssertionError,
- * so if tests fail in this method they are not reported as
- * failures but retried.
+
+ /**
+ * If true we stop retrying. The RetryLoop retries on AssertionError,
+ * so if tests fail in this method they are not reported as
+ * failures but retried.
*/
boolean isTrue() throws Exception;
}
-
- /** Retry Condition c until it returns true or timeout. See {@link Condition}
- * for isTrue semantics.
+
+ /**
+ * Retry Condition c until it returns true or timeout. See {@link Condition}
+ * for isTrue semantics.
*/
public RetryLoop(Condition c, int timeoutSeconds, int intervalBetweenTriesMsec) {
timeout = System.currentTimeMillis() + timeoutSeconds * 1000L;
- while(System.currentTimeMillis() < timeout) {
+ while (System.currentTimeMillis() < timeout) {
try {
- if(c.isTrue()) {
+ if (c.isTrue()) {
return;
}
- } catch(AssertionError ae) {
+ } catch (AssertionError ae) {
// Retry JUnit tests failing in the condition as well
reportException(ae);
- } catch(Exception e) {
+ } catch (Exception e) {
reportException(e);
}
-
+
try {
Thread.sleep(intervalBetweenTriesMsec);
- } catch(InterruptedException ignore) {
+ } catch (InterruptedException ignore) {
}
}
-
+
onTimeout();
- fail("RetryLoop failed, condition is false after " + timeoutSeconds + " seconds: "
- + c.getDescription());
+ fail("RetryLoop failed, condition is false after " + timeoutSeconds + " seconds: " + c.getDescription());
}
- /** Can be overridden to report Exceptions that happen in the retry loop */
+ /**
+ * Can be overridden to report Exceptions that happen in the retry loop
+ */
protected void reportException(Throwable t) {
}
-
- /** Called if the loop times out without success, just before failing */
+
+ /**
+ * Called if the loop times out without success, just before failing
+ */
protected void onTimeout() {
}
-
+
protected long getRemainingTimeSeconds() {
return Math.max(0L, (timeout - System.currentTimeMillis()) / 1000L);
}
Modified: incubator/stanbol/trunk/commons/testing/jarexec/src/main/java/org/apache/stanbol/commons/testing/jarexec/JarExecutor.java
URL: http://svn.apache.org/viewvc/incubator/stanbol/trunk/commons/testing/jarexec/src/main/java/org/apache/stanbol/commons/testing/jarexec/JarExecutor.java?rev=1078342&r1=1078341&r2=1078342&view=diff
==============================================================================
--- incubator/stanbol/trunk/commons/testing/jarexec/src/main/java/org/apache/stanbol/commons/testing/jarexec/JarExecutor.java (original)
+++ incubator/stanbol/trunk/commons/testing/jarexec/src/main/java/org/apache/stanbol/commons/testing/jarexec/JarExecutor.java Sat Mar 5 20:14:20 2011
@@ -32,15 +32,17 @@ import org.apache.commons.exec.util.Stri
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-/** Start a runnable jar by forking a JVM process,
- * and terminate the process when this VM exits.
+/**
+ * Start a runnable jar by forking a JVM process,
+ * and terminate the process when this VM exits.
*/
public class JarExecutor {
+
private static JarExecutor instance;
private final File jarToExecute;
private final String javaExecutable;
private final int serverPort;
-
+
private final Logger log = LoggerFactory.getLogger(getClass());
public static final int DEFAULT_PORT = 8765;
@@ -50,33 +52,37 @@ public class JarExecutor {
public static final String PROP_SERVER_PORT = PROP_PREFIX + "server.port";
public static final String PROP_JAR_FOLDER = PROP_PREFIX + "jar.folder";
public static final String PROP_JAR_NAME_REGEXP = PROP_PREFIX + "jar.name.regexp";
-
+
@SuppressWarnings("serial")
public static class ExecutorException extends Exception {
+
ExecutorException(String reason) {
super(reason);
}
+
ExecutorException(String reason, Throwable cause) {
super(reason, cause);
}
}
-
+
public int getServerPort() {
return serverPort;
}
public static JarExecutor getInstance(Properties config) throws ExecutorException {
- if(instance == null) {
+ if (instance == null) {
synchronized (JarExecutor.class) {
- if(instance == null) {
+ if (instance == null) {
instance = new JarExecutor(config);
}
}
}
return instance;
}
-
- /** Build a JarExecutor, locate the jar to run, etc */
+
+ /**
+ * Build a JarExecutor, locate the jar to run, etc
+ */
private JarExecutor(Properties config) throws ExecutorException {
final boolean isWindows = System.getProperty("os.name").toLowerCase().contains("windows");
@@ -84,33 +90,32 @@ public class JarExecutor {
serverPort = portStr == null ? DEFAULT_PORT : Integer.valueOf(portStr);
javaExecutable = isWindows ? "java.exe" : "java";
-
+
String jarFolderPath = config.getProperty(PROP_JAR_FOLDER);
jarFolderPath = jarFolderPath == null ? DEFAULT_JAR_FOLDER : jarFolderPath;
final File jarFolder = new File(jarFolderPath);
-
+
String jarNameRegexp = config.getProperty(PROP_JAR_NAME_REGEXP);
jarNameRegexp = jarNameRegexp == null ? DEFAULT_JAR_NAME_REGEXP : jarNameRegexp;
final Pattern jarPattern = Pattern.compile(jarNameRegexp);
// Find executable jar
- final String [] candidates = jarFolder.list();
- if(candidates == null) {
- throw new ExecutorException(
- "No files found in jar folder specified by "
+ final String[] candidates = jarFolder.list();
+ if (candidates == null) {
+ throw new ExecutorException("No files found in jar folder specified by "
+ PROP_JAR_FOLDER + " property: " + jarFolder.getAbsolutePath());
}
File f = null;
- if(candidates != null) {
- for(String filename : candidates) {
- if(jarPattern.matcher(filename).matches()) {
+ if (candidates != null) {
+ for (String filename : candidates) {
+ if (jarPattern.matcher(filename).matches()) {
f = new File(jarFolder, filename);
break;
}
}
}
- if(f == null) {
+ if (f == null) {
throw new ExecutorException("Executable jar matching '" + jarPattern
+ "' not found in " + jarFolder.getAbsolutePath()
+ ", candidates are " + Arrays.asList(candidates));
@@ -118,8 +123,9 @@ public class JarExecutor {
jarToExecute = f;
}
- /** Start the jar if not done yet, and setup runtime hook
- * to stop it.
+ /**
+ * Start the jar if not done yet, and setup runtime hook
+ * to stop it.
*/
public void start() throws Exception {
final ExecuteResultHandler h = new ExecuteResultHandler() {
Modified: incubator/stanbol/trunk/commons/testing/stanbol/src/main/java/org/apache/stanbol/commons/testing/stanbol/StanbolTestBase.java
URL: http://svn.apache.org/viewvc/incubator/stanbol/trunk/commons/testing/stanbol/src/main/java/org/apache/stanbol/commons/testing/stanbol/StanbolTestBase.java?rev=1078342&r1=1078341&r2=1078342&view=diff
==============================================================================
--- incubator/stanbol/trunk/commons/testing/stanbol/src/main/java/org/apache/stanbol/commons/testing/stanbol/StanbolTestBase.java (original)
+++ incubator/stanbol/trunk/commons/testing/stanbol/src/main/java/org/apache/stanbol/commons/testing/stanbol/StanbolTestBase.java Sat Mar 5 20:14:20 2011
@@ -34,33 +34,35 @@ import org.junit.BeforeClass;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-/** Base class for Stanbol integration tests - starts the runnable jar
- * to test if needed, and waits until server is ready before executing
- * the tests.
+/**
+ * Base class for Stanbol integration tests - starts the runnable jar
+ * to test if needed, and waits until server is ready before executing
+ * the tests.
*/
public class StanbolTestBase {
-
- private static final Logger log = LoggerFactory.getLogger(StanbolTestBase.class);
public static final String TEST_SERVER_URL_PROP = "test.server.url";
public static final String SERVER_READY_TIMEOUT_PROP = "server.ready.timeout.seconds";
public static final String SERVER_READY_PROP_PREFIX = "server.ready.path";
public static final String KEEP_JAR_RUNNING_PROP = "keepJarRunning";
+
protected static String serverBaseUrl;
- protected boolean serverReady = false;
+ private static final Logger log = LoggerFactory.getLogger(StanbolTestBase.class);
+
+ protected boolean serverReady = false;
protected RequestBuilder builder;
protected DefaultHttpClient httpClient = new DefaultHttpClient();
protected RequestExecutor executor = new RequestExecutor(httpClient);
-
+
@BeforeClass
- public synchronized static void startRunnableJar() throws Exception {
+ public static synchronized void startRunnableJar() throws Exception {
if (serverBaseUrl != null) {
// concurrent initialization by loading subclasses
return;
}
final String configuredUrl = System.getProperty(TEST_SERVER_URL_PROP);
- if(configuredUrl != null) {
+ if (configuredUrl != null) {
serverBaseUrl = configuredUrl;
log.info(TEST_SERVER_URL_PROP + " is set: not starting server jar (" + serverBaseUrl + ")");
} else {
@@ -68,19 +70,19 @@ public class StanbolTestBase {
j.start();
serverBaseUrl = "http://localhost:" + j.getServerPort();
log.info("Forked subprocess server listening to: " + serverBaseUrl);
-
+
// Optionally block here so that the runnable jar stays up - we can
// then run tests against it from another VM
if ("true".equals(System.getProperty(KEEP_JAR_RUNNING_PROP))) {
log.info(KEEP_JAR_RUNNING_PROP + " set to true - entering infinite loop"
- + " so that runnable jar stays up. Kill this process to exit.");
+ + " so that runnable jar stays up. Kill this process to exit.");
while (true) {
Thread.sleep(1000L);
}
}
}
}
-
+
@Before
public void waitForServerReady() throws Exception {
// initialize instance request builder and HTTP client
@@ -88,7 +90,7 @@ public class StanbolTestBase {
httpClient = new DefaultHttpClient();
executor = new RequestExecutor(httpClient);
- if(serverReady) {
+ if (serverReady) {
return;
}
@@ -102,59 +104,58 @@ public class StanbolTestBase {
final List<String> testPaths = new ArrayList<String>();
final TreeSet<Object> propertyNames = new TreeSet<Object>();
propertyNames.addAll(System.getProperties().keySet());
- for(Object o : propertyNames) {
+ for (Object o : propertyNames) {
final String key = (String) o;
- if(key.startsWith(SERVER_READY_PROP_PREFIX)) {
+ if (key.startsWith(SERVER_READY_PROP_PREFIX)) {
testPaths.add(System.getProperty(key));
}
}
-
+
// Consider the server ready if it responds to a GET on each of
// our configured request paths with a 200 result and content
// that matches the regexp supplied with the path
long sleepTime = 100;
readyLoop:
- while(!serverReady && System.currentTimeMillis() < endTime) {
+ while (!serverReady && System.currentTimeMillis() < endTime) {
// Wait a bit between checks, to let the server come up
Thread.sleep(sleepTime);
sleepTime = Math.min(5000L, sleepTime * 2);
-
+
// A test path is in the form path:substring or just path, in which case
// we don't check that the content contains the substring
- for(String p : testPaths) {
- final String [] s = p.split(":");
+ for (String p : testPaths) {
+ final String[] s = p.split(":");
final String path = s[0];
final String substring = (s.length > 0 ? s[1] : null);
final String url = serverBaseUrl + path;
final HttpGet get = new HttpGet(url);
- HttpResponse response = null;
HttpEntity entity = null;
try {
- response = httpClient.execute(get);
+ HttpResponse response = httpClient.execute(get);
entity = response.getEntity();
final int status = response.getStatusLine().getStatusCode();
- if(status != 200) {
+ if (status != 200) {
log.info("Got " + status + " at " + url + " - will retry");
continue readyLoop;
}
-
- if(substring != null) {
- if(entity == null) {
+
+ if (substring != null) {
+ if (entity == null) {
log.info("No entity returned for " + url + " - will retry");
continue readyLoop;
}
final String content = EntityUtils.toString(entity);
- if(!content.contains(substring)) {
- log.info("Returned content for " + url + " does not contain " + substring
- + " - will retry");
+ if (!content.contains(substring)) {
+ log.info("Returned content for " + url
+ + " does not contain " + substring + " - will retry");
continue readyLoop;
}
}
- } catch(HttpHostConnectException e) {
+ } catch (HttpHostConnectException e) {
log.info("Got HttpHostConnectException at " + url + " - will retry");
continue readyLoop;
} finally {
- if(entity != null) {
+ if (entity != null) {
entity.consumeContent();
}
}
@@ -163,7 +164,7 @@ public class StanbolTestBase {
log.info("Got expected content for all configured requests, server is ready");
}
- if(!serverReady) {
+ if (!serverReady) {
throw new Exception("Server not ready after " + timeoutSec + " seconds");
}
}