repo_name
stringlengths
7
104
file_path
stringlengths
13
198
context
stringlengths
67
7.15k
import_statement
stringlengths
16
4.43k
code
stringlengths
40
6.98k
prompt
stringlengths
227
8.27k
next_line
stringlengths
8
795
keenlabs/KeenClient-Java
query/src/main/java/io/keen/client/java/CachedDatasetRequest.java
// Path: query/src/main/java/io/keen/client/java/exceptions/KeenQueryClientException.java // public class KeenQueryClientException extends KeenException { // private static final long serialVersionUID = -8714276738565293346L; // // public KeenQueryClientException() { // super(); // } // // public KeenQueryClientException(Throwable cause) { // super(cause); // } // // public KeenQueryClientException(String message) { // super(message); // } // // public KeenQueryClientException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: core/src/main/java/io/keen/client/java/http/HttpMethods.java // public final class HttpMethods { // private HttpMethods() {} // // public final static String GET = "GET"; // public final static String POST = "POST"; // public final static String PUT = "PUT"; // public final static String DELETE = "DELETE"; // }
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import io.keen.client.java.exceptions.KeenQueryClientException; import io.keen.client.java.http.HttpMethods; import java.io.IOException; import java.net.URL; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import static java.util.Collections.emptyMap;
package io.keen.client.java; abstract class CachedDatasetRequest extends PersistentAnalysis { private CachedDatasetRequest(String httpMethod, boolean needsMasterKey, String datasetName) { super(httpMethod, needsMasterKey, datasetName, null); } static KeenQueryRequest definitionRequest(String datasetName) { return new CachedDatasetRequest(HttpMethods.GET, false, datasetName) { @Override
// Path: query/src/main/java/io/keen/client/java/exceptions/KeenQueryClientException.java // public class KeenQueryClientException extends KeenException { // private static final long serialVersionUID = -8714276738565293346L; // // public KeenQueryClientException() { // super(); // } // // public KeenQueryClientException(Throwable cause) { // super(cause); // } // // public KeenQueryClientException(String message) { // super(message); // } // // public KeenQueryClientException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: core/src/main/java/io/keen/client/java/http/HttpMethods.java // public final class HttpMethods { // private HttpMethods() {} // // public final static String GET = "GET"; // public final static String POST = "POST"; // public final static String PUT = "PUT"; // public final static String DELETE = "DELETE"; // } // Path: query/src/main/java/io/keen/client/java/CachedDatasetRequest.java import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import io.keen.client.java.exceptions.KeenQueryClientException; import io.keen.client.java.http.HttpMethods; import java.io.IOException; import java.net.URL; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import static java.util.Collections.emptyMap; package io.keen.client.java; abstract class CachedDatasetRequest extends PersistentAnalysis { private CachedDatasetRequest(String httpMethod, boolean needsMasterKey, String datasetName) { super(httpMethod, needsMasterKey, datasetName, null); } static KeenQueryRequest definitionRequest(String datasetName) { return new CachedDatasetRequest(HttpMethods.GET, false, datasetName) { @Override
URL getRequestURL(RequestUrlBuilder urlBuilder, String projectId) throws KeenQueryClientException {
keenlabs/KeenClient-Java
core/src/test/java/io/keen/client/java/KeenClientTest.java
// Path: core/src/main/java/io/keen/client/java/exceptions/NoWriteKeyException.java // public class NoWriteKeyException extends KeenException { // private static final long serialVersionUID = -8199471518510440670L; // // public NoWriteKeyException() { // super(); // } // // public NoWriteKeyException(Throwable cause) { // super(cause); // } // // public NoWriteKeyException(String message) { // super(message); // } // // public NoWriteKeyException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: core/src/main/java/io/keen/client/java/http/Request.java // public final class Request { // // ///// PROPERTIES ///// // // public final URL url; // public final String method; // public final String authorization; // public final OutputSource body; // public final Proxy proxy; // public final int connectTimeout; // public final int readTimeout; // // ///// PUBLIC CONSTRUCTORS ///// // // @Deprecated // public Request(URL url, String method, String authorization, OutputSource body) { // this(url, method, authorization, body, null, 30000, 30000); // } // // public Request(URL url, String method, String authorization, OutputSource body, Proxy proxy, int connectTimeout, int readTimeout) { // this.url = url; // this.method = method; // this.authorization = authorization; // this.body = body; // this.proxy = proxy; // this.connectTimeout = connectTimeout; // this.readTimeout = readTimeout; // } // // } // // Path: core/src/main/java/io/keen/client/java/http/Response.java // public final class Response { // // ///// PROPERTIES ///// // // public final int statusCode; // public final String body; // // ///// PUBLIC CONSTRUCTORS ///// // // public Response(int statusCode, String body) { // this.statusCode = statusCode; // this.body = body; // } // // ///// PUBLIC METHODS ///// // // public boolean isSuccess() { // return isSuccessCode(statusCode); // } // // ///// PRIVATE STATIC METHODS ///// // // /** // * Checks whether an HTTP status code indicates success. // * // * @param statusCode The HTTP status code. // * @return {@code true} if the status code indicates success (2xx), otherwise {@code false}. // */ // private static boolean isSuccessCode(int statusCode) { // return (statusCode / 100 == 2); // } // // }
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.mockito.ArgumentCaptor; import java.io.IOException; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import io.keen.client.java.exceptions.KeenException; import io.keen.client.java.exceptions.NoWriteKeyException; import io.keen.client.java.exceptions.ServerException; import io.keen.client.java.http.HttpHandler; import io.keen.client.java.http.Request; import io.keen.client.java.http.Response; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.endsWith; import static org.hamcrest.Matchers.startsWith; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when;
event.put("valid key", "valid value"); Map<String, Object> keenProperties = new HashMap<String, Object>(); keenProperties.put("keen key", "keen value"); Map<String, Object> result = client.validateAndBuildEvent(client.getDefaultProject(), "foo", event, keenProperties); @SuppressWarnings("unchecked") Map<String, Object> keenPropResult = (Map<String, Object>)result.get("keen"); assertNotNull(keenPropResult.get("timestamp")); assertNull(keenProperties.get("timestamp")); assertEquals(keenProperties.get("keen key"), "keen value"); assertEquals(keenPropResult.get("keen key"), "keen value"); assertEquals(keenProperties.get("keen key"), keenPropResult.get("keen key")); } @Test public void validEventWithNestedKeenProperty() throws Exception { Map<String, Object> event = TestUtils.getSimpleEvent(); Map<String, Object> nested = new HashMap<String, Object>(); nested.put("keen", "value"); event.put("nested", nested); client.validateAndBuildEvent(client.getDefaultProject(), "foo", event, null); } @Test public void testAddEventNoWriteKey() throws KeenException, IOException { client.setDefaultProject(new KeenProject("508339b0897a2c4282000000", null, "<read key>")); Map<String, Object> event = new HashMap<String, Object>(); event.put("test key", "test value"); try { client.addEvent("foo", event); fail("add event without write key should fail");
// Path: core/src/main/java/io/keen/client/java/exceptions/NoWriteKeyException.java // public class NoWriteKeyException extends KeenException { // private static final long serialVersionUID = -8199471518510440670L; // // public NoWriteKeyException() { // super(); // } // // public NoWriteKeyException(Throwable cause) { // super(cause); // } // // public NoWriteKeyException(String message) { // super(message); // } // // public NoWriteKeyException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: core/src/main/java/io/keen/client/java/http/Request.java // public final class Request { // // ///// PROPERTIES ///// // // public final URL url; // public final String method; // public final String authorization; // public final OutputSource body; // public final Proxy proxy; // public final int connectTimeout; // public final int readTimeout; // // ///// PUBLIC CONSTRUCTORS ///// // // @Deprecated // public Request(URL url, String method, String authorization, OutputSource body) { // this(url, method, authorization, body, null, 30000, 30000); // } // // public Request(URL url, String method, String authorization, OutputSource body, Proxy proxy, int connectTimeout, int readTimeout) { // this.url = url; // this.method = method; // this.authorization = authorization; // this.body = body; // this.proxy = proxy; // this.connectTimeout = connectTimeout; // this.readTimeout = readTimeout; // } // // } // // Path: core/src/main/java/io/keen/client/java/http/Response.java // public final class Response { // // ///// PROPERTIES ///// // // public final int statusCode; // public final String body; // // ///// PUBLIC CONSTRUCTORS ///// // // public Response(int statusCode, String body) { // this.statusCode = statusCode; // this.body = body; // } // // ///// PUBLIC METHODS ///// // // public boolean isSuccess() { // return isSuccessCode(statusCode); // } // // ///// PRIVATE STATIC METHODS ///// // // /** // * Checks whether an HTTP status code indicates success. // * // * @param statusCode The HTTP status code. // * @return {@code true} if the status code indicates success (2xx), otherwise {@code false}. // */ // private static boolean isSuccessCode(int statusCode) { // return (statusCode / 100 == 2); // } // // } // Path: core/src/test/java/io/keen/client/java/KeenClientTest.java import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.mockito.ArgumentCaptor; import java.io.IOException; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import io.keen.client.java.exceptions.KeenException; import io.keen.client.java.exceptions.NoWriteKeyException; import io.keen.client.java.exceptions.ServerException; import io.keen.client.java.http.HttpHandler; import io.keen.client.java.http.Request; import io.keen.client.java.http.Response; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.endsWith; import static org.hamcrest.Matchers.startsWith; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; event.put("valid key", "valid value"); Map<String, Object> keenProperties = new HashMap<String, Object>(); keenProperties.put("keen key", "keen value"); Map<String, Object> result = client.validateAndBuildEvent(client.getDefaultProject(), "foo", event, keenProperties); @SuppressWarnings("unchecked") Map<String, Object> keenPropResult = (Map<String, Object>)result.get("keen"); assertNotNull(keenPropResult.get("timestamp")); assertNull(keenProperties.get("timestamp")); assertEquals(keenProperties.get("keen key"), "keen value"); assertEquals(keenPropResult.get("keen key"), "keen value"); assertEquals(keenProperties.get("keen key"), keenPropResult.get("keen key")); } @Test public void validEventWithNestedKeenProperty() throws Exception { Map<String, Object> event = TestUtils.getSimpleEvent(); Map<String, Object> nested = new HashMap<String, Object>(); nested.put("keen", "value"); event.put("nested", nested); client.validateAndBuildEvent(client.getDefaultProject(), "foo", event, null); } @Test public void testAddEventNoWriteKey() throws KeenException, IOException { client.setDefaultProject(new KeenProject("508339b0897a2c4282000000", null, "<read key>")); Map<String, Object> event = new HashMap<String, Object>(); event.put("test key", "test value"); try { client.addEvent("foo", event); fail("add event without write key should fail");
} catch (NoWriteKeyException e) {
keenlabs/KeenClient-Java
core/src/test/java/io/keen/client/java/KeenClientTest.java
// Path: core/src/main/java/io/keen/client/java/exceptions/NoWriteKeyException.java // public class NoWriteKeyException extends KeenException { // private static final long serialVersionUID = -8199471518510440670L; // // public NoWriteKeyException() { // super(); // } // // public NoWriteKeyException(Throwable cause) { // super(cause); // } // // public NoWriteKeyException(String message) { // super(message); // } // // public NoWriteKeyException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: core/src/main/java/io/keen/client/java/http/Request.java // public final class Request { // // ///// PROPERTIES ///// // // public final URL url; // public final String method; // public final String authorization; // public final OutputSource body; // public final Proxy proxy; // public final int connectTimeout; // public final int readTimeout; // // ///// PUBLIC CONSTRUCTORS ///// // // @Deprecated // public Request(URL url, String method, String authorization, OutputSource body) { // this(url, method, authorization, body, null, 30000, 30000); // } // // public Request(URL url, String method, String authorization, OutputSource body, Proxy proxy, int connectTimeout, int readTimeout) { // this.url = url; // this.method = method; // this.authorization = authorization; // this.body = body; // this.proxy = proxy; // this.connectTimeout = connectTimeout; // this.readTimeout = readTimeout; // } // // } // // Path: core/src/main/java/io/keen/client/java/http/Response.java // public final class Response { // // ///// PROPERTIES ///// // // public final int statusCode; // public final String body; // // ///// PUBLIC CONSTRUCTORS ///// // // public Response(int statusCode, String body) { // this.statusCode = statusCode; // this.body = body; // } // // ///// PUBLIC METHODS ///// // // public boolean isSuccess() { // return isSuccessCode(statusCode); // } // // ///// PRIVATE STATIC METHODS ///// // // /** // * Checks whether an HTTP status code indicates success. // * // * @param statusCode The HTTP status code. // * @return {@code true} if the status code indicates success (2xx), otherwise {@code false}. // */ // private static boolean isSuccessCode(int statusCode) { // return (statusCode / 100 == 2); // } // // }
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.mockito.ArgumentCaptor; import java.io.IOException; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import io.keen.client.java.exceptions.KeenException; import io.keen.client.java.exceptions.NoWriteKeyException; import io.keen.client.java.exceptions.ServerException; import io.keen.client.java.http.HttpHandler; import io.keen.client.java.http.Request; import io.keen.client.java.http.Response; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.endsWith; import static org.hamcrest.Matchers.startsWith; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when;
assertEquals(keenProperties.get("keen key"), keenPropResult.get("keen key")); } @Test public void validEventWithNestedKeenProperty() throws Exception { Map<String, Object> event = TestUtils.getSimpleEvent(); Map<String, Object> nested = new HashMap<String, Object>(); nested.put("keen", "value"); event.put("nested", nested); client.validateAndBuildEvent(client.getDefaultProject(), "foo", event, null); } @Test public void testAddEventNoWriteKey() throws KeenException, IOException { client.setDefaultProject(new KeenProject("508339b0897a2c4282000000", null, "<read key>")); Map<String, Object> event = new HashMap<String, Object>(); event.put("test key", "test value"); try { client.addEvent("foo", event); fail("add event without write key should fail"); } catch (NoWriteKeyException e) { assertEquals("You can't send events to Keen if you haven't set a write key.", e.getLocalizedMessage()); } } @Test public void testAddEvent() throws Exception { setMockResponse(201, POST_EVENT_SUCCESS); client.addEvent(TEST_COLLECTION, TEST_EVENTS.get(0));
// Path: core/src/main/java/io/keen/client/java/exceptions/NoWriteKeyException.java // public class NoWriteKeyException extends KeenException { // private static final long serialVersionUID = -8199471518510440670L; // // public NoWriteKeyException() { // super(); // } // // public NoWriteKeyException(Throwable cause) { // super(cause); // } // // public NoWriteKeyException(String message) { // super(message); // } // // public NoWriteKeyException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: core/src/main/java/io/keen/client/java/http/Request.java // public final class Request { // // ///// PROPERTIES ///// // // public final URL url; // public final String method; // public final String authorization; // public final OutputSource body; // public final Proxy proxy; // public final int connectTimeout; // public final int readTimeout; // // ///// PUBLIC CONSTRUCTORS ///// // // @Deprecated // public Request(URL url, String method, String authorization, OutputSource body) { // this(url, method, authorization, body, null, 30000, 30000); // } // // public Request(URL url, String method, String authorization, OutputSource body, Proxy proxy, int connectTimeout, int readTimeout) { // this.url = url; // this.method = method; // this.authorization = authorization; // this.body = body; // this.proxy = proxy; // this.connectTimeout = connectTimeout; // this.readTimeout = readTimeout; // } // // } // // Path: core/src/main/java/io/keen/client/java/http/Response.java // public final class Response { // // ///// PROPERTIES ///// // // public final int statusCode; // public final String body; // // ///// PUBLIC CONSTRUCTORS ///// // // public Response(int statusCode, String body) { // this.statusCode = statusCode; // this.body = body; // } // // ///// PUBLIC METHODS ///// // // public boolean isSuccess() { // return isSuccessCode(statusCode); // } // // ///// PRIVATE STATIC METHODS ///// // // /** // * Checks whether an HTTP status code indicates success. // * // * @param statusCode The HTTP status code. // * @return {@code true} if the status code indicates success (2xx), otherwise {@code false}. // */ // private static boolean isSuccessCode(int statusCode) { // return (statusCode / 100 == 2); // } // // } // Path: core/src/test/java/io/keen/client/java/KeenClientTest.java import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.mockito.ArgumentCaptor; import java.io.IOException; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import io.keen.client.java.exceptions.KeenException; import io.keen.client.java.exceptions.NoWriteKeyException; import io.keen.client.java.exceptions.ServerException; import io.keen.client.java.http.HttpHandler; import io.keen.client.java.http.Request; import io.keen.client.java.http.Response; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.endsWith; import static org.hamcrest.Matchers.startsWith; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; assertEquals(keenProperties.get("keen key"), keenPropResult.get("keen key")); } @Test public void validEventWithNestedKeenProperty() throws Exception { Map<String, Object> event = TestUtils.getSimpleEvent(); Map<String, Object> nested = new HashMap<String, Object>(); nested.put("keen", "value"); event.put("nested", nested); client.validateAndBuildEvent(client.getDefaultProject(), "foo", event, null); } @Test public void testAddEventNoWriteKey() throws KeenException, IOException { client.setDefaultProject(new KeenProject("508339b0897a2c4282000000", null, "<read key>")); Map<String, Object> event = new HashMap<String, Object>(); event.put("test key", "test value"); try { client.addEvent("foo", event); fail("add event without write key should fail"); } catch (NoWriteKeyException e) { assertEquals("You can't send events to Keen if you haven't set a write key.", e.getLocalizedMessage()); } } @Test public void testAddEvent() throws Exception { setMockResponse(201, POST_EVENT_SUCCESS); client.addEvent(TEST_COLLECTION, TEST_EVENTS.get(0));
ArgumentCaptor<Request> capturedRequest = ArgumentCaptor.forClass(Request.class);
keenlabs/KeenClient-Java
core/src/test/java/io/keen/client/java/KeenClientTest.java
// Path: core/src/main/java/io/keen/client/java/exceptions/NoWriteKeyException.java // public class NoWriteKeyException extends KeenException { // private static final long serialVersionUID = -8199471518510440670L; // // public NoWriteKeyException() { // super(); // } // // public NoWriteKeyException(Throwable cause) { // super(cause); // } // // public NoWriteKeyException(String message) { // super(message); // } // // public NoWriteKeyException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: core/src/main/java/io/keen/client/java/http/Request.java // public final class Request { // // ///// PROPERTIES ///// // // public final URL url; // public final String method; // public final String authorization; // public final OutputSource body; // public final Proxy proxy; // public final int connectTimeout; // public final int readTimeout; // // ///// PUBLIC CONSTRUCTORS ///// // // @Deprecated // public Request(URL url, String method, String authorization, OutputSource body) { // this(url, method, authorization, body, null, 30000, 30000); // } // // public Request(URL url, String method, String authorization, OutputSource body, Proxy proxy, int connectTimeout, int readTimeout) { // this.url = url; // this.method = method; // this.authorization = authorization; // this.body = body; // this.proxy = proxy; // this.connectTimeout = connectTimeout; // this.readTimeout = readTimeout; // } // // } // // Path: core/src/main/java/io/keen/client/java/http/Response.java // public final class Response { // // ///// PROPERTIES ///// // // public final int statusCode; // public final String body; // // ///// PUBLIC CONSTRUCTORS ///// // // public Response(int statusCode, String body) { // this.statusCode = statusCode; // this.body = body; // } // // ///// PUBLIC METHODS ///// // // public boolean isSuccess() { // return isSuccessCode(statusCode); // } // // ///// PRIVATE STATIC METHODS ///// // // /** // * Checks whether an HTTP status code indicates success. // * // * @param statusCode The HTTP status code. // * @return {@code true} if the status code indicates success (2xx), otherwise {@code false}. // */ // private static boolean isSuccessCode(int statusCode) { // return (statusCode / 100 == 2); // } // // }
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.mockito.ArgumentCaptor; import java.io.IOException; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import io.keen.client.java.exceptions.KeenException; import io.keen.client.java.exceptions.NoWriteKeyException; import io.keen.client.java.exceptions.ServerException; import io.keen.client.java.http.HttpHandler; import io.keen.client.java.http.Request; import io.keen.client.java.http.Response; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.endsWith; import static org.hamcrest.Matchers.startsWith; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when;
client.setGlobalPropertiesEvaluator(evaluator); Map<String, Object> event = new HashMap<String, Object>(); event.put("event", "event"); Map<String, Object> eventKeenProperties = new HashMap<String, Object>(); eventKeenProperties.put("eventkeen", "event"); Map<String, Object> builtEvent = client.validateAndBuildEvent(client.getDefaultProject(), "apples", event, eventKeenProperties); assertEquals("static", builtEvent.get("staticglobal")); assertEquals("dynamic", builtEvent.get("dynamicglobal")); assertEquals("event", builtEvent.get("event")); Map builtKeenProperties = (Map) builtEvent.get("keen"); assertEquals("static", builtKeenProperties.get("statickeenglobal")); assertEquals("dynamic", builtKeenProperties.get("dynamickeenglobal")); assertEquals("event", builtKeenProperties.get("eventkeen")); } private void runValidateAndBuildEventTest(Map<String, Object> event, String eventCollection, String msg, String expectedMessage) { try { client.validateAndBuildEvent(client.getDefaultProject(), eventCollection, event, null); fail(msg); } catch (KeenException e) { assertEquals(expectedMessage, e.getLocalizedMessage()); } } private void setMockResponse(int statusCode, String body) throws IOException {
// Path: core/src/main/java/io/keen/client/java/exceptions/NoWriteKeyException.java // public class NoWriteKeyException extends KeenException { // private static final long serialVersionUID = -8199471518510440670L; // // public NoWriteKeyException() { // super(); // } // // public NoWriteKeyException(Throwable cause) { // super(cause); // } // // public NoWriteKeyException(String message) { // super(message); // } // // public NoWriteKeyException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: core/src/main/java/io/keen/client/java/http/Request.java // public final class Request { // // ///// PROPERTIES ///// // // public final URL url; // public final String method; // public final String authorization; // public final OutputSource body; // public final Proxy proxy; // public final int connectTimeout; // public final int readTimeout; // // ///// PUBLIC CONSTRUCTORS ///// // // @Deprecated // public Request(URL url, String method, String authorization, OutputSource body) { // this(url, method, authorization, body, null, 30000, 30000); // } // // public Request(URL url, String method, String authorization, OutputSource body, Proxy proxy, int connectTimeout, int readTimeout) { // this.url = url; // this.method = method; // this.authorization = authorization; // this.body = body; // this.proxy = proxy; // this.connectTimeout = connectTimeout; // this.readTimeout = readTimeout; // } // // } // // Path: core/src/main/java/io/keen/client/java/http/Response.java // public final class Response { // // ///// PROPERTIES ///// // // public final int statusCode; // public final String body; // // ///// PUBLIC CONSTRUCTORS ///// // // public Response(int statusCode, String body) { // this.statusCode = statusCode; // this.body = body; // } // // ///// PUBLIC METHODS ///// // // public boolean isSuccess() { // return isSuccessCode(statusCode); // } // // ///// PRIVATE STATIC METHODS ///// // // /** // * Checks whether an HTTP status code indicates success. // * // * @param statusCode The HTTP status code. // * @return {@code true} if the status code indicates success (2xx), otherwise {@code false}. // */ // private static boolean isSuccessCode(int statusCode) { // return (statusCode / 100 == 2); // } // // } // Path: core/src/test/java/io/keen/client/java/KeenClientTest.java import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.mockito.ArgumentCaptor; import java.io.IOException; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import io.keen.client.java.exceptions.KeenException; import io.keen.client.java.exceptions.NoWriteKeyException; import io.keen.client.java.exceptions.ServerException; import io.keen.client.java.http.HttpHandler; import io.keen.client.java.http.Request; import io.keen.client.java.http.Response; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.endsWith; import static org.hamcrest.Matchers.startsWith; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; client.setGlobalPropertiesEvaluator(evaluator); Map<String, Object> event = new HashMap<String, Object>(); event.put("event", "event"); Map<String, Object> eventKeenProperties = new HashMap<String, Object>(); eventKeenProperties.put("eventkeen", "event"); Map<String, Object> builtEvent = client.validateAndBuildEvent(client.getDefaultProject(), "apples", event, eventKeenProperties); assertEquals("static", builtEvent.get("staticglobal")); assertEquals("dynamic", builtEvent.get("dynamicglobal")); assertEquals("event", builtEvent.get("event")); Map builtKeenProperties = (Map) builtEvent.get("keen"); assertEquals("static", builtKeenProperties.get("statickeenglobal")); assertEquals("dynamic", builtKeenProperties.get("dynamickeenglobal")); assertEquals("event", builtKeenProperties.get("eventkeen")); } private void runValidateAndBuildEventTest(Map<String, Object> event, String eventCollection, String msg, String expectedMessage) { try { client.validateAndBuildEvent(client.getDefaultProject(), eventCollection, event, null); fail(msg); } catch (KeenException e) { assertEquals(expectedMessage, e.getLocalizedMessage()); } } private void setMockResponse(int statusCode, String body) throws IOException {
Response response = new Response(statusCode, body);
keenlabs/KeenClient-Java
query/src/main/java/io/keen/client/java/CachedDatasetsClient.java
// Path: query/src/main/java/io/keen/client/java/result/IntervalResultValue.java // public class IntervalResultValue { // private final AbsoluteTimeframe timeframe; // private final QueryResult result; // // public IntervalResultValue(AbsoluteTimeframe timeframe, QueryResult result) { // this.timeframe = timeframe; // this.result = result; // } // // public AbsoluteTimeframe getTimeframe() { // return timeframe; // } // // public QueryResult getResult() { // return result; // } // // @Override // public String toString() { // return ReflectionToStringBuilder.toString(this, ToStringStyle.SHORT_PREFIX_STYLE); // } // // @Override // public boolean equals(Object obj) { // return EqualsBuilder.reflectionEquals(this, obj); // } // // @Override // public int hashCode() { // return HashCodeBuilder.reflectionHashCode(this); // } // }
import io.keen.client.java.result.IntervalResultValue; import org.apache.commons.lang3.Validate; import java.io.IOException; import java.util.*;
package io.keen.client.java; class CachedDatasetsClient implements CachedDatasets { private KeenQueryClient keenQueryClient; CachedDatasetsClient(KeenQueryClient keenQueryClient) { this.keenQueryClient = keenQueryClient; } @Override public DatasetDefinition create(String datasetName, String displayName, DatasetQuery query, Collection<String> indexBy) throws IOException { Validate.notBlank(datasetName, "Dataset name cannot be blank"); Validate.notBlank(displayName, "Display name cannot be blank"); Validate.notNull(query, "Dataset query is required"); Validate.notEmpty(indexBy, "At least one index property is required"); KeenQueryRequest request = CachedDatasetRequest.creationRequest(datasetName, displayName, query, indexBy); return DatasetDefinition.fromMap(keenQueryClient.getMapResponse(request)); } @Override public DatasetDefinition getDefinition(String datasetName) throws IOException { Validate.notBlank(datasetName, "Dataset name cannot be blank"); KeenQueryRequest request = CachedDatasetRequest.definitionRequest(datasetName); return DatasetDefinition.fromMap(keenQueryClient.getMapResponse(request)); } @Override
// Path: query/src/main/java/io/keen/client/java/result/IntervalResultValue.java // public class IntervalResultValue { // private final AbsoluteTimeframe timeframe; // private final QueryResult result; // // public IntervalResultValue(AbsoluteTimeframe timeframe, QueryResult result) { // this.timeframe = timeframe; // this.result = result; // } // // public AbsoluteTimeframe getTimeframe() { // return timeframe; // } // // public QueryResult getResult() { // return result; // } // // @Override // public String toString() { // return ReflectionToStringBuilder.toString(this, ToStringStyle.SHORT_PREFIX_STYLE); // } // // @Override // public boolean equals(Object obj) { // return EqualsBuilder.reflectionEquals(this, obj); // } // // @Override // public int hashCode() { // return HashCodeBuilder.reflectionHashCode(this); // } // } // Path: query/src/main/java/io/keen/client/java/CachedDatasetsClient.java import io.keen.client.java.result.IntervalResultValue; import org.apache.commons.lang3.Validate; import java.io.IOException; import java.util.*; package io.keen.client.java; class CachedDatasetsClient implements CachedDatasets { private KeenQueryClient keenQueryClient; CachedDatasetsClient(KeenQueryClient keenQueryClient) { this.keenQueryClient = keenQueryClient; } @Override public DatasetDefinition create(String datasetName, String displayName, DatasetQuery query, Collection<String> indexBy) throws IOException { Validate.notBlank(datasetName, "Dataset name cannot be blank"); Validate.notBlank(displayName, "Display name cannot be blank"); Validate.notNull(query, "Dataset query is required"); Validate.notEmpty(indexBy, "At least one index property is required"); KeenQueryRequest request = CachedDatasetRequest.creationRequest(datasetName, displayName, query, indexBy); return DatasetDefinition.fromMap(keenQueryClient.getMapResponse(request)); } @Override public DatasetDefinition getDefinition(String datasetName) throws IOException { Validate.notBlank(datasetName, "Dataset name cannot be blank"); KeenQueryRequest request = CachedDatasetRequest.definitionRequest(datasetName); return DatasetDefinition.fromMap(keenQueryClient.getMapResponse(request)); } @Override
public List<IntervalResultValue> getResults(DatasetDefinition datasetDefinition, Map<String, ?> indexByValues, Timeframe timeframe) throws IOException {
keenlabs/KeenClient-Java
android/src/main/java/io/keen/client/android/AndroidJsonHandler.java
// Path: core/src/main/java/io/keen/client/java/KeenConstants.java // public final class KeenConstants { // private KeenConstants() {} // // static final String SERVER_ADDRESS = "https://api.keen.io"; // static final String API_VERSION = "3.0"; // // // Keen API constants // // static final int MAX_EVENT_DEPTH = 1000; // static final int DEFAULT_MAX_ATTEMPTS = 3; // static final String NAME_PARAM = "name"; // static final String SUCCESS_PARAM = "success"; // static final String ERROR_PARAM = "error"; // static final String DESCRIPTION_PARAM = "description"; // static final String INVALID_COLLECTION_NAME_ERROR = "InvalidCollectionNameError"; // static final String INVALID_PROPERTY_NAME_ERROR = "InvalidPropertyNameError"; // static final String INVALID_PROPERTY_VALUE_ERROR = "InvalidPropertyValueError"; // // // Exported constants // // public static final String KEEN_FAKE_JSON_ROOT = "io.keen.client.java.__fake_root"; // } // // Path: core/src/main/java/io/keen/client/java/KeenJsonHandler.java // public interface KeenJsonHandler { // // /** // * Reads JSON-formatted data from the provided {@link java.io.Reader} and constructs a // * {@link java.util.Map} representing the object described. The keys of the map should // * correspond to the names of the top-level members, and the values may primitives (Strings, // * Integers, Booleans, etc.), Maps, or Iterables. // * // * @param reader The {@link java.io.Reader} from which to read the JSON data. // * @return The object which was read, held in a {@code Map<String, Object>}. // * @throws IOException If there is an error reading from the input. // */ // Map<String, Object> readJson(Reader reader) throws IOException; // // /** // * Writes the given object (in the form of a {@code Map<String, Object>} to the specified // * {@link java.io.Writer}. // * // * @param writer The {@link java.io.Writer} to which the JSON data should be written. // * @param value The object to write. // * @throws IOException If there is an error writing to the output. // */ // void writeJson(Writer writer, Map<String, ?> value) throws IOException; // // }
import android.os.Build; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.json.JSONTokener; import java.io.IOException; import java.io.Reader; import java.io.StringWriter; import java.io.Writer; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import io.keen.client.java.KeenConstants; import io.keen.client.java.KeenJsonHandler;
package io.keen.client.android; /** * Implementation of the {@link io.keen.client.java.KeenJsonHandler} interface using the built-in * Android JSON library ({@link org.json.JSONObject}). * * @author Kevin Litwack ([email protected]), masojus * @since 2.0.0 */ public class AndroidJsonHandler implements KeenJsonHandler { ///// KeenJsonHandler METHODS ///// /** * {@inheritDoc} */ @Override public Map<String, Object> readJson(Reader reader) throws IOException { if (reader == null) { throw new IllegalArgumentException("Reader must not be null"); } String json = readerToString(reader); try { Object jsonObjOrArray = getJsonObjectManager().newTokener(json).nextValue(); // Issue #99 : Take a look at better dealing with root Map<> vs root List<> in the // response. Object rootNode = JsonHelper.fromJson(jsonObjOrArray); Map<String, Object> rootMap = null; if (null == rootNode) { throw new IllegalArgumentException("Empty reader or ill-formatted JSON " + "encountered."); } else if (rootNode instanceof Map) { rootMap = (Map)rootNode; } else if (rootNode instanceof List) { rootMap = new LinkedHashMap<String, Object>();
// Path: core/src/main/java/io/keen/client/java/KeenConstants.java // public final class KeenConstants { // private KeenConstants() {} // // static final String SERVER_ADDRESS = "https://api.keen.io"; // static final String API_VERSION = "3.0"; // // // Keen API constants // // static final int MAX_EVENT_DEPTH = 1000; // static final int DEFAULT_MAX_ATTEMPTS = 3; // static final String NAME_PARAM = "name"; // static final String SUCCESS_PARAM = "success"; // static final String ERROR_PARAM = "error"; // static final String DESCRIPTION_PARAM = "description"; // static final String INVALID_COLLECTION_NAME_ERROR = "InvalidCollectionNameError"; // static final String INVALID_PROPERTY_NAME_ERROR = "InvalidPropertyNameError"; // static final String INVALID_PROPERTY_VALUE_ERROR = "InvalidPropertyValueError"; // // // Exported constants // // public static final String KEEN_FAKE_JSON_ROOT = "io.keen.client.java.__fake_root"; // } // // Path: core/src/main/java/io/keen/client/java/KeenJsonHandler.java // public interface KeenJsonHandler { // // /** // * Reads JSON-formatted data from the provided {@link java.io.Reader} and constructs a // * {@link java.util.Map} representing the object described. The keys of the map should // * correspond to the names of the top-level members, and the values may primitives (Strings, // * Integers, Booleans, etc.), Maps, or Iterables. // * // * @param reader The {@link java.io.Reader} from which to read the JSON data. // * @return The object which was read, held in a {@code Map<String, Object>}. // * @throws IOException If there is an error reading from the input. // */ // Map<String, Object> readJson(Reader reader) throws IOException; // // /** // * Writes the given object (in the form of a {@code Map<String, Object>} to the specified // * {@link java.io.Writer}. // * // * @param writer The {@link java.io.Writer} to which the JSON data should be written. // * @param value The object to write. // * @throws IOException If there is an error writing to the output. // */ // void writeJson(Writer writer, Map<String, ?> value) throws IOException; // // } // Path: android/src/main/java/io/keen/client/android/AndroidJsonHandler.java import android.os.Build; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.json.JSONTokener; import java.io.IOException; import java.io.Reader; import java.io.StringWriter; import java.io.Writer; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import io.keen.client.java.KeenConstants; import io.keen.client.java.KeenJsonHandler; package io.keen.client.android; /** * Implementation of the {@link io.keen.client.java.KeenJsonHandler} interface using the built-in * Android JSON library ({@link org.json.JSONObject}). * * @author Kevin Litwack ([email protected]), masojus * @since 2.0.0 */ public class AndroidJsonHandler implements KeenJsonHandler { ///// KeenJsonHandler METHODS ///// /** * {@inheritDoc} */ @Override public Map<String, Object> readJson(Reader reader) throws IOException { if (reader == null) { throw new IllegalArgumentException("Reader must not be null"); } String json = readerToString(reader); try { Object jsonObjOrArray = getJsonObjectManager().newTokener(json).nextValue(); // Issue #99 : Take a look at better dealing with root Map<> vs root List<> in the // response. Object rootNode = JsonHelper.fromJson(jsonObjOrArray); Map<String, Object> rootMap = null; if (null == rootNode) { throw new IllegalArgumentException("Empty reader or ill-formatted JSON " + "encountered."); } else if (rootNode instanceof Map) { rootMap = (Map)rootNode; } else if (rootNode instanceof List) { rootMap = new LinkedHashMap<String, Object>();
rootMap.put(KeenConstants.KEEN_FAKE_JSON_ROOT, rootNode);
keenlabs/KeenClient-Java
core/src/main/java/io/keen/client/java/ScopedKeys.java
// Path: core/src/main/java/io/keen/client/java/exceptions/ScopedKeyException.java // public class ScopedKeyException extends KeenException { // private static final long serialVersionUID = -8250886829624436391L; // // public ScopedKeyException() { // super(); // } // // public ScopedKeyException(Throwable cause) { // super(cause); // } // // public ScopedKeyException(String message) { // super(message); // } // // public ScopedKeyException(String message, Throwable cause) { // super(message, cause); // } // }
import java.io.StringReader; import java.io.StringWriter; import java.security.AlgorithmParameters; import java.util.HashMap; import java.util.Map; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import io.keen.client.java.exceptions.ScopedKeyException;
package io.keen.client.java; /** * ScopedKeys is a utility class for dealing with Keen Scoped Keys. You'll probably only ever need the * encrypt method. However, for completeness, there's also a decrypt method. * <p> * Example usage: * </p> * <pre> * {@code * String apiKey = "YOUR_API_KEY_HERE"; * * //Filters to apply to the key * Map<String, Object> filter = new HashMap<String, Object>(); * List<Map<String, Object>> filters = new ArrayList<Map<String, Object>>(); * * //Create and add a filter * filter.put("property_name", "user_id"); * filter.put("operator", "eq"); * filter.put("property_value", "123"); * * filters.add(filter); * * // create the options we'll use * Map<String, Object> options = new HashMap<String, Object>(); * options.put("allowed_operations", Arrays.asList("write")); * options.put("filters", filters); * * // do the encryption * String scopedKey = ScopedKeys.encrypt(apiKey, options); * } * </pre> * * @author dkador * @since 1.0.3 */ public class ScopedKeys { private static final int BLOCK_SIZE = 32; // TODO: Review exceptions from this class. /** * Encrypts the given options with a Keen API Key and creates a Scoped Key. * * @param apiKey Your Keen API Key. * @param options The options you want to encrypt. * @return A Keen Scoped Key. * @throws ScopedKeyException an error occurred while attempting to encrypt a Scoped Key. */ public static String encrypt(String apiKey, Map<String, Object> options)
// Path: core/src/main/java/io/keen/client/java/exceptions/ScopedKeyException.java // public class ScopedKeyException extends KeenException { // private static final long serialVersionUID = -8250886829624436391L; // // public ScopedKeyException() { // super(); // } // // public ScopedKeyException(Throwable cause) { // super(cause); // } // // public ScopedKeyException(String message) { // super(message); // } // // public ScopedKeyException(String message, Throwable cause) { // super(message, cause); // } // } // Path: core/src/main/java/io/keen/client/java/ScopedKeys.java import java.io.StringReader; import java.io.StringWriter; import java.security.AlgorithmParameters; import java.util.HashMap; import java.util.Map; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import io.keen.client.java.exceptions.ScopedKeyException; package io.keen.client.java; /** * ScopedKeys is a utility class for dealing with Keen Scoped Keys. You'll probably only ever need the * encrypt method. However, for completeness, there's also a decrypt method. * <p> * Example usage: * </p> * <pre> * {@code * String apiKey = "YOUR_API_KEY_HERE"; * * //Filters to apply to the key * Map<String, Object> filter = new HashMap<String, Object>(); * List<Map<String, Object>> filters = new ArrayList<Map<String, Object>>(); * * //Create and add a filter * filter.put("property_name", "user_id"); * filter.put("operator", "eq"); * filter.put("property_value", "123"); * * filters.add(filter); * * // create the options we'll use * Map<String, Object> options = new HashMap<String, Object>(); * options.put("allowed_operations", Arrays.asList("write")); * options.put("filters", filters); * * // do the encryption * String scopedKey = ScopedKeys.encrypt(apiKey, options); * } * </pre> * * @author dkador * @since 1.0.3 */ public class ScopedKeys { private static final int BLOCK_SIZE = 32; // TODO: Review exceptions from this class. /** * Encrypts the given options with a Keen API Key and creates a Scoped Key. * * @param apiKey Your Keen API Key. * @param options The options you want to encrypt. * @return A Keen Scoped Key. * @throws ScopedKeyException an error occurred while attempting to encrypt a Scoped Key. */ public static String encrypt(String apiKey, Map<String, Object> options)
throws ScopedKeyException {
keenlabs/KeenClient-Java
query/src/main/java/io/keen/client/java/SavedQueryRequest.java
// Path: query/src/main/java/io/keen/client/java/exceptions/KeenQueryClientException.java // public class KeenQueryClientException extends KeenException { // private static final long serialVersionUID = -8714276738565293346L; // // public KeenQueryClientException() { // super(); // } // // public KeenQueryClientException(Throwable cause) { // super(cause); // } // // public KeenQueryClientException(String message) { // super(message); // } // // public KeenQueryClientException(String message, Throwable cause) { // super(message, cause); // } // }
import java.net.URL; import java.util.HashMap; import java.util.Map; import io.keen.client.java.exceptions.KeenQueryClientException;
package io.keen.client.java; /** * A PersistentAnalysis specifically for Saved/Cached Query requests. A lot of the CRUD * functionality can be performed with this class, but subclasses can customize behavior more. * * @author masojus */ class SavedQueryRequest extends PersistentAnalysis { SavedQueryRequest(String httpMethod, boolean needsMasterKey, String queryName) { this(httpMethod, needsMasterKey, queryName, null); } SavedQueryRequest(String httpMethod, boolean needsMasterKey, String queryName, String displayName) { super(httpMethod, needsMasterKey, queryName, displayName); } @Override URL getRequestURL(RequestUrlBuilder urlBuilder,
// Path: query/src/main/java/io/keen/client/java/exceptions/KeenQueryClientException.java // public class KeenQueryClientException extends KeenException { // private static final long serialVersionUID = -8714276738565293346L; // // public KeenQueryClientException() { // super(); // } // // public KeenQueryClientException(Throwable cause) { // super(cause); // } // // public KeenQueryClientException(String message) { // super(message); // } // // public KeenQueryClientException(String message, Throwable cause) { // super(message, cause); // } // } // Path: query/src/main/java/io/keen/client/java/SavedQueryRequest.java import java.net.URL; import java.util.HashMap; import java.util.Map; import io.keen.client.java.exceptions.KeenQueryClientException; package io.keen.client.java; /** * A PersistentAnalysis specifically for Saved/Cached Query requests. A lot of the CRUD * functionality can be performed with this class, but subclasses can customize behavior more. * * @author masojus */ class SavedQueryRequest extends PersistentAnalysis { SavedQueryRequest(String httpMethod, boolean needsMasterKey, String queryName) { this(httpMethod, needsMasterKey, queryName, null); } SavedQueryRequest(String httpMethod, boolean needsMasterKey, String queryName, String displayName) { super(httpMethod, needsMasterKey, queryName, displayName); } @Override URL getRequestURL(RequestUrlBuilder urlBuilder,
String projectId) throws KeenQueryClientException {
keenlabs/KeenClient-Java
query/src/main/java/io/keen/client/java/Query.java
// Path: query/src/main/java/io/keen/client/java/exceptions/KeenQueryClientException.java // public class KeenQueryClientException extends KeenException { // private static final long serialVersionUID = -8714276738565293346L; // // public KeenQueryClientException() { // super(); // } // // public KeenQueryClientException(Throwable cause) { // super(cause); // } // // public KeenQueryClientException(String message) { // super(message); // } // // public KeenQueryClientException(String message, Throwable cause) { // super(message, cause); // } // }
import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import io.keen.client.java.exceptions.KeenQueryClientException;
} return true; } /** * Constructs a Keen Query using a Builder. * * @param builder The builder from which to retrieve this client's interfaces and settings. */ protected Query(Builder builder) { this.eventCollection = builder.eventCollection; this.targetProperty = builder.targetProperty; this.interval = builder.interval; this.timezone = builder.timezone; this.groupBy = builder.groupBy; this.maxAge = builder.maxAge; this.percentile = builder.percentile; this.queryType = builder.queryType; this.timeframe = builder.timeframe; if (null != builder.filters && !builder.filters.isEmpty()) { this.filters = new RequestParameterCollection<Filter>(builder.filters); } else { this.filters = null; } } @Override URL getRequestURL(RequestUrlBuilder urlBuilder,
// Path: query/src/main/java/io/keen/client/java/exceptions/KeenQueryClientException.java // public class KeenQueryClientException extends KeenException { // private static final long serialVersionUID = -8714276738565293346L; // // public KeenQueryClientException() { // super(); // } // // public KeenQueryClientException(Throwable cause) { // super(cause); // } // // public KeenQueryClientException(String message) { // super(message); // } // // public KeenQueryClientException(String message, Throwable cause) { // super(message, cause); // } // } // Path: query/src/main/java/io/keen/client/java/Query.java import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import io.keen.client.java.exceptions.KeenQueryClientException; } return true; } /** * Constructs a Keen Query using a Builder. * * @param builder The builder from which to retrieve this client's interfaces and settings. */ protected Query(Builder builder) { this.eventCollection = builder.eventCollection; this.targetProperty = builder.targetProperty; this.interval = builder.interval; this.timezone = builder.timezone; this.groupBy = builder.groupBy; this.maxAge = builder.maxAge; this.percentile = builder.percentile; this.queryType = builder.queryType; this.timeframe = builder.timeframe; if (null != builder.filters && !builder.filters.isEmpty()) { this.filters = new RequestParameterCollection<Filter>(builder.filters); } else { this.filters = null; } } @Override URL getRequestURL(RequestUrlBuilder urlBuilder,
String projectId) throws KeenQueryClientException {
keenlabs/KeenClient-Java
query/src/test/java/io/keen/client/java/KeenQueryTestBase.java
// Path: core/src/main/java/io/keen/client/java/http/Request.java // public final class Request { // // ///// PROPERTIES ///// // // public final URL url; // public final String method; // public final String authorization; // public final OutputSource body; // public final Proxy proxy; // public final int connectTimeout; // public final int readTimeout; // // ///// PUBLIC CONSTRUCTORS ///// // // @Deprecated // public Request(URL url, String method, String authorization, OutputSource body) { // this(url, method, authorization, body, null, 30000, 30000); // } // // public Request(URL url, String method, String authorization, OutputSource body, Proxy proxy, int connectTimeout, int readTimeout) { // this.url = url; // this.method = method; // this.authorization = authorization; // this.body = body; // this.proxy = proxy; // this.connectTimeout = connectTimeout; // this.readTimeout = readTimeout; // } // // } // // Path: core/src/main/java/io/keen/client/java/http/Response.java // public final class Response { // // ///// PROPERTIES ///// // // public final int statusCode; // public final String body; // // ///// PUBLIC CONSTRUCTORS ///// // // public Response(int statusCode, String body) { // this.statusCode = statusCode; // this.body = body; // } // // ///// PUBLIC METHODS ///// // // public boolean isSuccess() { // return isSuccessCode(statusCode); // } // // ///// PRIVATE STATIC METHODS ///// // // /** // * Checks whether an HTTP status code indicates success. // * // * @param statusCode The HTTP status code. // * @return {@code true} if the status code indicates success (2xx), otherwise {@code false}. // */ // private static boolean isSuccessCode(int statusCode) { // return (statusCode / 100 == 2); // } // // }
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import io.keen.client.java.http.HttpHandler; import io.keen.client.java.http.Request; import io.keen.client.java.http.Response; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.MockitoAnnotations; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.List; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when;
} @AfterClass public static void tearDownClass() { KeenLogging.disableLogging(); TEST_PROJECT = null; } @Before public void setup() throws IOException { MockitoAnnotations.initMocks(this); // Set up a mock HTTP handler. mockHttpHandler = mock(HttpHandler.class); setMockResponse(500, "Unexpected HTTP request"); // build the client queryClient = new KeenQueryClient.Builder(TEST_PROJECT) .withJsonHandler(new TestJsonHandler()) .withHttpHandler(mockHttpHandler) .build(); } @After public void cleanUp() { queryClient = null; numExecuteCalls = 0; } @Captor
// Path: core/src/main/java/io/keen/client/java/http/Request.java // public final class Request { // // ///// PROPERTIES ///// // // public final URL url; // public final String method; // public final String authorization; // public final OutputSource body; // public final Proxy proxy; // public final int connectTimeout; // public final int readTimeout; // // ///// PUBLIC CONSTRUCTORS ///// // // @Deprecated // public Request(URL url, String method, String authorization, OutputSource body) { // this(url, method, authorization, body, null, 30000, 30000); // } // // public Request(URL url, String method, String authorization, OutputSource body, Proxy proxy, int connectTimeout, int readTimeout) { // this.url = url; // this.method = method; // this.authorization = authorization; // this.body = body; // this.proxy = proxy; // this.connectTimeout = connectTimeout; // this.readTimeout = readTimeout; // } // // } // // Path: core/src/main/java/io/keen/client/java/http/Response.java // public final class Response { // // ///// PROPERTIES ///// // // public final int statusCode; // public final String body; // // ///// PUBLIC CONSTRUCTORS ///// // // public Response(int statusCode, String body) { // this.statusCode = statusCode; // this.body = body; // } // // ///// PUBLIC METHODS ///// // // public boolean isSuccess() { // return isSuccessCode(statusCode); // } // // ///// PRIVATE STATIC METHODS ///// // // /** // * Checks whether an HTTP status code indicates success. // * // * @param statusCode The HTTP status code. // * @return {@code true} if the status code indicates success (2xx), otherwise {@code false}. // */ // private static boolean isSuccessCode(int statusCode) { // return (statusCode / 100 == 2); // } // // } // Path: query/src/test/java/io/keen/client/java/KeenQueryTestBase.java import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import io.keen.client.java.http.HttpHandler; import io.keen.client.java.http.Request; import io.keen.client.java.http.Response; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.MockitoAnnotations; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.List; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; } @AfterClass public static void tearDownClass() { KeenLogging.disableLogging(); TEST_PROJECT = null; } @Before public void setup() throws IOException { MockitoAnnotations.initMocks(this); // Set up a mock HTTP handler. mockHttpHandler = mock(HttpHandler.class); setMockResponse(500, "Unexpected HTTP request"); // build the client queryClient = new KeenQueryClient.Builder(TEST_PROJECT) .withJsonHandler(new TestJsonHandler()) .withHttpHandler(mockHttpHandler) .build(); } @After public void cleanUp() { queryClient = null; numExecuteCalls = 0; } @Captor
private ArgumentCaptor<Request> requestArgumentCaptor;
keenlabs/KeenClient-Java
query/src/test/java/io/keen/client/java/KeenQueryTestBase.java
// Path: core/src/main/java/io/keen/client/java/http/Request.java // public final class Request { // // ///// PROPERTIES ///// // // public final URL url; // public final String method; // public final String authorization; // public final OutputSource body; // public final Proxy proxy; // public final int connectTimeout; // public final int readTimeout; // // ///// PUBLIC CONSTRUCTORS ///// // // @Deprecated // public Request(URL url, String method, String authorization, OutputSource body) { // this(url, method, authorization, body, null, 30000, 30000); // } // // public Request(URL url, String method, String authorization, OutputSource body, Proxy proxy, int connectTimeout, int readTimeout) { // this.url = url; // this.method = method; // this.authorization = authorization; // this.body = body; // this.proxy = proxy; // this.connectTimeout = connectTimeout; // this.readTimeout = readTimeout; // } // // } // // Path: core/src/main/java/io/keen/client/java/http/Response.java // public final class Response { // // ///// PROPERTIES ///// // // public final int statusCode; // public final String body; // // ///// PUBLIC CONSTRUCTORS ///// // // public Response(int statusCode, String body) { // this.statusCode = statusCode; // this.body = body; // } // // ///// PUBLIC METHODS ///// // // public boolean isSuccess() { // return isSuccessCode(statusCode); // } // // ///// PRIVATE STATIC METHODS ///// // // /** // * Checks whether an HTTP status code indicates success. // * // * @param statusCode The HTTP status code. // * @return {@code true} if the status code indicates success (2xx), otherwise {@code false}. // */ // private static boolean isSuccessCode(int statusCode) { // return (statusCode / 100 == 2); // } // // }
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import io.keen.client.java.http.HttpHandler; import io.keen.client.java.http.Request; import io.keen.client.java.http.Response; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.MockitoAnnotations; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.List; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when;
KeenLogging.disableLogging(); TEST_PROJECT = null; } @Before public void setup() throws IOException { MockitoAnnotations.initMocks(this); // Set up a mock HTTP handler. mockHttpHandler = mock(HttpHandler.class); setMockResponse(500, "Unexpected HTTP request"); // build the client queryClient = new KeenQueryClient.Builder(TEST_PROJECT) .withJsonHandler(new TestJsonHandler()) .withHttpHandler(mockHttpHandler) .build(); } @After public void cleanUp() { queryClient = null; numExecuteCalls = 0; } @Captor private ArgumentCaptor<Request> requestArgumentCaptor; private int numExecuteCalls = 0; void setMockResponse(int statusCode, String body) throws IOException {
// Path: core/src/main/java/io/keen/client/java/http/Request.java // public final class Request { // // ///// PROPERTIES ///// // // public final URL url; // public final String method; // public final String authorization; // public final OutputSource body; // public final Proxy proxy; // public final int connectTimeout; // public final int readTimeout; // // ///// PUBLIC CONSTRUCTORS ///// // // @Deprecated // public Request(URL url, String method, String authorization, OutputSource body) { // this(url, method, authorization, body, null, 30000, 30000); // } // // public Request(URL url, String method, String authorization, OutputSource body, Proxy proxy, int connectTimeout, int readTimeout) { // this.url = url; // this.method = method; // this.authorization = authorization; // this.body = body; // this.proxy = proxy; // this.connectTimeout = connectTimeout; // this.readTimeout = readTimeout; // } // // } // // Path: core/src/main/java/io/keen/client/java/http/Response.java // public final class Response { // // ///// PROPERTIES ///// // // public final int statusCode; // public final String body; // // ///// PUBLIC CONSTRUCTORS ///// // // public Response(int statusCode, String body) { // this.statusCode = statusCode; // this.body = body; // } // // ///// PUBLIC METHODS ///// // // public boolean isSuccess() { // return isSuccessCode(statusCode); // } // // ///// PRIVATE STATIC METHODS ///// // // /** // * Checks whether an HTTP status code indicates success. // * // * @param statusCode The HTTP status code. // * @return {@code true} if the status code indicates success (2xx), otherwise {@code false}. // */ // private static boolean isSuccessCode(int statusCode) { // return (statusCode / 100 == 2); // } // // } // Path: query/src/test/java/io/keen/client/java/KeenQueryTestBase.java import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import io.keen.client.java.http.HttpHandler; import io.keen.client.java.http.Request; import io.keen.client.java.http.Response; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.MockitoAnnotations; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.List; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; KeenLogging.disableLogging(); TEST_PROJECT = null; } @Before public void setup() throws IOException { MockitoAnnotations.initMocks(this); // Set up a mock HTTP handler. mockHttpHandler = mock(HttpHandler.class); setMockResponse(500, "Unexpected HTTP request"); // build the client queryClient = new KeenQueryClient.Builder(TEST_PROJECT) .withJsonHandler(new TestJsonHandler()) .withHttpHandler(mockHttpHandler) .build(); } @After public void cleanUp() { queryClient = null; numExecuteCalls = 0; } @Captor private ArgumentCaptor<Request> requestArgumentCaptor; private int numExecuteCalls = 0; void setMockResponse(int statusCode, String body) throws IOException {
Response response = new Response(statusCode, body);
keenlabs/KeenClient-Java
core/src/main/java/io/keen/client/java/http/UrlConnectionHttpHandler.java
// Path: core/src/main/java/io/keen/client/java/KeenVersion.java // public class KeenVersion { // // private static final String SDK_VERSION = "5.6.0"; // // private KeenVersion() { // } // // public static String getSdkVersion() { // return SDK_VERSION; // } // // }
import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import io.keen.client.java.KeenUtils; import io.keen.client.java.KeenVersion;
package io.keen.client.java.http; /** * This class provides a default implementation of {@link HttpHandler} using * {@link java.net.HttpURLConnection}. To use a different HttpURLConnection implementation simply * override the {@link UrlConnectionHttpHandler#execute(Request)}} method. * * @author Kevin Litwack ([email protected]) * @since 2.0.0 */ public class UrlConnectionHttpHandler implements HttpHandler { /** * Sends an HTTP request. * * @param request The {@link Request} to send. * @return A {@link Response} object describing the response from the server. * @throws IOException If there was an error during the connection. */ @Override public Response execute(Request request) throws IOException { HttpURLConnection connection = openConnection(request); sendRequest(connection, request); return readResponse(connection); } ///// PROTECTED METHODS ///// /** * Opens a connection based on the URL in the given request. * * Subclasses can override this method to use a different implementation of * {@link HttpURLConnection}. * * @param request The {@link Request}. * @return A new {@link HttpURLConnection}. * @throws IOException If there is an error opening the connection. */ protected HttpURLConnection openConnection(Request request) throws IOException { HttpURLConnection result; if (request.proxy != null) { result = (HttpURLConnection) request.url.openConnection(request.proxy); } else { result = (HttpURLConnection) request.url.openConnection(); } result.setConnectTimeout(request.connectTimeout); result.setReadTimeout(request.readTimeout); return result; } /** * Sends a request over a given connection. * * @param connection The connection over which to send the request. * @param request The request to send. * @throws IOException If there is an error sending the request. */ protected void sendRequest(HttpURLConnection connection, Request request) throws IOException { // Set up the request. connection.setRequestMethod(request.method); connection.setRequestProperty("Accept", "application/json"); connection.setRequestProperty("Authorization", request.authorization); // If a different HttpHandler is used, we won't get this header. We would need to refactor // to a delegation pattern to give the client code's HttpHandler a chance to process the // Request first, then attach our custom headers, which would likely be a breaking change.
// Path: core/src/main/java/io/keen/client/java/KeenVersion.java // public class KeenVersion { // // private static final String SDK_VERSION = "5.6.0"; // // private KeenVersion() { // } // // public static String getSdkVersion() { // return SDK_VERSION; // } // // } // Path: core/src/main/java/io/keen/client/java/http/UrlConnectionHttpHandler.java import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import io.keen.client.java.KeenUtils; import io.keen.client.java.KeenVersion; package io.keen.client.java.http; /** * This class provides a default implementation of {@link HttpHandler} using * {@link java.net.HttpURLConnection}. To use a different HttpURLConnection implementation simply * override the {@link UrlConnectionHttpHandler#execute(Request)}} method. * * @author Kevin Litwack ([email protected]) * @since 2.0.0 */ public class UrlConnectionHttpHandler implements HttpHandler { /** * Sends an HTTP request. * * @param request The {@link Request} to send. * @return A {@link Response} object describing the response from the server. * @throws IOException If there was an error during the connection. */ @Override public Response execute(Request request) throws IOException { HttpURLConnection connection = openConnection(request); sendRequest(connection, request); return readResponse(connection); } ///// PROTECTED METHODS ///// /** * Opens a connection based on the URL in the given request. * * Subclasses can override this method to use a different implementation of * {@link HttpURLConnection}. * * @param request The {@link Request}. * @return A new {@link HttpURLConnection}. * @throws IOException If there is an error opening the connection. */ protected HttpURLConnection openConnection(Request request) throws IOException { HttpURLConnection result; if (request.proxy != null) { result = (HttpURLConnection) request.url.openConnection(request.proxy); } else { result = (HttpURLConnection) request.url.openConnection(); } result.setConnectTimeout(request.connectTimeout); result.setReadTimeout(request.readTimeout); return result; } /** * Sends a request over a given connection. * * @param connection The connection over which to send the request. * @param request The request to send. * @throws IOException If there is an error sending the request. */ protected void sendRequest(HttpURLConnection connection, Request request) throws IOException { // Set up the request. connection.setRequestMethod(request.method); connection.setRequestProperty("Accept", "application/json"); connection.setRequestProperty("Authorization", request.authorization); // If a different HttpHandler is used, we won't get this header. We would need to refactor // to a delegation pattern to give the client code's HttpHandler a chance to process the // Request first, then attach our custom headers, which would likely be a breaking change.
connection.setRequestProperty("Keen-Sdk", "java-" + KeenVersion.getSdkVersion());
keenlabs/KeenClient-Java
query/src/main/java/io/keen/client/java/MultiAnalysis.java
// Path: query/src/main/java/io/keen/client/java/exceptions/KeenQueryClientException.java // public class KeenQueryClientException extends KeenException { // private static final long serialVersionUID = -8714276738565293346L; // // public KeenQueryClientException() { // super(); // } // // public KeenQueryClientException(Throwable cause) { // super(cause); // } // // public KeenQueryClientException(String message) { // super(message); // } // // public KeenQueryClientException(String message, Throwable cause) { // super(message, cause); // } // }
import java.net.URL; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import io.keen.client.java.exceptions.KeenQueryClientException;
package io.keen.client.java; /** * Represents a Multi-Analysis. This type of analysis targets an event collection and specifies * a set of sub-analyses described in the * <a href="https://keen.io/docs/api/#multi-analysis">API Docs</a>. * * @author masojus */ public class MultiAnalysis extends CollectionAnalysis { // required private final Collection<SubAnalysis> analyses; protected MultiAnalysis(Builder builder) { super(builder); this.analyses = builder.subAnalyses; } @Override URL getRequestURL(RequestUrlBuilder urlBuilder, String projectId)
// Path: query/src/main/java/io/keen/client/java/exceptions/KeenQueryClientException.java // public class KeenQueryClientException extends KeenException { // private static final long serialVersionUID = -8714276738565293346L; // // public KeenQueryClientException() { // super(); // } // // public KeenQueryClientException(Throwable cause) { // super(cause); // } // // public KeenQueryClientException(String message) { // super(message); // } // // public KeenQueryClientException(String message, Throwable cause) { // super(message, cause); // } // } // Path: query/src/main/java/io/keen/client/java/MultiAnalysis.java import java.net.URL; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import io.keen.client.java.exceptions.KeenQueryClientException; package io.keen.client.java; /** * Represents a Multi-Analysis. This type of analysis targets an event collection and specifies * a set of sub-analyses described in the * <a href="https://keen.io/docs/api/#multi-analysis">API Docs</a>. * * @author masojus */ public class MultiAnalysis extends CollectionAnalysis { // required private final Collection<SubAnalysis> analyses; protected MultiAnalysis(Builder builder) { super(builder); this.analyses = builder.subAnalyses; } @Override URL getRequestURL(RequestUrlBuilder urlBuilder, String projectId)
throws KeenQueryClientException {
keenlabs/KeenClient-Java
core/src/test/java/io/keen/client/java/ScopedKeysTest.java
// Path: core/src/main/java/io/keen/client/java/exceptions/ScopedKeyException.java // public class ScopedKeyException extends KeenException { // private static final long serialVersionUID = -8250886829624436391L; // // public ScopedKeyException() { // super(); // } // // public ScopedKeyException(Throwable cause) { // super(cause); // } // // public ScopedKeyException(String message) { // super(message); // } // // public ScopedKeyException(String message, Throwable cause) { // super(message, cause); // } // }
import org.junit.BeforeClass; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import io.keen.client.java.exceptions.ScopedKeyException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue;
package io.keen.client.java; public class ScopedKeysTest { @BeforeClass public static void classSetUp() { KeenLogging.enableLogging(); KeenClient.initialize(new TestKeenClientBuilder().build()); } @Test
// Path: core/src/main/java/io/keen/client/java/exceptions/ScopedKeyException.java // public class ScopedKeyException extends KeenException { // private static final long serialVersionUID = -8250886829624436391L; // // public ScopedKeyException() { // super(); // } // // public ScopedKeyException(Throwable cause) { // super(cause); // } // // public ScopedKeyException(String message) { // super(message); // } // // public ScopedKeyException(String message, Throwable cause) { // super(message, cause); // } // } // Path: core/src/test/java/io/keen/client/java/ScopedKeysTest.java import org.junit.BeforeClass; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import io.keen.client.java.exceptions.ScopedKeyException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; package io.keen.client.java; public class ScopedKeysTest { @BeforeClass public static void classSetUp() { KeenLogging.enableLogging(); KeenClient.initialize(new TestKeenClientBuilder().build()); } @Test
public void testEncryptionAndDecryption() throws ScopedKeyException {
keenlabs/KeenClient-Java
query/src/main/java/io/keen/client/java/SavedQueriesImpl.java
// Path: core/src/main/java/io/keen/client/java/http/HttpMethods.java // public final class HttpMethods { // private HttpMethods() {} // // public final static String GET = "GET"; // public final static String POST = "POST"; // public final static String PUT = "PUT"; // public final static String DELETE = "DELETE"; // } // // Path: query/src/main/java/io/keen/client/java/result/QueryResult.java // public abstract class QueryResult { // /** // * @return {@code false} // */ // public boolean isDouble() { // return false; // } // // /** // * @return {@code false} // */ // public boolean isLong() { // return false; // } // // /** // * @return {@code false} // */ // public boolean isString() { // return false; // } // // /** // * @return {@code false} // */ // public boolean isListResult() { // return false; // } // // /** // * @return {@code false} // */ // public boolean isIntervalResult() { // return false; // } // // /** // * @return {@code false} // */ // public boolean isGroupResult() { return false; } // // /** // * @return doubleValue, which is IllegalStateException in abstract class. // */ // public double doubleValue() { // throw new IllegalStateException(); // } // // /** // * @return longValue, which is IllegalStateException in abstract class. // */ // public long longValue() { // throw new IllegalStateException(); // } // // /** // * @return stringValue, which is IllegalStateException in abstract class. // */ // public String stringValue() { // throw new IllegalStateException(); // } // // /** // * @return list results, which is IllegalStateException in abstract class. // */ // public List<QueryResult> getListResults() { // throw new IllegalStateException(); // } // // /** // * @return map of AbsoluteTimeframe to QueryResult's, which is IllegalStateException in // * abstract class. // */ // public List<IntervalResultValue> getIntervalResults() { throw new IllegalStateException(); } // // /** // * @return map of Group to QueryResult's, which is IllegalStateException in abstract class. // */ // public Map<Group, QueryResult> getGroupResults() { throw new IllegalStateException(); } // // @Override // public String toString() { // return ReflectionToStringBuilder.toString(this, ToStringStyle.SHORT_PREFIX_STYLE); // } // // @Override // public boolean equals(Object obj) { // return EqualsBuilder.reflectionEquals(this, obj); // } // // @Override // public int hashCode() { // return HashCodeBuilder.reflectionHashCode(this); // } // }
import java.io.IOException; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import io.keen.client.java.exceptions.ServerException; import io.keen.client.java.http.HttpMethods; import io.keen.client.java.result.QueryResult;
public Map<String, Object> createCachedQuery(String queryName, KeenQueryRequest query, int refreshRate) throws IOException { PersistentAnalysis newCachedQueryRequest = new SavedQueryPut(queryName, null /* displayName */, query, refreshRate, null /* miscProperties */); return queryClient.getMapResponse(newCachedQueryRequest); } @Override public Map<String, Object> createCachedQuery(String queryName, KeenQueryRequest query, String displayName, int refreshRate) throws IOException { PersistentAnalysis newCachedQueryRequest = new SavedQueryPut(queryName, displayName, query, refreshRate, null /* miscProperties */); return queryClient.getMapResponse(newCachedQueryRequest); } @Override public Map<String, Object> getDefinition(String queryName) throws IOException {
// Path: core/src/main/java/io/keen/client/java/http/HttpMethods.java // public final class HttpMethods { // private HttpMethods() {} // // public final static String GET = "GET"; // public final static String POST = "POST"; // public final static String PUT = "PUT"; // public final static String DELETE = "DELETE"; // } // // Path: query/src/main/java/io/keen/client/java/result/QueryResult.java // public abstract class QueryResult { // /** // * @return {@code false} // */ // public boolean isDouble() { // return false; // } // // /** // * @return {@code false} // */ // public boolean isLong() { // return false; // } // // /** // * @return {@code false} // */ // public boolean isString() { // return false; // } // // /** // * @return {@code false} // */ // public boolean isListResult() { // return false; // } // // /** // * @return {@code false} // */ // public boolean isIntervalResult() { // return false; // } // // /** // * @return {@code false} // */ // public boolean isGroupResult() { return false; } // // /** // * @return doubleValue, which is IllegalStateException in abstract class. // */ // public double doubleValue() { // throw new IllegalStateException(); // } // // /** // * @return longValue, which is IllegalStateException in abstract class. // */ // public long longValue() { // throw new IllegalStateException(); // } // // /** // * @return stringValue, which is IllegalStateException in abstract class. // */ // public String stringValue() { // throw new IllegalStateException(); // } // // /** // * @return list results, which is IllegalStateException in abstract class. // */ // public List<QueryResult> getListResults() { // throw new IllegalStateException(); // } // // /** // * @return map of AbsoluteTimeframe to QueryResult's, which is IllegalStateException in // * abstract class. // */ // public List<IntervalResultValue> getIntervalResults() { throw new IllegalStateException(); } // // /** // * @return map of Group to QueryResult's, which is IllegalStateException in abstract class. // */ // public Map<Group, QueryResult> getGroupResults() { throw new IllegalStateException(); } // // @Override // public String toString() { // return ReflectionToStringBuilder.toString(this, ToStringStyle.SHORT_PREFIX_STYLE); // } // // @Override // public boolean equals(Object obj) { // return EqualsBuilder.reflectionEquals(this, obj); // } // // @Override // public int hashCode() { // return HashCodeBuilder.reflectionHashCode(this); // } // } // Path: query/src/main/java/io/keen/client/java/SavedQueriesImpl.java import java.io.IOException; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import io.keen.client.java.exceptions.ServerException; import io.keen.client.java.http.HttpMethods; import io.keen.client.java.result.QueryResult; public Map<String, Object> createCachedQuery(String queryName, KeenQueryRequest query, int refreshRate) throws IOException { PersistentAnalysis newCachedQueryRequest = new SavedQueryPut(queryName, null /* displayName */, query, refreshRate, null /* miscProperties */); return queryClient.getMapResponse(newCachedQueryRequest); } @Override public Map<String, Object> createCachedQuery(String queryName, KeenQueryRequest query, String displayName, int refreshRate) throws IOException { PersistentAnalysis newCachedQueryRequest = new SavedQueryPut(queryName, displayName, query, refreshRate, null /* miscProperties */); return queryClient.getMapResponse(newCachedQueryRequest); } @Override public Map<String, Object> getDefinition(String queryName) throws IOException {
PersistentAnalysis getDefRequest = new SavedQueryRequest(HttpMethods.GET,
keenlabs/KeenClient-Java
query/src/main/java/io/keen/client/java/SavedQueriesImpl.java
// Path: core/src/main/java/io/keen/client/java/http/HttpMethods.java // public final class HttpMethods { // private HttpMethods() {} // // public final static String GET = "GET"; // public final static String POST = "POST"; // public final static String PUT = "PUT"; // public final static String DELETE = "DELETE"; // } // // Path: query/src/main/java/io/keen/client/java/result/QueryResult.java // public abstract class QueryResult { // /** // * @return {@code false} // */ // public boolean isDouble() { // return false; // } // // /** // * @return {@code false} // */ // public boolean isLong() { // return false; // } // // /** // * @return {@code false} // */ // public boolean isString() { // return false; // } // // /** // * @return {@code false} // */ // public boolean isListResult() { // return false; // } // // /** // * @return {@code false} // */ // public boolean isIntervalResult() { // return false; // } // // /** // * @return {@code false} // */ // public boolean isGroupResult() { return false; } // // /** // * @return doubleValue, which is IllegalStateException in abstract class. // */ // public double doubleValue() { // throw new IllegalStateException(); // } // // /** // * @return longValue, which is IllegalStateException in abstract class. // */ // public long longValue() { // throw new IllegalStateException(); // } // // /** // * @return stringValue, which is IllegalStateException in abstract class. // */ // public String stringValue() { // throw new IllegalStateException(); // } // // /** // * @return list results, which is IllegalStateException in abstract class. // */ // public List<QueryResult> getListResults() { // throw new IllegalStateException(); // } // // /** // * @return map of AbsoluteTimeframe to QueryResult's, which is IllegalStateException in // * abstract class. // */ // public List<IntervalResultValue> getIntervalResults() { throw new IllegalStateException(); } // // /** // * @return map of Group to QueryResult's, which is IllegalStateException in abstract class. // */ // public Map<Group, QueryResult> getGroupResults() { throw new IllegalStateException(); } // // @Override // public String toString() { // return ReflectionToStringBuilder.toString(this, ToStringStyle.SHORT_PREFIX_STYLE); // } // // @Override // public boolean equals(Object obj) { // return EqualsBuilder.reflectionEquals(this, obj); // } // // @Override // public int hashCode() { // return HashCodeBuilder.reflectionHashCode(this); // } // }
import java.io.IOException; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import io.keen.client.java.exceptions.ServerException; import io.keen.client.java.http.HttpMethods; import io.keen.client.java.result.QueryResult;
// When retrieving a single query definition, we expect a single JSON Object and just // hand it back instead of wrapping in QueryResult. return queryClient.getMapResponse(getDefRequest); } @Override public List<Map<String, Object>> getAllDefinitions() throws IOException { PersistentAnalysis getAllDefsRequest = new SavedQueryRequest(HttpMethods.GET, true /* needsMasterKey */, null /* queryName */); List<Object> response = queryClient.getListResponse(getAllDefsRequest); // We expect a structure such that each entry in the list was a JSON Object representing a // query definition, and no entry should be a JSON Value. for (Object defObj : response) { if (!(defObj instanceof Map)) { // Issue #101 : Are we using the appropriate exception type in the Saved/cached // Query code, or should we add an exception type? throw new ServerException("Expected list of definitions to be JSON Array of JSON " + "Objects, but encountered this: " + defObj.toString()); } } @SuppressWarnings("unchecked") List<Map<String, Object>> responseMaps = (List)response; return responseMaps; } @Override
// Path: core/src/main/java/io/keen/client/java/http/HttpMethods.java // public final class HttpMethods { // private HttpMethods() {} // // public final static String GET = "GET"; // public final static String POST = "POST"; // public final static String PUT = "PUT"; // public final static String DELETE = "DELETE"; // } // // Path: query/src/main/java/io/keen/client/java/result/QueryResult.java // public abstract class QueryResult { // /** // * @return {@code false} // */ // public boolean isDouble() { // return false; // } // // /** // * @return {@code false} // */ // public boolean isLong() { // return false; // } // // /** // * @return {@code false} // */ // public boolean isString() { // return false; // } // // /** // * @return {@code false} // */ // public boolean isListResult() { // return false; // } // // /** // * @return {@code false} // */ // public boolean isIntervalResult() { // return false; // } // // /** // * @return {@code false} // */ // public boolean isGroupResult() { return false; } // // /** // * @return doubleValue, which is IllegalStateException in abstract class. // */ // public double doubleValue() { // throw new IllegalStateException(); // } // // /** // * @return longValue, which is IllegalStateException in abstract class. // */ // public long longValue() { // throw new IllegalStateException(); // } // // /** // * @return stringValue, which is IllegalStateException in abstract class. // */ // public String stringValue() { // throw new IllegalStateException(); // } // // /** // * @return list results, which is IllegalStateException in abstract class. // */ // public List<QueryResult> getListResults() { // throw new IllegalStateException(); // } // // /** // * @return map of AbsoluteTimeframe to QueryResult's, which is IllegalStateException in // * abstract class. // */ // public List<IntervalResultValue> getIntervalResults() { throw new IllegalStateException(); } // // /** // * @return map of Group to QueryResult's, which is IllegalStateException in abstract class. // */ // public Map<Group, QueryResult> getGroupResults() { throw new IllegalStateException(); } // // @Override // public String toString() { // return ReflectionToStringBuilder.toString(this, ToStringStyle.SHORT_PREFIX_STYLE); // } // // @Override // public boolean equals(Object obj) { // return EqualsBuilder.reflectionEquals(this, obj); // } // // @Override // public int hashCode() { // return HashCodeBuilder.reflectionHashCode(this); // } // } // Path: query/src/main/java/io/keen/client/java/SavedQueriesImpl.java import java.io.IOException; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import io.keen.client.java.exceptions.ServerException; import io.keen.client.java.http.HttpMethods; import io.keen.client.java.result.QueryResult; // When retrieving a single query definition, we expect a single JSON Object and just // hand it back instead of wrapping in QueryResult. return queryClient.getMapResponse(getDefRequest); } @Override public List<Map<String, Object>> getAllDefinitions() throws IOException { PersistentAnalysis getAllDefsRequest = new SavedQueryRequest(HttpMethods.GET, true /* needsMasterKey */, null /* queryName */); List<Object> response = queryClient.getListResponse(getAllDefsRequest); // We expect a structure such that each entry in the list was a JSON Object representing a // query definition, and no entry should be a JSON Value. for (Object defObj : response) { if (!(defObj instanceof Map)) { // Issue #101 : Are we using the appropriate exception type in the Saved/cached // Query code, or should we add an exception type? throw new ServerException("Expected list of definitions to be JSON Array of JSON " + "Objects, but encountered this: " + defObj.toString()); } } @SuppressWarnings("unchecked") List<Map<String, Object>> responseMaps = (List)response; return responseMaps; } @Override
public QueryResult getResult(String queryName) throws IOException {
keenlabs/KeenClient-Java
query/src/main/java/io/keen/client/java/SingleAnalysis.java
// Path: query/src/main/java/io/keen/client/java/exceptions/KeenQueryClientException.java // public class KeenQueryClientException extends KeenException { // private static final long serialVersionUID = -8714276738565293346L; // // public KeenQueryClientException() { // super(); // } // // public KeenQueryClientException(Throwable cause) { // super(cause); // } // // public KeenQueryClientException(String message) { // super(message); // } // // public KeenQueryClientException(String message, Throwable cause) { // super(message, cause); // } // }
import java.net.URL; import java.util.Map; import io.keen.client.java.exceptions.KeenQueryClientException;
package io.keen.client.java; /** * This will replace Query, delegating most functionality to the CollectionAnalysis base class, * and adding the additional fields useful for some of the single analysis types, like the target * property and percentile. * * @author masojus */ public class SingleAnalysis extends CollectionAnalysis { // required private final QueryType queryType; // sometimes optional private final String targetPropertyName; // required by the Percentile query private final Percentile percentile; protected SingleAnalysis(Builder builder) { super(builder); this.queryType = builder.queryType; this.targetPropertyName = builder.targetPropertyName; this.percentile = builder.percentile; } @Override URL getRequestURL(RequestUrlBuilder urlBuilder, String projectId)
// Path: query/src/main/java/io/keen/client/java/exceptions/KeenQueryClientException.java // public class KeenQueryClientException extends KeenException { // private static final long serialVersionUID = -8714276738565293346L; // // public KeenQueryClientException() { // super(); // } // // public KeenQueryClientException(Throwable cause) { // super(cause); // } // // public KeenQueryClientException(String message) { // super(message); // } // // public KeenQueryClientException(String message, Throwable cause) { // super(message, cause); // } // } // Path: query/src/main/java/io/keen/client/java/SingleAnalysis.java import java.net.URL; import java.util.Map; import io.keen.client.java.exceptions.KeenQueryClientException; package io.keen.client.java; /** * This will replace Query, delegating most functionality to the CollectionAnalysis base class, * and adding the additional fields useful for some of the single analysis types, like the target * property and percentile. * * @author masojus */ public class SingleAnalysis extends CollectionAnalysis { // required private final QueryType queryType; // sometimes optional private final String targetPropertyName; // required by the Percentile query private final Percentile percentile; protected SingleAnalysis(Builder builder) { super(builder); this.queryType = builder.queryType; this.targetPropertyName = builder.targetPropertyName; this.percentile = builder.percentile; } @Override URL getRequestURL(RequestUrlBuilder urlBuilder, String projectId)
throws KeenQueryClientException {
arnaudroger/orm-benchmark
src/main/java/org/sfm/benchmark/db/sql2o/Sql2OBenchmark.java
// Path: src/main/java/org/sfm/beans/SmallBenchmarkObject.java // @Entity // @Table(name="test_small_benchmark_object") // public class SmallBenchmarkObject { // // @Id // @RowMapperField(columnName="ID") // private long id; // // @RowMapperField(columnName="YEAR_STARTED") // private int yearStarted; // @RowMapperField(columnName = "NAME") // private String name; // @RowMapperField(columnName="EMAIL") // private String email; // // @Column(name="ID") // public long getId() { // return id; // } // public void setId(long id) { // this.id = id; // } // @Column(name="NAME") // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } // @Column(name="EMAIL") // public String getEmail() { // return email; // } // public void setEmail(String email) { // this.email = email; // } // // @Column(name="YEAR_STARTED") // public int getYearStarted() { // return yearStarted; // } // public void setYearStarted(int yearStarted) { // this.yearStarted = yearStarted; // } // @Override // public String toString() { // return "SmallBenchmarkObject [id=" + id + ", yearStarted=" // + yearStarted + ", name=" + name + ", email=" + email + "]"; // } // // // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/ConnectionParam.java // @State(Scope.Benchmark) // public class ConnectionParam { // // @Param(value="MOCK") // public DbTarget db; // // public DataSource dataSource; // // @Setup // public void init() throws SQLException, NamingException { // dataSource = ConnectionHelper.getDataSource(db); // // if (db != DbTarget.MOCK) { // Connection conn = dataSource.getConnection(); // try { // ConnectionHelper.createTableAndInsertData(conn); // } finally { // conn.close(); // } // } // } // // public Connection getConnection() throws SQLException { // return dataSource.getConnection(); // } // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/DbTarget.java // public enum DbTarget { // MOCK { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.MYSQL; // } // }, HSQLDB { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.HSQLDB; // } // }, MYSQL { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.MYSQL; // } // }; // // public abstract SQLDialect getSqlDialect(); // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/LimitParam.java // @State(Scope.Benchmark) // public class LimitParam { // @Param(value={"1", "10", "100", "1000", "10000", "100000", "1000000"}) // public int limit; // }
import java.sql.SQLException; import java.util.List; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.infra.Blackhole; import org.sfm.beans.SmallBenchmarkObject; import org.sfm.benchmark.db.jmh.ConnectionParam; import org.sfm.benchmark.db.jmh.DbTarget; import org.sfm.benchmark.db.jmh.LimitParam; import org.sfm.sql2o.SfmResultSetHandlerFactory; import org.sfm.sql2o.SfmResultSetHandlerFactoryBuilder; import org.sql2o.ResultSetHandlerFactory; import org.sql2o.Sql2o;
package org.sfm.benchmark.db.sql2o; @State(Scope.Benchmark) public class Sql2OBenchmark {
// Path: src/main/java/org/sfm/beans/SmallBenchmarkObject.java // @Entity // @Table(name="test_small_benchmark_object") // public class SmallBenchmarkObject { // // @Id // @RowMapperField(columnName="ID") // private long id; // // @RowMapperField(columnName="YEAR_STARTED") // private int yearStarted; // @RowMapperField(columnName = "NAME") // private String name; // @RowMapperField(columnName="EMAIL") // private String email; // // @Column(name="ID") // public long getId() { // return id; // } // public void setId(long id) { // this.id = id; // } // @Column(name="NAME") // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } // @Column(name="EMAIL") // public String getEmail() { // return email; // } // public void setEmail(String email) { // this.email = email; // } // // @Column(name="YEAR_STARTED") // public int getYearStarted() { // return yearStarted; // } // public void setYearStarted(int yearStarted) { // this.yearStarted = yearStarted; // } // @Override // public String toString() { // return "SmallBenchmarkObject [id=" + id + ", yearStarted=" // + yearStarted + ", name=" + name + ", email=" + email + "]"; // } // // // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/ConnectionParam.java // @State(Scope.Benchmark) // public class ConnectionParam { // // @Param(value="MOCK") // public DbTarget db; // // public DataSource dataSource; // // @Setup // public void init() throws SQLException, NamingException { // dataSource = ConnectionHelper.getDataSource(db); // // if (db != DbTarget.MOCK) { // Connection conn = dataSource.getConnection(); // try { // ConnectionHelper.createTableAndInsertData(conn); // } finally { // conn.close(); // } // } // } // // public Connection getConnection() throws SQLException { // return dataSource.getConnection(); // } // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/DbTarget.java // public enum DbTarget { // MOCK { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.MYSQL; // } // }, HSQLDB { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.HSQLDB; // } // }, MYSQL { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.MYSQL; // } // }; // // public abstract SQLDialect getSqlDialect(); // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/LimitParam.java // @State(Scope.Benchmark) // public class LimitParam { // @Param(value={"1", "10", "100", "1000", "10000", "100000", "1000000"}) // public int limit; // } // Path: src/main/java/org/sfm/benchmark/db/sql2o/Sql2OBenchmark.java import java.sql.SQLException; import java.util.List; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.infra.Blackhole; import org.sfm.beans.SmallBenchmarkObject; import org.sfm.benchmark.db.jmh.ConnectionParam; import org.sfm.benchmark.db.jmh.DbTarget; import org.sfm.benchmark.db.jmh.LimitParam; import org.sfm.sql2o.SfmResultSetHandlerFactory; import org.sfm.sql2o.SfmResultSetHandlerFactoryBuilder; import org.sql2o.ResultSetHandlerFactory; import org.sql2o.Sql2o; package org.sfm.benchmark.db.sql2o; @State(Scope.Benchmark) public class Sql2OBenchmark {
private final ResultSetHandlerFactory<SmallBenchmarkObject> factory;
arnaudroger/orm-benchmark
src/main/java/org/sfm/benchmark/db/sql2o/Sql2OBenchmark.java
// Path: src/main/java/org/sfm/beans/SmallBenchmarkObject.java // @Entity // @Table(name="test_small_benchmark_object") // public class SmallBenchmarkObject { // // @Id // @RowMapperField(columnName="ID") // private long id; // // @RowMapperField(columnName="YEAR_STARTED") // private int yearStarted; // @RowMapperField(columnName = "NAME") // private String name; // @RowMapperField(columnName="EMAIL") // private String email; // // @Column(name="ID") // public long getId() { // return id; // } // public void setId(long id) { // this.id = id; // } // @Column(name="NAME") // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } // @Column(name="EMAIL") // public String getEmail() { // return email; // } // public void setEmail(String email) { // this.email = email; // } // // @Column(name="YEAR_STARTED") // public int getYearStarted() { // return yearStarted; // } // public void setYearStarted(int yearStarted) { // this.yearStarted = yearStarted; // } // @Override // public String toString() { // return "SmallBenchmarkObject [id=" + id + ", yearStarted=" // + yearStarted + ", name=" + name + ", email=" + email + "]"; // } // // // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/ConnectionParam.java // @State(Scope.Benchmark) // public class ConnectionParam { // // @Param(value="MOCK") // public DbTarget db; // // public DataSource dataSource; // // @Setup // public void init() throws SQLException, NamingException { // dataSource = ConnectionHelper.getDataSource(db); // // if (db != DbTarget.MOCK) { // Connection conn = dataSource.getConnection(); // try { // ConnectionHelper.createTableAndInsertData(conn); // } finally { // conn.close(); // } // } // } // // public Connection getConnection() throws SQLException { // return dataSource.getConnection(); // } // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/DbTarget.java // public enum DbTarget { // MOCK { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.MYSQL; // } // }, HSQLDB { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.HSQLDB; // } // }, MYSQL { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.MYSQL; // } // }; // // public abstract SQLDialect getSqlDialect(); // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/LimitParam.java // @State(Scope.Benchmark) // public class LimitParam { // @Param(value={"1", "10", "100", "1000", "10000", "100000", "1000000"}) // public int limit; // }
import java.sql.SQLException; import java.util.List; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.infra.Blackhole; import org.sfm.beans.SmallBenchmarkObject; import org.sfm.benchmark.db.jmh.ConnectionParam; import org.sfm.benchmark.db.jmh.DbTarget; import org.sfm.benchmark.db.jmh.LimitParam; import org.sfm.sql2o.SfmResultSetHandlerFactory; import org.sfm.sql2o.SfmResultSetHandlerFactoryBuilder; import org.sql2o.ResultSetHandlerFactory; import org.sql2o.Sql2o;
package org.sfm.benchmark.db.sql2o; @State(Scope.Benchmark) public class Sql2OBenchmark { private final ResultSetHandlerFactory<SmallBenchmarkObject> factory; private Sql2o sql2o; @Param(value="MOCK")
// Path: src/main/java/org/sfm/beans/SmallBenchmarkObject.java // @Entity // @Table(name="test_small_benchmark_object") // public class SmallBenchmarkObject { // // @Id // @RowMapperField(columnName="ID") // private long id; // // @RowMapperField(columnName="YEAR_STARTED") // private int yearStarted; // @RowMapperField(columnName = "NAME") // private String name; // @RowMapperField(columnName="EMAIL") // private String email; // // @Column(name="ID") // public long getId() { // return id; // } // public void setId(long id) { // this.id = id; // } // @Column(name="NAME") // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } // @Column(name="EMAIL") // public String getEmail() { // return email; // } // public void setEmail(String email) { // this.email = email; // } // // @Column(name="YEAR_STARTED") // public int getYearStarted() { // return yearStarted; // } // public void setYearStarted(int yearStarted) { // this.yearStarted = yearStarted; // } // @Override // public String toString() { // return "SmallBenchmarkObject [id=" + id + ", yearStarted=" // + yearStarted + ", name=" + name + ", email=" + email + "]"; // } // // // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/ConnectionParam.java // @State(Scope.Benchmark) // public class ConnectionParam { // // @Param(value="MOCK") // public DbTarget db; // // public DataSource dataSource; // // @Setup // public void init() throws SQLException, NamingException { // dataSource = ConnectionHelper.getDataSource(db); // // if (db != DbTarget.MOCK) { // Connection conn = dataSource.getConnection(); // try { // ConnectionHelper.createTableAndInsertData(conn); // } finally { // conn.close(); // } // } // } // // public Connection getConnection() throws SQLException { // return dataSource.getConnection(); // } // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/DbTarget.java // public enum DbTarget { // MOCK { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.MYSQL; // } // }, HSQLDB { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.HSQLDB; // } // }, MYSQL { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.MYSQL; // } // }; // // public abstract SQLDialect getSqlDialect(); // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/LimitParam.java // @State(Scope.Benchmark) // public class LimitParam { // @Param(value={"1", "10", "100", "1000", "10000", "100000", "1000000"}) // public int limit; // } // Path: src/main/java/org/sfm/benchmark/db/sql2o/Sql2OBenchmark.java import java.sql.SQLException; import java.util.List; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.infra.Blackhole; import org.sfm.beans.SmallBenchmarkObject; import org.sfm.benchmark.db.jmh.ConnectionParam; import org.sfm.benchmark.db.jmh.DbTarget; import org.sfm.benchmark.db.jmh.LimitParam; import org.sfm.sql2o.SfmResultSetHandlerFactory; import org.sfm.sql2o.SfmResultSetHandlerFactoryBuilder; import org.sql2o.ResultSetHandlerFactory; import org.sql2o.Sql2o; package org.sfm.benchmark.db.sql2o; @State(Scope.Benchmark) public class Sql2OBenchmark { private final ResultSetHandlerFactory<SmallBenchmarkObject> factory; private Sql2o sql2o; @Param(value="MOCK")
DbTarget db;
arnaudroger/orm-benchmark
src/main/java/org/sfm/benchmark/db/sql2o/Sql2OBenchmark.java
// Path: src/main/java/org/sfm/beans/SmallBenchmarkObject.java // @Entity // @Table(name="test_small_benchmark_object") // public class SmallBenchmarkObject { // // @Id // @RowMapperField(columnName="ID") // private long id; // // @RowMapperField(columnName="YEAR_STARTED") // private int yearStarted; // @RowMapperField(columnName = "NAME") // private String name; // @RowMapperField(columnName="EMAIL") // private String email; // // @Column(name="ID") // public long getId() { // return id; // } // public void setId(long id) { // this.id = id; // } // @Column(name="NAME") // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } // @Column(name="EMAIL") // public String getEmail() { // return email; // } // public void setEmail(String email) { // this.email = email; // } // // @Column(name="YEAR_STARTED") // public int getYearStarted() { // return yearStarted; // } // public void setYearStarted(int yearStarted) { // this.yearStarted = yearStarted; // } // @Override // public String toString() { // return "SmallBenchmarkObject [id=" + id + ", yearStarted=" // + yearStarted + ", name=" + name + ", email=" + email + "]"; // } // // // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/ConnectionParam.java // @State(Scope.Benchmark) // public class ConnectionParam { // // @Param(value="MOCK") // public DbTarget db; // // public DataSource dataSource; // // @Setup // public void init() throws SQLException, NamingException { // dataSource = ConnectionHelper.getDataSource(db); // // if (db != DbTarget.MOCK) { // Connection conn = dataSource.getConnection(); // try { // ConnectionHelper.createTableAndInsertData(conn); // } finally { // conn.close(); // } // } // } // // public Connection getConnection() throws SQLException { // return dataSource.getConnection(); // } // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/DbTarget.java // public enum DbTarget { // MOCK { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.MYSQL; // } // }, HSQLDB { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.HSQLDB; // } // }, MYSQL { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.MYSQL; // } // }; // // public abstract SQLDialect getSqlDialect(); // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/LimitParam.java // @State(Scope.Benchmark) // public class LimitParam { // @Param(value={"1", "10", "100", "1000", "10000", "100000", "1000000"}) // public int limit; // }
import java.sql.SQLException; import java.util.List; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.infra.Blackhole; import org.sfm.beans.SmallBenchmarkObject; import org.sfm.benchmark.db.jmh.ConnectionParam; import org.sfm.benchmark.db.jmh.DbTarget; import org.sfm.benchmark.db.jmh.LimitParam; import org.sfm.sql2o.SfmResultSetHandlerFactory; import org.sfm.sql2o.SfmResultSetHandlerFactoryBuilder; import org.sql2o.ResultSetHandlerFactory; import org.sql2o.Sql2o;
package org.sfm.benchmark.db.sql2o; @State(Scope.Benchmark) public class Sql2OBenchmark { private final ResultSetHandlerFactory<SmallBenchmarkObject> factory; private Sql2o sql2o; @Param(value="MOCK") DbTarget db; public Sql2OBenchmark() { factory = new SfmResultSetHandlerFactoryBuilder().newFactory(SmallBenchmarkObject.class); } @Setup public void init() throws Exception {
// Path: src/main/java/org/sfm/beans/SmallBenchmarkObject.java // @Entity // @Table(name="test_small_benchmark_object") // public class SmallBenchmarkObject { // // @Id // @RowMapperField(columnName="ID") // private long id; // // @RowMapperField(columnName="YEAR_STARTED") // private int yearStarted; // @RowMapperField(columnName = "NAME") // private String name; // @RowMapperField(columnName="EMAIL") // private String email; // // @Column(name="ID") // public long getId() { // return id; // } // public void setId(long id) { // this.id = id; // } // @Column(name="NAME") // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } // @Column(name="EMAIL") // public String getEmail() { // return email; // } // public void setEmail(String email) { // this.email = email; // } // // @Column(name="YEAR_STARTED") // public int getYearStarted() { // return yearStarted; // } // public void setYearStarted(int yearStarted) { // this.yearStarted = yearStarted; // } // @Override // public String toString() { // return "SmallBenchmarkObject [id=" + id + ", yearStarted=" // + yearStarted + ", name=" + name + ", email=" + email + "]"; // } // // // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/ConnectionParam.java // @State(Scope.Benchmark) // public class ConnectionParam { // // @Param(value="MOCK") // public DbTarget db; // // public DataSource dataSource; // // @Setup // public void init() throws SQLException, NamingException { // dataSource = ConnectionHelper.getDataSource(db); // // if (db != DbTarget.MOCK) { // Connection conn = dataSource.getConnection(); // try { // ConnectionHelper.createTableAndInsertData(conn); // } finally { // conn.close(); // } // } // } // // public Connection getConnection() throws SQLException { // return dataSource.getConnection(); // } // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/DbTarget.java // public enum DbTarget { // MOCK { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.MYSQL; // } // }, HSQLDB { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.HSQLDB; // } // }, MYSQL { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.MYSQL; // } // }; // // public abstract SQLDialect getSqlDialect(); // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/LimitParam.java // @State(Scope.Benchmark) // public class LimitParam { // @Param(value={"1", "10", "100", "1000", "10000", "100000", "1000000"}) // public int limit; // } // Path: src/main/java/org/sfm/benchmark/db/sql2o/Sql2OBenchmark.java import java.sql.SQLException; import java.util.List; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.infra.Blackhole; import org.sfm.beans.SmallBenchmarkObject; import org.sfm.benchmark.db.jmh.ConnectionParam; import org.sfm.benchmark.db.jmh.DbTarget; import org.sfm.benchmark.db.jmh.LimitParam; import org.sfm.sql2o.SfmResultSetHandlerFactory; import org.sfm.sql2o.SfmResultSetHandlerFactoryBuilder; import org.sql2o.ResultSetHandlerFactory; import org.sql2o.Sql2o; package org.sfm.benchmark.db.sql2o; @State(Scope.Benchmark) public class Sql2OBenchmark { private final ResultSetHandlerFactory<SmallBenchmarkObject> factory; private Sql2o sql2o; @Param(value="MOCK") DbTarget db; public Sql2OBenchmark() { factory = new SfmResultSetHandlerFactoryBuilder().newFactory(SmallBenchmarkObject.class); } @Setup public void init() throws Exception {
ConnectionParam connParam = new ConnectionParam();
arnaudroger/orm-benchmark
src/main/java/org/sfm/benchmark/db/sql2o/Sql2OBenchmark.java
// Path: src/main/java/org/sfm/beans/SmallBenchmarkObject.java // @Entity // @Table(name="test_small_benchmark_object") // public class SmallBenchmarkObject { // // @Id // @RowMapperField(columnName="ID") // private long id; // // @RowMapperField(columnName="YEAR_STARTED") // private int yearStarted; // @RowMapperField(columnName = "NAME") // private String name; // @RowMapperField(columnName="EMAIL") // private String email; // // @Column(name="ID") // public long getId() { // return id; // } // public void setId(long id) { // this.id = id; // } // @Column(name="NAME") // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } // @Column(name="EMAIL") // public String getEmail() { // return email; // } // public void setEmail(String email) { // this.email = email; // } // // @Column(name="YEAR_STARTED") // public int getYearStarted() { // return yearStarted; // } // public void setYearStarted(int yearStarted) { // this.yearStarted = yearStarted; // } // @Override // public String toString() { // return "SmallBenchmarkObject [id=" + id + ", yearStarted=" // + yearStarted + ", name=" + name + ", email=" + email + "]"; // } // // // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/ConnectionParam.java // @State(Scope.Benchmark) // public class ConnectionParam { // // @Param(value="MOCK") // public DbTarget db; // // public DataSource dataSource; // // @Setup // public void init() throws SQLException, NamingException { // dataSource = ConnectionHelper.getDataSource(db); // // if (db != DbTarget.MOCK) { // Connection conn = dataSource.getConnection(); // try { // ConnectionHelper.createTableAndInsertData(conn); // } finally { // conn.close(); // } // } // } // // public Connection getConnection() throws SQLException { // return dataSource.getConnection(); // } // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/DbTarget.java // public enum DbTarget { // MOCK { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.MYSQL; // } // }, HSQLDB { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.HSQLDB; // } // }, MYSQL { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.MYSQL; // } // }; // // public abstract SQLDialect getSqlDialect(); // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/LimitParam.java // @State(Scope.Benchmark) // public class LimitParam { // @Param(value={"1", "10", "100", "1000", "10000", "100000", "1000000"}) // public int limit; // }
import java.sql.SQLException; import java.util.List; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.infra.Blackhole; import org.sfm.beans.SmallBenchmarkObject; import org.sfm.benchmark.db.jmh.ConnectionParam; import org.sfm.benchmark.db.jmh.DbTarget; import org.sfm.benchmark.db.jmh.LimitParam; import org.sfm.sql2o.SfmResultSetHandlerFactory; import org.sfm.sql2o.SfmResultSetHandlerFactoryBuilder; import org.sql2o.ResultSetHandlerFactory; import org.sql2o.Sql2o;
package org.sfm.benchmark.db.sql2o; @State(Scope.Benchmark) public class Sql2OBenchmark { private final ResultSetHandlerFactory<SmallBenchmarkObject> factory; private Sql2o sql2o; @Param(value="MOCK") DbTarget db; public Sql2OBenchmark() { factory = new SfmResultSetHandlerFactoryBuilder().newFactory(SmallBenchmarkObject.class); } @Setup public void init() throws Exception { ConnectionParam connParam = new ConnectionParam(); connParam.db = db; connParam.init(); sql2o = new Sql2o(connParam.dataSource); } @Benchmark
// Path: src/main/java/org/sfm/beans/SmallBenchmarkObject.java // @Entity // @Table(name="test_small_benchmark_object") // public class SmallBenchmarkObject { // // @Id // @RowMapperField(columnName="ID") // private long id; // // @RowMapperField(columnName="YEAR_STARTED") // private int yearStarted; // @RowMapperField(columnName = "NAME") // private String name; // @RowMapperField(columnName="EMAIL") // private String email; // // @Column(name="ID") // public long getId() { // return id; // } // public void setId(long id) { // this.id = id; // } // @Column(name="NAME") // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } // @Column(name="EMAIL") // public String getEmail() { // return email; // } // public void setEmail(String email) { // this.email = email; // } // // @Column(name="YEAR_STARTED") // public int getYearStarted() { // return yearStarted; // } // public void setYearStarted(int yearStarted) { // this.yearStarted = yearStarted; // } // @Override // public String toString() { // return "SmallBenchmarkObject [id=" + id + ", yearStarted=" // + yearStarted + ", name=" + name + ", email=" + email + "]"; // } // // // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/ConnectionParam.java // @State(Scope.Benchmark) // public class ConnectionParam { // // @Param(value="MOCK") // public DbTarget db; // // public DataSource dataSource; // // @Setup // public void init() throws SQLException, NamingException { // dataSource = ConnectionHelper.getDataSource(db); // // if (db != DbTarget.MOCK) { // Connection conn = dataSource.getConnection(); // try { // ConnectionHelper.createTableAndInsertData(conn); // } finally { // conn.close(); // } // } // } // // public Connection getConnection() throws SQLException { // return dataSource.getConnection(); // } // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/DbTarget.java // public enum DbTarget { // MOCK { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.MYSQL; // } // }, HSQLDB { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.HSQLDB; // } // }, MYSQL { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.MYSQL; // } // }; // // public abstract SQLDialect getSqlDialect(); // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/LimitParam.java // @State(Scope.Benchmark) // public class LimitParam { // @Param(value={"1", "10", "100", "1000", "10000", "100000", "1000000"}) // public int limit; // } // Path: src/main/java/org/sfm/benchmark/db/sql2o/Sql2OBenchmark.java import java.sql.SQLException; import java.util.List; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.infra.Blackhole; import org.sfm.beans.SmallBenchmarkObject; import org.sfm.benchmark.db.jmh.ConnectionParam; import org.sfm.benchmark.db.jmh.DbTarget; import org.sfm.benchmark.db.jmh.LimitParam; import org.sfm.sql2o.SfmResultSetHandlerFactory; import org.sfm.sql2o.SfmResultSetHandlerFactoryBuilder; import org.sql2o.ResultSetHandlerFactory; import org.sql2o.Sql2o; package org.sfm.benchmark.db.sql2o; @State(Scope.Benchmark) public class Sql2OBenchmark { private final ResultSetHandlerFactory<SmallBenchmarkObject> factory; private Sql2o sql2o; @Param(value="MOCK") DbTarget db; public Sql2OBenchmark() { factory = new SfmResultSetHandlerFactoryBuilder().newFactory(SmallBenchmarkObject.class); } @Setup public void init() throws Exception { ConnectionParam connParam = new ConnectionParam(); connParam.db = db; connParam.init(); sql2o = new Sql2o(connParam.dataSource); } @Benchmark
public void testQuery(LimitParam limit, final Blackhole blackhole) throws Exception {
arnaudroger/orm-benchmark
src/main/java/org/sfm/benchmark/db/jmh/ConnectionParam.java
// Path: src/main/java/org/sfm/benchmark/db/ConnectionHelper.java // public class ConnectionHelper { // // private static final int NB_BENCHMARK_OBJECT = 1000; // public static final String TEST_SMALL_BENCHMARK_OBJECT = "TEST_SMALL_BENCHMARK_OBJECT"; // // public static DataSource getDataSource(DbTarget db) { // switch (db) { // case MOCK: // return new MockDataSource(); // case HSQLDB: // return hsqlDbDataSource(); // case MYSQL: // return mysqlDataSource(); // } // throw new IllegalArgumentException("Invalid db " + db); // } // // private static DataSource mysqlDataSource() { // try { // Class.forName("com.mysql.jdbc.Driver"); // } catch(Exception e) { // throw new Error(e); // } // BoneCPConfig config = new BoneCPConfig(); // // configureBoneCp(config); // // config.setJdbcUrl("jdbc:mysql://localhost/sfm"); // config.setUsername("sfm"); // config.setPassword(""); // // // return new BoneCPDataSource(config); // } // // private static void configureBoneCp(BoneCPConfig config) { // config.setPartitionCount(3); // config.setConnectionTimeoutInMs(500); // config.setStatementsCacheSize(20); // config.setResetConnectionOnClose(false); // config.setCloseConnectionWatch(false); // config.setDefaultAutoCommit(true); // config.setDefaultReadOnly(true); // } // // private static DataSource hsqlDbDataSource() { // try { // Class.forName("org.hsqldb.jdbc.JDBCDriver"); // } catch(Exception e) { // throw new Error(e); // } // BoneCPConfig config = new BoneCPConfig(); // // configureBoneCp(config); // // config.setJdbcUrl("jdbc:hsqldb:mem:mymemdb"); // config.setUsername("SA"); // config.setPassword(""); // // return new BoneCPDataSource(config); // } // // // public static void createTableAndInsertData(Connection c) // throws SQLException { // c.setReadOnly(false); // Statement st = c.createStatement(); // // try { // try { // ResultSet rs = st.executeQuery("select count(*) from " + TEST_SMALL_BENCHMARK_OBJECT); // rs.next(); // if (rs.getLong(1) == NB_BENCHMARK_OBJECT) { // return; // } else { // st.execute("delete from " + TEST_SMALL_BENCHMARK_OBJECT); // } // }catch(Exception e) { // // ignore // createSmallBenchmarkObject(st); // } // // // PreparedStatement ps = c.prepareStatement("insert into " + TEST_SMALL_BENCHMARK_OBJECT + " values(?, ?, ?, ?)"); // for(int i = 0; i < NB_BENCHMARK_OBJECT; i++) { // ps.setLong(1, i); // ps.setString(2, "name " + i); // ps.setString(3, "name" + i + "@gmail.com"); // ps.setInt(4, 2000 + (i % 14)); // ps.addBatch(); // // } // // ps.executeBatch(); // // } finally { // st.close(); // c.setReadOnly(true); // } // } // // public static void createSmallBenchmarkObject(Statement st) throws SQLException { // st.execute("create table " + TEST_SMALL_BENCHMARK_OBJECT + "(" // + " id bigint not null primary key," // + " name varchar(100), " // + " email varchar(100)," // + " year_started int )"); // } // // // // // }
import java.sql.Connection; import java.sql.SQLException; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.sql.DataSource; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.sfm.benchmark.db.ConnectionHelper;
package org.sfm.benchmark.db.jmh; @State(Scope.Benchmark) public class ConnectionParam { @Param(value="MOCK") public DbTarget db; public DataSource dataSource; @Setup public void init() throws SQLException, NamingException {
// Path: src/main/java/org/sfm/benchmark/db/ConnectionHelper.java // public class ConnectionHelper { // // private static final int NB_BENCHMARK_OBJECT = 1000; // public static final String TEST_SMALL_BENCHMARK_OBJECT = "TEST_SMALL_BENCHMARK_OBJECT"; // // public static DataSource getDataSource(DbTarget db) { // switch (db) { // case MOCK: // return new MockDataSource(); // case HSQLDB: // return hsqlDbDataSource(); // case MYSQL: // return mysqlDataSource(); // } // throw new IllegalArgumentException("Invalid db " + db); // } // // private static DataSource mysqlDataSource() { // try { // Class.forName("com.mysql.jdbc.Driver"); // } catch(Exception e) { // throw new Error(e); // } // BoneCPConfig config = new BoneCPConfig(); // // configureBoneCp(config); // // config.setJdbcUrl("jdbc:mysql://localhost/sfm"); // config.setUsername("sfm"); // config.setPassword(""); // // // return new BoneCPDataSource(config); // } // // private static void configureBoneCp(BoneCPConfig config) { // config.setPartitionCount(3); // config.setConnectionTimeoutInMs(500); // config.setStatementsCacheSize(20); // config.setResetConnectionOnClose(false); // config.setCloseConnectionWatch(false); // config.setDefaultAutoCommit(true); // config.setDefaultReadOnly(true); // } // // private static DataSource hsqlDbDataSource() { // try { // Class.forName("org.hsqldb.jdbc.JDBCDriver"); // } catch(Exception e) { // throw new Error(e); // } // BoneCPConfig config = new BoneCPConfig(); // // configureBoneCp(config); // // config.setJdbcUrl("jdbc:hsqldb:mem:mymemdb"); // config.setUsername("SA"); // config.setPassword(""); // // return new BoneCPDataSource(config); // } // // // public static void createTableAndInsertData(Connection c) // throws SQLException { // c.setReadOnly(false); // Statement st = c.createStatement(); // // try { // try { // ResultSet rs = st.executeQuery("select count(*) from " + TEST_SMALL_BENCHMARK_OBJECT); // rs.next(); // if (rs.getLong(1) == NB_BENCHMARK_OBJECT) { // return; // } else { // st.execute("delete from " + TEST_SMALL_BENCHMARK_OBJECT); // } // }catch(Exception e) { // // ignore // createSmallBenchmarkObject(st); // } // // // PreparedStatement ps = c.prepareStatement("insert into " + TEST_SMALL_BENCHMARK_OBJECT + " values(?, ?, ?, ?)"); // for(int i = 0; i < NB_BENCHMARK_OBJECT; i++) { // ps.setLong(1, i); // ps.setString(2, "name " + i); // ps.setString(3, "name" + i + "@gmail.com"); // ps.setInt(4, 2000 + (i % 14)); // ps.addBatch(); // // } // // ps.executeBatch(); // // } finally { // st.close(); // c.setReadOnly(true); // } // } // // public static void createSmallBenchmarkObject(Statement st) throws SQLException { // st.execute("create table " + TEST_SMALL_BENCHMARK_OBJECT + "(" // + " id bigint not null primary key," // + " name varchar(100), " // + " email varchar(100)," // + " year_started int )"); // } // // // // // } // Path: src/main/java/org/sfm/benchmark/db/jmh/ConnectionParam.java import java.sql.Connection; import java.sql.SQLException; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.sql.DataSource; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.sfm.benchmark.db.ConnectionHelper; package org.sfm.benchmark.db.jmh; @State(Scope.Benchmark) public class ConnectionParam { @Param(value="MOCK") public DbTarget db; public DataSource dataSource; @Setup public void init() throws SQLException, NamingException {
dataSource = ConnectionHelper.getDataSource(db);
arnaudroger/orm-benchmark
src/main/java/org/sfm/benchmark/db/hibernate/HibernateHelper.java
// Path: src/main/java/org/sfm/benchmark/db/jmh/ConnectionParam.java // @State(Scope.Benchmark) // public class ConnectionParam { // // @Param(value="MOCK") // public DbTarget db; // // public DataSource dataSource; // // @Setup // public void init() throws SQLException, NamingException { // dataSource = ConnectionHelper.getDataSource(db); // // if (db != DbTarget.MOCK) { // Connection conn = dataSource.getConnection(); // try { // ConnectionHelper.createTableAndInsertData(conn); // } finally { // conn.close(); // } // } // } // // public Connection getConnection() throws SQLException { // return dataSource.getConnection(); // } // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/DbTarget.java // public enum DbTarget { // MOCK { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.MYSQL; // } // }, HSQLDB { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.HSQLDB; // } // }, MYSQL { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.MYSQL; // } // }; // // public abstract SQLDialect getSqlDialect(); // }
import org.hibernate.SessionFactory; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Environment; import org.hibernate.service.ServiceRegistry; import org.sfm.benchmark.db.jmh.ConnectionParam; import org.sfm.benchmark.db.jmh.DbTarget;
package org.sfm.benchmark.db.hibernate; @SuppressWarnings("deprecation") public class HibernateHelper {
// Path: src/main/java/org/sfm/benchmark/db/jmh/ConnectionParam.java // @State(Scope.Benchmark) // public class ConnectionParam { // // @Param(value="MOCK") // public DbTarget db; // // public DataSource dataSource; // // @Setup // public void init() throws SQLException, NamingException { // dataSource = ConnectionHelper.getDataSource(db); // // if (db != DbTarget.MOCK) { // Connection conn = dataSource.getConnection(); // try { // ConnectionHelper.createTableAndInsertData(conn); // } finally { // conn.close(); // } // } // } // // public Connection getConnection() throws SQLException { // return dataSource.getConnection(); // } // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/DbTarget.java // public enum DbTarget { // MOCK { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.MYSQL; // } // }, HSQLDB { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.HSQLDB; // } // }, MYSQL { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.MYSQL; // } // }; // // public abstract SQLDialect getSqlDialect(); // } // Path: src/main/java/org/sfm/benchmark/db/hibernate/HibernateHelper.java import org.hibernate.SessionFactory; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Environment; import org.hibernate.service.ServiceRegistry; import org.sfm.benchmark.db.jmh.ConnectionParam; import org.sfm.benchmark.db.jmh.DbTarget; package org.sfm.benchmark.db.hibernate; @SuppressWarnings("deprecation") public class HibernateHelper {
public static SessionFactory getSessionFactory(boolean enableCache, ConnectionParam conn) {
arnaudroger/orm-benchmark
src/main/java/org/sfm/benchmark/db/hibernate/HibernateHelper.java
// Path: src/main/java/org/sfm/benchmark/db/jmh/ConnectionParam.java // @State(Scope.Benchmark) // public class ConnectionParam { // // @Param(value="MOCK") // public DbTarget db; // // public DataSource dataSource; // // @Setup // public void init() throws SQLException, NamingException { // dataSource = ConnectionHelper.getDataSource(db); // // if (db != DbTarget.MOCK) { // Connection conn = dataSource.getConnection(); // try { // ConnectionHelper.createTableAndInsertData(conn); // } finally { // conn.close(); // } // } // } // // public Connection getConnection() throws SQLException { // return dataSource.getConnection(); // } // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/DbTarget.java // public enum DbTarget { // MOCK { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.MYSQL; // } // }, HSQLDB { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.HSQLDB; // } // }, MYSQL { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.MYSQL; // } // }; // // public abstract SQLDialect getSqlDialect(); // }
import org.hibernate.SessionFactory; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Environment; import org.hibernate.service.ServiceRegistry; import org.sfm.benchmark.db.jmh.ConnectionParam; import org.sfm.benchmark.db.jmh.DbTarget;
package org.sfm.benchmark.db.hibernate; @SuppressWarnings("deprecation") public class HibernateHelper { public static SessionFactory getSessionFactory(boolean enableCache, ConnectionParam conn) { // Create the SessionFactory from hibernate.cfg.xml Configuration configuration = new Configuration(); configuration.addResource("small_benchmark_object.hbm.xml"); try {
// Path: src/main/java/org/sfm/benchmark/db/jmh/ConnectionParam.java // @State(Scope.Benchmark) // public class ConnectionParam { // // @Param(value="MOCK") // public DbTarget db; // // public DataSource dataSource; // // @Setup // public void init() throws SQLException, NamingException { // dataSource = ConnectionHelper.getDataSource(db); // // if (db != DbTarget.MOCK) { // Connection conn = dataSource.getConnection(); // try { // ConnectionHelper.createTableAndInsertData(conn); // } finally { // conn.close(); // } // } // } // // public Connection getConnection() throws SQLException { // return dataSource.getConnection(); // } // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/DbTarget.java // public enum DbTarget { // MOCK { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.MYSQL; // } // }, HSQLDB { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.HSQLDB; // } // }, MYSQL { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.MYSQL; // } // }; // // public abstract SQLDialect getSqlDialect(); // } // Path: src/main/java/org/sfm/benchmark/db/hibernate/HibernateHelper.java import org.hibernate.SessionFactory; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Environment; import org.hibernate.service.ServiceRegistry; import org.sfm.benchmark.db.jmh.ConnectionParam; import org.sfm.benchmark.db.jmh.DbTarget; package org.sfm.benchmark.db.hibernate; @SuppressWarnings("deprecation") public class HibernateHelper { public static SessionFactory getSessionFactory(boolean enableCache, ConnectionParam conn) { // Create the SessionFactory from hibernate.cfg.xml Configuration configuration = new Configuration(); configuration.addResource("small_benchmark_object.hbm.xml"); try {
if (conn.db == DbTarget.MOCK) {
arnaudroger/orm-benchmark
src/main/java/org/sfm/benchmark/db/ConnectionHelper.java
// Path: src/main/java/org/sfm/benchmark/db/jmh/DbTarget.java // public enum DbTarget { // MOCK { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.MYSQL; // } // }, HSQLDB { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.HSQLDB; // } // }, MYSQL { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.MYSQL; // } // }; // // public abstract SQLDialect getSqlDialect(); // } // // Path: src/main/java/org/sfm/benchmark/db/mockdb/MockDataSource.java // public class MockDataSource implements DataSource { // private MockConnection mockConnection = new MockConnection(); // @Override // public PrintWriter getLogWriter() throws SQLException { // return null; // } // // @Override // public void setLogWriter(PrintWriter out) throws SQLException { // } // // @Override // public void setLoginTimeout(int seconds) throws SQLException { // } // // @Override // public int getLoginTimeout() throws SQLException { // return 0; // } // // @Override // public Logger getParentLogger() throws SQLFeatureNotSupportedException { // return null; // } // // @Override // public <T> T unwrap(Class<T> iface) throws SQLException { // return null; // } // // @Override // public boolean isWrapperFor(Class<?> iface) throws SQLException { // return false; // } // // @Override // public Connection getConnection() throws SQLException { // return mockConnection; // } // // @Override // public Connection getConnection(String username, String password) // throws SQLException { // return mockConnection; // } // // }
import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import javax.sql.DataSource; import org.sfm.benchmark.db.jmh.DbTarget; import org.sfm.benchmark.db.mockdb.MockDataSource; import com.jolbox.bonecp.BoneCPConfig; import com.jolbox.bonecp.BoneCPDataSource;
package org.sfm.benchmark.db; public class ConnectionHelper { private static final int NB_BENCHMARK_OBJECT = 1000; public static final String TEST_SMALL_BENCHMARK_OBJECT = "TEST_SMALL_BENCHMARK_OBJECT";
// Path: src/main/java/org/sfm/benchmark/db/jmh/DbTarget.java // public enum DbTarget { // MOCK { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.MYSQL; // } // }, HSQLDB { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.HSQLDB; // } // }, MYSQL { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.MYSQL; // } // }; // // public abstract SQLDialect getSqlDialect(); // } // // Path: src/main/java/org/sfm/benchmark/db/mockdb/MockDataSource.java // public class MockDataSource implements DataSource { // private MockConnection mockConnection = new MockConnection(); // @Override // public PrintWriter getLogWriter() throws SQLException { // return null; // } // // @Override // public void setLogWriter(PrintWriter out) throws SQLException { // } // // @Override // public void setLoginTimeout(int seconds) throws SQLException { // } // // @Override // public int getLoginTimeout() throws SQLException { // return 0; // } // // @Override // public Logger getParentLogger() throws SQLFeatureNotSupportedException { // return null; // } // // @Override // public <T> T unwrap(Class<T> iface) throws SQLException { // return null; // } // // @Override // public boolean isWrapperFor(Class<?> iface) throws SQLException { // return false; // } // // @Override // public Connection getConnection() throws SQLException { // return mockConnection; // } // // @Override // public Connection getConnection(String username, String password) // throws SQLException { // return mockConnection; // } // // } // Path: src/main/java/org/sfm/benchmark/db/ConnectionHelper.java import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import javax.sql.DataSource; import org.sfm.benchmark.db.jmh.DbTarget; import org.sfm.benchmark.db.mockdb.MockDataSource; import com.jolbox.bonecp.BoneCPConfig; import com.jolbox.bonecp.BoneCPDataSource; package org.sfm.benchmark.db; public class ConnectionHelper { private static final int NB_BENCHMARK_OBJECT = 1000; public static final String TEST_SMALL_BENCHMARK_OBJECT = "TEST_SMALL_BENCHMARK_OBJECT";
public static DataSource getDataSource(DbTarget db) {
arnaudroger/orm-benchmark
src/main/java/org/sfm/benchmark/db/ConnectionHelper.java
// Path: src/main/java/org/sfm/benchmark/db/jmh/DbTarget.java // public enum DbTarget { // MOCK { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.MYSQL; // } // }, HSQLDB { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.HSQLDB; // } // }, MYSQL { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.MYSQL; // } // }; // // public abstract SQLDialect getSqlDialect(); // } // // Path: src/main/java/org/sfm/benchmark/db/mockdb/MockDataSource.java // public class MockDataSource implements DataSource { // private MockConnection mockConnection = new MockConnection(); // @Override // public PrintWriter getLogWriter() throws SQLException { // return null; // } // // @Override // public void setLogWriter(PrintWriter out) throws SQLException { // } // // @Override // public void setLoginTimeout(int seconds) throws SQLException { // } // // @Override // public int getLoginTimeout() throws SQLException { // return 0; // } // // @Override // public Logger getParentLogger() throws SQLFeatureNotSupportedException { // return null; // } // // @Override // public <T> T unwrap(Class<T> iface) throws SQLException { // return null; // } // // @Override // public boolean isWrapperFor(Class<?> iface) throws SQLException { // return false; // } // // @Override // public Connection getConnection() throws SQLException { // return mockConnection; // } // // @Override // public Connection getConnection(String username, String password) // throws SQLException { // return mockConnection; // } // // }
import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import javax.sql.DataSource; import org.sfm.benchmark.db.jmh.DbTarget; import org.sfm.benchmark.db.mockdb.MockDataSource; import com.jolbox.bonecp.BoneCPConfig; import com.jolbox.bonecp.BoneCPDataSource;
package org.sfm.benchmark.db; public class ConnectionHelper { private static final int NB_BENCHMARK_OBJECT = 1000; public static final String TEST_SMALL_BENCHMARK_OBJECT = "TEST_SMALL_BENCHMARK_OBJECT"; public static DataSource getDataSource(DbTarget db) { switch (db) { case MOCK:
// Path: src/main/java/org/sfm/benchmark/db/jmh/DbTarget.java // public enum DbTarget { // MOCK { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.MYSQL; // } // }, HSQLDB { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.HSQLDB; // } // }, MYSQL { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.MYSQL; // } // }; // // public abstract SQLDialect getSqlDialect(); // } // // Path: src/main/java/org/sfm/benchmark/db/mockdb/MockDataSource.java // public class MockDataSource implements DataSource { // private MockConnection mockConnection = new MockConnection(); // @Override // public PrintWriter getLogWriter() throws SQLException { // return null; // } // // @Override // public void setLogWriter(PrintWriter out) throws SQLException { // } // // @Override // public void setLoginTimeout(int seconds) throws SQLException { // } // // @Override // public int getLoginTimeout() throws SQLException { // return 0; // } // // @Override // public Logger getParentLogger() throws SQLFeatureNotSupportedException { // return null; // } // // @Override // public <T> T unwrap(Class<T> iface) throws SQLException { // return null; // } // // @Override // public boolean isWrapperFor(Class<?> iface) throws SQLException { // return false; // } // // @Override // public Connection getConnection() throws SQLException { // return mockConnection; // } // // @Override // public Connection getConnection(String username, String password) // throws SQLException { // return mockConnection; // } // // } // Path: src/main/java/org/sfm/benchmark/db/ConnectionHelper.java import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import javax.sql.DataSource; import org.sfm.benchmark.db.jmh.DbTarget; import org.sfm.benchmark.db.mockdb.MockDataSource; import com.jolbox.bonecp.BoneCPConfig; import com.jolbox.bonecp.BoneCPDataSource; package org.sfm.benchmark.db; public class ConnectionHelper { private static final int NB_BENCHMARK_OBJECT = 1000; public static final String TEST_SMALL_BENCHMARK_OBJECT = "TEST_SMALL_BENCHMARK_OBJECT"; public static DataSource getDataSource(DbTarget db) { switch (db) { case MOCK:
return new MockDataSource();
arnaudroger/orm-benchmark
src/main/java/org/sfm/benchmark/db/spring/BeanPropertyRowMapperBenchmark.java
// Path: src/main/java/org/sfm/beans/SmallBenchmarkObject.java // @Entity // @Table(name="test_small_benchmark_object") // public class SmallBenchmarkObject { // // @Id // @RowMapperField(columnName="ID") // private long id; // // @RowMapperField(columnName="YEAR_STARTED") // private int yearStarted; // @RowMapperField(columnName = "NAME") // private String name; // @RowMapperField(columnName="EMAIL") // private String email; // // @Column(name="ID") // public long getId() { // return id; // } // public void setId(long id) { // this.id = id; // } // @Column(name="NAME") // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } // @Column(name="EMAIL") // public String getEmail() { // return email; // } // public void setEmail(String email) { // this.email = email; // } // // @Column(name="YEAR_STARTED") // public int getYearStarted() { // return yearStarted; // } // public void setYearStarted(int yearStarted) { // this.yearStarted = yearStarted; // } // @Override // public String toString() { // return "SmallBenchmarkObject [id=" + id + ", yearStarted=" // + yearStarted + ", name=" + name + ", email=" + email + "]"; // } // // // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/ConnectionParam.java // @State(Scope.Benchmark) // public class ConnectionParam { // // @Param(value="MOCK") // public DbTarget db; // // public DataSource dataSource; // // @Setup // public void init() throws SQLException, NamingException { // dataSource = ConnectionHelper.getDataSource(db); // // if (db != DbTarget.MOCK) { // Connection conn = dataSource.getConnection(); // try { // ConnectionHelper.createTableAndInsertData(conn); // } finally { // conn.close(); // } // } // } // // public Connection getConnection() throws SQLException { // return dataSource.getConnection(); // } // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/LimitParam.java // @State(Scope.Benchmark) // public class LimitParam { // @Param(value={"1", "10", "100", "1000", "10000", "100000", "1000000"}) // public int limit; // }
import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.infra.Blackhole; import org.sfm.beans.SmallBenchmarkObject; import org.sfm.benchmark.db.jmh.ConnectionParam; import org.sfm.benchmark.db.jmh.LimitParam; import org.springframework.jdbc.core.BeanPropertyRowMapper;
package org.sfm.benchmark.db.spring; @State(Scope.Benchmark) public class BeanPropertyRowMapperBenchmark {
// Path: src/main/java/org/sfm/beans/SmallBenchmarkObject.java // @Entity // @Table(name="test_small_benchmark_object") // public class SmallBenchmarkObject { // // @Id // @RowMapperField(columnName="ID") // private long id; // // @RowMapperField(columnName="YEAR_STARTED") // private int yearStarted; // @RowMapperField(columnName = "NAME") // private String name; // @RowMapperField(columnName="EMAIL") // private String email; // // @Column(name="ID") // public long getId() { // return id; // } // public void setId(long id) { // this.id = id; // } // @Column(name="NAME") // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } // @Column(name="EMAIL") // public String getEmail() { // return email; // } // public void setEmail(String email) { // this.email = email; // } // // @Column(name="YEAR_STARTED") // public int getYearStarted() { // return yearStarted; // } // public void setYearStarted(int yearStarted) { // this.yearStarted = yearStarted; // } // @Override // public String toString() { // return "SmallBenchmarkObject [id=" + id + ", yearStarted=" // + yearStarted + ", name=" + name + ", email=" + email + "]"; // } // // // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/ConnectionParam.java // @State(Scope.Benchmark) // public class ConnectionParam { // // @Param(value="MOCK") // public DbTarget db; // // public DataSource dataSource; // // @Setup // public void init() throws SQLException, NamingException { // dataSource = ConnectionHelper.getDataSource(db); // // if (db != DbTarget.MOCK) { // Connection conn = dataSource.getConnection(); // try { // ConnectionHelper.createTableAndInsertData(conn); // } finally { // conn.close(); // } // } // } // // public Connection getConnection() throws SQLException { // return dataSource.getConnection(); // } // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/LimitParam.java // @State(Scope.Benchmark) // public class LimitParam { // @Param(value={"1", "10", "100", "1000", "10000", "100000", "1000000"}) // public int limit; // } // Path: src/main/java/org/sfm/benchmark/db/spring/BeanPropertyRowMapperBenchmark.java import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.infra.Blackhole; import org.sfm.beans.SmallBenchmarkObject; import org.sfm.benchmark.db.jmh.ConnectionParam; import org.sfm.benchmark.db.jmh.LimitParam; import org.springframework.jdbc.core.BeanPropertyRowMapper; package org.sfm.benchmark.db.spring; @State(Scope.Benchmark) public class BeanPropertyRowMapperBenchmark {
private BeanPropertyRowMapper<SmallBenchmarkObject> mapper;
arnaudroger/orm-benchmark
src/main/java/org/sfm/benchmark/db/spring/BeanPropertyRowMapperBenchmark.java
// Path: src/main/java/org/sfm/beans/SmallBenchmarkObject.java // @Entity // @Table(name="test_small_benchmark_object") // public class SmallBenchmarkObject { // // @Id // @RowMapperField(columnName="ID") // private long id; // // @RowMapperField(columnName="YEAR_STARTED") // private int yearStarted; // @RowMapperField(columnName = "NAME") // private String name; // @RowMapperField(columnName="EMAIL") // private String email; // // @Column(name="ID") // public long getId() { // return id; // } // public void setId(long id) { // this.id = id; // } // @Column(name="NAME") // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } // @Column(name="EMAIL") // public String getEmail() { // return email; // } // public void setEmail(String email) { // this.email = email; // } // // @Column(name="YEAR_STARTED") // public int getYearStarted() { // return yearStarted; // } // public void setYearStarted(int yearStarted) { // this.yearStarted = yearStarted; // } // @Override // public String toString() { // return "SmallBenchmarkObject [id=" + id + ", yearStarted=" // + yearStarted + ", name=" + name + ", email=" + email + "]"; // } // // // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/ConnectionParam.java // @State(Scope.Benchmark) // public class ConnectionParam { // // @Param(value="MOCK") // public DbTarget db; // // public DataSource dataSource; // // @Setup // public void init() throws SQLException, NamingException { // dataSource = ConnectionHelper.getDataSource(db); // // if (db != DbTarget.MOCK) { // Connection conn = dataSource.getConnection(); // try { // ConnectionHelper.createTableAndInsertData(conn); // } finally { // conn.close(); // } // } // } // // public Connection getConnection() throws SQLException { // return dataSource.getConnection(); // } // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/LimitParam.java // @State(Scope.Benchmark) // public class LimitParam { // @Param(value={"1", "10", "100", "1000", "10000", "100000", "1000000"}) // public int limit; // }
import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.infra.Blackhole; import org.sfm.beans.SmallBenchmarkObject; import org.sfm.benchmark.db.jmh.ConnectionParam; import org.sfm.benchmark.db.jmh.LimitParam; import org.springframework.jdbc.core.BeanPropertyRowMapper;
package org.sfm.benchmark.db.spring; @State(Scope.Benchmark) public class BeanPropertyRowMapperBenchmark { private BeanPropertyRowMapper<SmallBenchmarkObject> mapper; @Setup public void init() { mapper = new BeanPropertyRowMapper<SmallBenchmarkObject>(SmallBenchmarkObject.class); } @Benchmark
// Path: src/main/java/org/sfm/beans/SmallBenchmarkObject.java // @Entity // @Table(name="test_small_benchmark_object") // public class SmallBenchmarkObject { // // @Id // @RowMapperField(columnName="ID") // private long id; // // @RowMapperField(columnName="YEAR_STARTED") // private int yearStarted; // @RowMapperField(columnName = "NAME") // private String name; // @RowMapperField(columnName="EMAIL") // private String email; // // @Column(name="ID") // public long getId() { // return id; // } // public void setId(long id) { // this.id = id; // } // @Column(name="NAME") // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } // @Column(name="EMAIL") // public String getEmail() { // return email; // } // public void setEmail(String email) { // this.email = email; // } // // @Column(name="YEAR_STARTED") // public int getYearStarted() { // return yearStarted; // } // public void setYearStarted(int yearStarted) { // this.yearStarted = yearStarted; // } // @Override // public String toString() { // return "SmallBenchmarkObject [id=" + id + ", yearStarted=" // + yearStarted + ", name=" + name + ", email=" + email + "]"; // } // // // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/ConnectionParam.java // @State(Scope.Benchmark) // public class ConnectionParam { // // @Param(value="MOCK") // public DbTarget db; // // public DataSource dataSource; // // @Setup // public void init() throws SQLException, NamingException { // dataSource = ConnectionHelper.getDataSource(db); // // if (db != DbTarget.MOCK) { // Connection conn = dataSource.getConnection(); // try { // ConnectionHelper.createTableAndInsertData(conn); // } finally { // conn.close(); // } // } // } // // public Connection getConnection() throws SQLException { // return dataSource.getConnection(); // } // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/LimitParam.java // @State(Scope.Benchmark) // public class LimitParam { // @Param(value={"1", "10", "100", "1000", "10000", "100000", "1000000"}) // public int limit; // } // Path: src/main/java/org/sfm/benchmark/db/spring/BeanPropertyRowMapperBenchmark.java import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.infra.Blackhole; import org.sfm.beans.SmallBenchmarkObject; import org.sfm.benchmark.db.jmh.ConnectionParam; import org.sfm.benchmark.db.jmh.LimitParam; import org.springframework.jdbc.core.BeanPropertyRowMapper; package org.sfm.benchmark.db.spring; @State(Scope.Benchmark) public class BeanPropertyRowMapperBenchmark { private BeanPropertyRowMapper<SmallBenchmarkObject> mapper; @Setup public void init() { mapper = new BeanPropertyRowMapper<SmallBenchmarkObject>(SmallBenchmarkObject.class); } @Benchmark
public void testQuery(ConnectionParam connectionHolder, LimitParam limit, final Blackhole blackhole) throws Exception {
arnaudroger/orm-benchmark
src/main/java/org/sfm/benchmark/db/spring/BeanPropertyRowMapperBenchmark.java
// Path: src/main/java/org/sfm/beans/SmallBenchmarkObject.java // @Entity // @Table(name="test_small_benchmark_object") // public class SmallBenchmarkObject { // // @Id // @RowMapperField(columnName="ID") // private long id; // // @RowMapperField(columnName="YEAR_STARTED") // private int yearStarted; // @RowMapperField(columnName = "NAME") // private String name; // @RowMapperField(columnName="EMAIL") // private String email; // // @Column(name="ID") // public long getId() { // return id; // } // public void setId(long id) { // this.id = id; // } // @Column(name="NAME") // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } // @Column(name="EMAIL") // public String getEmail() { // return email; // } // public void setEmail(String email) { // this.email = email; // } // // @Column(name="YEAR_STARTED") // public int getYearStarted() { // return yearStarted; // } // public void setYearStarted(int yearStarted) { // this.yearStarted = yearStarted; // } // @Override // public String toString() { // return "SmallBenchmarkObject [id=" + id + ", yearStarted=" // + yearStarted + ", name=" + name + ", email=" + email + "]"; // } // // // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/ConnectionParam.java // @State(Scope.Benchmark) // public class ConnectionParam { // // @Param(value="MOCK") // public DbTarget db; // // public DataSource dataSource; // // @Setup // public void init() throws SQLException, NamingException { // dataSource = ConnectionHelper.getDataSource(db); // // if (db != DbTarget.MOCK) { // Connection conn = dataSource.getConnection(); // try { // ConnectionHelper.createTableAndInsertData(conn); // } finally { // conn.close(); // } // } // } // // public Connection getConnection() throws SQLException { // return dataSource.getConnection(); // } // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/LimitParam.java // @State(Scope.Benchmark) // public class LimitParam { // @Param(value={"1", "10", "100", "1000", "10000", "100000", "1000000"}) // public int limit; // }
import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.infra.Blackhole; import org.sfm.beans.SmallBenchmarkObject; import org.sfm.benchmark.db.jmh.ConnectionParam; import org.sfm.benchmark.db.jmh.LimitParam; import org.springframework.jdbc.core.BeanPropertyRowMapper;
package org.sfm.benchmark.db.spring; @State(Scope.Benchmark) public class BeanPropertyRowMapperBenchmark { private BeanPropertyRowMapper<SmallBenchmarkObject> mapper; @Setup public void init() { mapper = new BeanPropertyRowMapper<SmallBenchmarkObject>(SmallBenchmarkObject.class); } @Benchmark
// Path: src/main/java/org/sfm/beans/SmallBenchmarkObject.java // @Entity // @Table(name="test_small_benchmark_object") // public class SmallBenchmarkObject { // // @Id // @RowMapperField(columnName="ID") // private long id; // // @RowMapperField(columnName="YEAR_STARTED") // private int yearStarted; // @RowMapperField(columnName = "NAME") // private String name; // @RowMapperField(columnName="EMAIL") // private String email; // // @Column(name="ID") // public long getId() { // return id; // } // public void setId(long id) { // this.id = id; // } // @Column(name="NAME") // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } // @Column(name="EMAIL") // public String getEmail() { // return email; // } // public void setEmail(String email) { // this.email = email; // } // // @Column(name="YEAR_STARTED") // public int getYearStarted() { // return yearStarted; // } // public void setYearStarted(int yearStarted) { // this.yearStarted = yearStarted; // } // @Override // public String toString() { // return "SmallBenchmarkObject [id=" + id + ", yearStarted=" // + yearStarted + ", name=" + name + ", email=" + email + "]"; // } // // // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/ConnectionParam.java // @State(Scope.Benchmark) // public class ConnectionParam { // // @Param(value="MOCK") // public DbTarget db; // // public DataSource dataSource; // // @Setup // public void init() throws SQLException, NamingException { // dataSource = ConnectionHelper.getDataSource(db); // // if (db != DbTarget.MOCK) { // Connection conn = dataSource.getConnection(); // try { // ConnectionHelper.createTableAndInsertData(conn); // } finally { // conn.close(); // } // } // } // // public Connection getConnection() throws SQLException { // return dataSource.getConnection(); // } // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/LimitParam.java // @State(Scope.Benchmark) // public class LimitParam { // @Param(value={"1", "10", "100", "1000", "10000", "100000", "1000000"}) // public int limit; // } // Path: src/main/java/org/sfm/benchmark/db/spring/BeanPropertyRowMapperBenchmark.java import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.infra.Blackhole; import org.sfm.beans.SmallBenchmarkObject; import org.sfm.benchmark.db.jmh.ConnectionParam; import org.sfm.benchmark.db.jmh.LimitParam; import org.springframework.jdbc.core.BeanPropertyRowMapper; package org.sfm.benchmark.db.spring; @State(Scope.Benchmark) public class BeanPropertyRowMapperBenchmark { private BeanPropertyRowMapper<SmallBenchmarkObject> mapper; @Setup public void init() { mapper = new BeanPropertyRowMapper<SmallBenchmarkObject>(SmallBenchmarkObject.class); } @Benchmark
public void testQuery(ConnectionParam connectionHolder, LimitParam limit, final Blackhole blackhole) throws Exception {
arnaudroger/orm-benchmark
src/main/java/org/sfm/benchmark/db/jdbc/PureJdbcBenchmark.java
// Path: src/main/java/org/sfm/beans/SmallBenchmarkObject.java // @Entity // @Table(name="test_small_benchmark_object") // public class SmallBenchmarkObject { // // @Id // @RowMapperField(columnName="ID") // private long id; // // @RowMapperField(columnName="YEAR_STARTED") // private int yearStarted; // @RowMapperField(columnName = "NAME") // private String name; // @RowMapperField(columnName="EMAIL") // private String email; // // @Column(name="ID") // public long getId() { // return id; // } // public void setId(long id) { // this.id = id; // } // @Column(name="NAME") // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } // @Column(name="EMAIL") // public String getEmail() { // return email; // } // public void setEmail(String email) { // this.email = email; // } // // @Column(name="YEAR_STARTED") // public int getYearStarted() { // return yearStarted; // } // public void setYearStarted(int yearStarted) { // this.yearStarted = yearStarted; // } // @Override // public String toString() { // return "SmallBenchmarkObject [id=" + id + ", yearStarted=" // + yearStarted + ", name=" + name + ", email=" + email + "]"; // } // // // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/ConnectionParam.java // @State(Scope.Benchmark) // public class ConnectionParam { // // @Param(value="MOCK") // public DbTarget db; // // public DataSource dataSource; // // @Setup // public void init() throws SQLException, NamingException { // dataSource = ConnectionHelper.getDataSource(db); // // if (db != DbTarget.MOCK) { // Connection conn = dataSource.getConnection(); // try { // ConnectionHelper.createTableAndInsertData(conn); // } finally { // conn.close(); // } // } // } // // public Connection getConnection() throws SQLException { // return dataSource.getConnection(); // } // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/LimitParam.java // @State(Scope.Benchmark) // public class LimitParam { // @Param(value={"1", "10", "100", "1000", "10000", "100000", "1000000"}) // public int limit; // }
import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.infra.Blackhole; import org.sfm.beans.SmallBenchmarkObject; import org.sfm.benchmark.db.jmh.ConnectionParam; import org.sfm.benchmark.db.jmh.LimitParam;
package org.sfm.benchmark.db.jdbc; @State(Scope.Benchmark) public class PureJdbcBenchmark { private RowMapper<?> mapper; @Setup public void init() {
// Path: src/main/java/org/sfm/beans/SmallBenchmarkObject.java // @Entity // @Table(name="test_small_benchmark_object") // public class SmallBenchmarkObject { // // @Id // @RowMapperField(columnName="ID") // private long id; // // @RowMapperField(columnName="YEAR_STARTED") // private int yearStarted; // @RowMapperField(columnName = "NAME") // private String name; // @RowMapperField(columnName="EMAIL") // private String email; // // @Column(name="ID") // public long getId() { // return id; // } // public void setId(long id) { // this.id = id; // } // @Column(name="NAME") // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } // @Column(name="EMAIL") // public String getEmail() { // return email; // } // public void setEmail(String email) { // this.email = email; // } // // @Column(name="YEAR_STARTED") // public int getYearStarted() { // return yearStarted; // } // public void setYearStarted(int yearStarted) { // this.yearStarted = yearStarted; // } // @Override // public String toString() { // return "SmallBenchmarkObject [id=" + id + ", yearStarted=" // + yearStarted + ", name=" + name + ", email=" + email + "]"; // } // // // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/ConnectionParam.java // @State(Scope.Benchmark) // public class ConnectionParam { // // @Param(value="MOCK") // public DbTarget db; // // public DataSource dataSource; // // @Setup // public void init() throws SQLException, NamingException { // dataSource = ConnectionHelper.getDataSource(db); // // if (db != DbTarget.MOCK) { // Connection conn = dataSource.getConnection(); // try { // ConnectionHelper.createTableAndInsertData(conn); // } finally { // conn.close(); // } // } // } // // public Connection getConnection() throws SQLException { // return dataSource.getConnection(); // } // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/LimitParam.java // @State(Scope.Benchmark) // public class LimitParam { // @Param(value={"1", "10", "100", "1000", "10000", "100000", "1000000"}) // public int limit; // } // Path: src/main/java/org/sfm/benchmark/db/jdbc/PureJdbcBenchmark.java import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.infra.Blackhole; import org.sfm.beans.SmallBenchmarkObject; import org.sfm.benchmark.db.jmh.ConnectionParam; import org.sfm.benchmark.db.jmh.LimitParam; package org.sfm.benchmark.db.jdbc; @State(Scope.Benchmark) public class PureJdbcBenchmark { private RowMapper<?> mapper; @Setup public void init() {
mapper = new RowMapper<SmallBenchmarkObject>() {
arnaudroger/orm-benchmark
src/main/java/org/sfm/benchmark/db/jdbc/PureJdbcBenchmark.java
// Path: src/main/java/org/sfm/beans/SmallBenchmarkObject.java // @Entity // @Table(name="test_small_benchmark_object") // public class SmallBenchmarkObject { // // @Id // @RowMapperField(columnName="ID") // private long id; // // @RowMapperField(columnName="YEAR_STARTED") // private int yearStarted; // @RowMapperField(columnName = "NAME") // private String name; // @RowMapperField(columnName="EMAIL") // private String email; // // @Column(name="ID") // public long getId() { // return id; // } // public void setId(long id) { // this.id = id; // } // @Column(name="NAME") // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } // @Column(name="EMAIL") // public String getEmail() { // return email; // } // public void setEmail(String email) { // this.email = email; // } // // @Column(name="YEAR_STARTED") // public int getYearStarted() { // return yearStarted; // } // public void setYearStarted(int yearStarted) { // this.yearStarted = yearStarted; // } // @Override // public String toString() { // return "SmallBenchmarkObject [id=" + id + ", yearStarted=" // + yearStarted + ", name=" + name + ", email=" + email + "]"; // } // // // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/ConnectionParam.java // @State(Scope.Benchmark) // public class ConnectionParam { // // @Param(value="MOCK") // public DbTarget db; // // public DataSource dataSource; // // @Setup // public void init() throws SQLException, NamingException { // dataSource = ConnectionHelper.getDataSource(db); // // if (db != DbTarget.MOCK) { // Connection conn = dataSource.getConnection(); // try { // ConnectionHelper.createTableAndInsertData(conn); // } finally { // conn.close(); // } // } // } // // public Connection getConnection() throws SQLException { // return dataSource.getConnection(); // } // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/LimitParam.java // @State(Scope.Benchmark) // public class LimitParam { // @Param(value={"1", "10", "100", "1000", "10000", "100000", "1000000"}) // public int limit; // }
import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.infra.Blackhole; import org.sfm.beans.SmallBenchmarkObject; import org.sfm.benchmark.db.jmh.ConnectionParam; import org.sfm.benchmark.db.jmh.LimitParam;
package org.sfm.benchmark.db.jdbc; @State(Scope.Benchmark) public class PureJdbcBenchmark { private RowMapper<?> mapper; @Setup public void init() { mapper = new RowMapper<SmallBenchmarkObject>() { @Override public SmallBenchmarkObject map(ResultSet rs) throws Exception { SmallBenchmarkObject o = new SmallBenchmarkObject(); o.setId(rs.getLong(1)); o.setName(rs.getString(2)); o.setEmail(rs.getString(3)); o.setYearStarted(rs.getInt(4)); return o; } }; } @Benchmark
// Path: src/main/java/org/sfm/beans/SmallBenchmarkObject.java // @Entity // @Table(name="test_small_benchmark_object") // public class SmallBenchmarkObject { // // @Id // @RowMapperField(columnName="ID") // private long id; // // @RowMapperField(columnName="YEAR_STARTED") // private int yearStarted; // @RowMapperField(columnName = "NAME") // private String name; // @RowMapperField(columnName="EMAIL") // private String email; // // @Column(name="ID") // public long getId() { // return id; // } // public void setId(long id) { // this.id = id; // } // @Column(name="NAME") // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } // @Column(name="EMAIL") // public String getEmail() { // return email; // } // public void setEmail(String email) { // this.email = email; // } // // @Column(name="YEAR_STARTED") // public int getYearStarted() { // return yearStarted; // } // public void setYearStarted(int yearStarted) { // this.yearStarted = yearStarted; // } // @Override // public String toString() { // return "SmallBenchmarkObject [id=" + id + ", yearStarted=" // + yearStarted + ", name=" + name + ", email=" + email + "]"; // } // // // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/ConnectionParam.java // @State(Scope.Benchmark) // public class ConnectionParam { // // @Param(value="MOCK") // public DbTarget db; // // public DataSource dataSource; // // @Setup // public void init() throws SQLException, NamingException { // dataSource = ConnectionHelper.getDataSource(db); // // if (db != DbTarget.MOCK) { // Connection conn = dataSource.getConnection(); // try { // ConnectionHelper.createTableAndInsertData(conn); // } finally { // conn.close(); // } // } // } // // public Connection getConnection() throws SQLException { // return dataSource.getConnection(); // } // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/LimitParam.java // @State(Scope.Benchmark) // public class LimitParam { // @Param(value={"1", "10", "100", "1000", "10000", "100000", "1000000"}) // public int limit; // } // Path: src/main/java/org/sfm/benchmark/db/jdbc/PureJdbcBenchmark.java import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.infra.Blackhole; import org.sfm.beans.SmallBenchmarkObject; import org.sfm.benchmark.db.jmh.ConnectionParam; import org.sfm.benchmark.db.jmh.LimitParam; package org.sfm.benchmark.db.jdbc; @State(Scope.Benchmark) public class PureJdbcBenchmark { private RowMapper<?> mapper; @Setup public void init() { mapper = new RowMapper<SmallBenchmarkObject>() { @Override public SmallBenchmarkObject map(ResultSet rs) throws Exception { SmallBenchmarkObject o = new SmallBenchmarkObject(); o.setId(rs.getLong(1)); o.setName(rs.getString(2)); o.setEmail(rs.getString(3)); o.setYearStarted(rs.getInt(4)); return o; } }; } @Benchmark
public void testQuery(ConnectionParam connectionHolder, LimitParam limit, final Blackhole blackhole) throws Exception {
arnaudroger/orm-benchmark
src/main/java/org/sfm/benchmark/db/jdbc/PureJdbcBenchmark.java
// Path: src/main/java/org/sfm/beans/SmallBenchmarkObject.java // @Entity // @Table(name="test_small_benchmark_object") // public class SmallBenchmarkObject { // // @Id // @RowMapperField(columnName="ID") // private long id; // // @RowMapperField(columnName="YEAR_STARTED") // private int yearStarted; // @RowMapperField(columnName = "NAME") // private String name; // @RowMapperField(columnName="EMAIL") // private String email; // // @Column(name="ID") // public long getId() { // return id; // } // public void setId(long id) { // this.id = id; // } // @Column(name="NAME") // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } // @Column(name="EMAIL") // public String getEmail() { // return email; // } // public void setEmail(String email) { // this.email = email; // } // // @Column(name="YEAR_STARTED") // public int getYearStarted() { // return yearStarted; // } // public void setYearStarted(int yearStarted) { // this.yearStarted = yearStarted; // } // @Override // public String toString() { // return "SmallBenchmarkObject [id=" + id + ", yearStarted=" // + yearStarted + ", name=" + name + ", email=" + email + "]"; // } // // // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/ConnectionParam.java // @State(Scope.Benchmark) // public class ConnectionParam { // // @Param(value="MOCK") // public DbTarget db; // // public DataSource dataSource; // // @Setup // public void init() throws SQLException, NamingException { // dataSource = ConnectionHelper.getDataSource(db); // // if (db != DbTarget.MOCK) { // Connection conn = dataSource.getConnection(); // try { // ConnectionHelper.createTableAndInsertData(conn); // } finally { // conn.close(); // } // } // } // // public Connection getConnection() throws SQLException { // return dataSource.getConnection(); // } // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/LimitParam.java // @State(Scope.Benchmark) // public class LimitParam { // @Param(value={"1", "10", "100", "1000", "10000", "100000", "1000000"}) // public int limit; // }
import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.infra.Blackhole; import org.sfm.beans.SmallBenchmarkObject; import org.sfm.benchmark.db.jmh.ConnectionParam; import org.sfm.benchmark.db.jmh.LimitParam;
package org.sfm.benchmark.db.jdbc; @State(Scope.Benchmark) public class PureJdbcBenchmark { private RowMapper<?> mapper; @Setup public void init() { mapper = new RowMapper<SmallBenchmarkObject>() { @Override public SmallBenchmarkObject map(ResultSet rs) throws Exception { SmallBenchmarkObject o = new SmallBenchmarkObject(); o.setId(rs.getLong(1)); o.setName(rs.getString(2)); o.setEmail(rs.getString(3)); o.setYearStarted(rs.getInt(4)); return o; } }; } @Benchmark
// Path: src/main/java/org/sfm/beans/SmallBenchmarkObject.java // @Entity // @Table(name="test_small_benchmark_object") // public class SmallBenchmarkObject { // // @Id // @RowMapperField(columnName="ID") // private long id; // // @RowMapperField(columnName="YEAR_STARTED") // private int yearStarted; // @RowMapperField(columnName = "NAME") // private String name; // @RowMapperField(columnName="EMAIL") // private String email; // // @Column(name="ID") // public long getId() { // return id; // } // public void setId(long id) { // this.id = id; // } // @Column(name="NAME") // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } // @Column(name="EMAIL") // public String getEmail() { // return email; // } // public void setEmail(String email) { // this.email = email; // } // // @Column(name="YEAR_STARTED") // public int getYearStarted() { // return yearStarted; // } // public void setYearStarted(int yearStarted) { // this.yearStarted = yearStarted; // } // @Override // public String toString() { // return "SmallBenchmarkObject [id=" + id + ", yearStarted=" // + yearStarted + ", name=" + name + ", email=" + email + "]"; // } // // // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/ConnectionParam.java // @State(Scope.Benchmark) // public class ConnectionParam { // // @Param(value="MOCK") // public DbTarget db; // // public DataSource dataSource; // // @Setup // public void init() throws SQLException, NamingException { // dataSource = ConnectionHelper.getDataSource(db); // // if (db != DbTarget.MOCK) { // Connection conn = dataSource.getConnection(); // try { // ConnectionHelper.createTableAndInsertData(conn); // } finally { // conn.close(); // } // } // } // // public Connection getConnection() throws SQLException { // return dataSource.getConnection(); // } // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/LimitParam.java // @State(Scope.Benchmark) // public class LimitParam { // @Param(value={"1", "10", "100", "1000", "10000", "100000", "1000000"}) // public int limit; // } // Path: src/main/java/org/sfm/benchmark/db/jdbc/PureJdbcBenchmark.java import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.infra.Blackhole; import org.sfm.beans.SmallBenchmarkObject; import org.sfm.benchmark.db.jmh.ConnectionParam; import org.sfm.benchmark.db.jmh.LimitParam; package org.sfm.benchmark.db.jdbc; @State(Scope.Benchmark) public class PureJdbcBenchmark { private RowMapper<?> mapper; @Setup public void init() { mapper = new RowMapper<SmallBenchmarkObject>() { @Override public SmallBenchmarkObject map(ResultSet rs) throws Exception { SmallBenchmarkObject o = new SmallBenchmarkObject(); o.setId(rs.getLong(1)); o.setName(rs.getString(2)); o.setEmail(rs.getString(3)); o.setYearStarted(rs.getInt(4)); return o; } }; } @Benchmark
public void testQuery(ConnectionParam connectionHolder, LimitParam limit, final Blackhole blackhole) throws Exception {
arnaudroger/orm-benchmark
src/main/java/org/sfm/benchmark/db/ibatis/DbObjectMapper.java
// Path: src/main/java/org/sfm/beans/SmallBenchmarkObject.java // @Entity // @Table(name="test_small_benchmark_object") // public class SmallBenchmarkObject { // // @Id // @RowMapperField(columnName="ID") // private long id; // // @RowMapperField(columnName="YEAR_STARTED") // private int yearStarted; // @RowMapperField(columnName = "NAME") // private String name; // @RowMapperField(columnName="EMAIL") // private String email; // // @Column(name="ID") // public long getId() { // return id; // } // public void setId(long id) { // this.id = id; // } // @Column(name="NAME") // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } // @Column(name="EMAIL") // public String getEmail() { // return email; // } // public void setEmail(String email) { // this.email = email; // } // // @Column(name="YEAR_STARTED") // public int getYearStarted() { // return yearStarted; // } // public void setYearStarted(int yearStarted) { // this.yearStarted = yearStarted; // } // @Override // public String toString() { // return "SmallBenchmarkObject [id=" + id + ", yearStarted=" // + yearStarted + ", name=" + name + ", email=" + email + "]"; // } // // // }
import java.util.List; import org.apache.ibatis.annotations.Select; import org.sfm.beans.SmallBenchmarkObject;
package org.sfm.benchmark.db.ibatis; public interface DbObjectMapper { @Select("SELECT id, name, email, year_started FROM test_small_benchmark_object ")
// Path: src/main/java/org/sfm/beans/SmallBenchmarkObject.java // @Entity // @Table(name="test_small_benchmark_object") // public class SmallBenchmarkObject { // // @Id // @RowMapperField(columnName="ID") // private long id; // // @RowMapperField(columnName="YEAR_STARTED") // private int yearStarted; // @RowMapperField(columnName = "NAME") // private String name; // @RowMapperField(columnName="EMAIL") // private String email; // // @Column(name="ID") // public long getId() { // return id; // } // public void setId(long id) { // this.id = id; // } // @Column(name="NAME") // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } // @Column(name="EMAIL") // public String getEmail() { // return email; // } // public void setEmail(String email) { // this.email = email; // } // // @Column(name="YEAR_STARTED") // public int getYearStarted() { // return yearStarted; // } // public void setYearStarted(int yearStarted) { // this.yearStarted = yearStarted; // } // @Override // public String toString() { // return "SmallBenchmarkObject [id=" + id + ", yearStarted=" // + yearStarted + ", name=" + name + ", email=" + email + "]"; // } // // // } // Path: src/main/java/org/sfm/benchmark/db/ibatis/DbObjectMapper.java import java.util.List; import org.apache.ibatis.annotations.Select; import org.sfm.beans.SmallBenchmarkObject; package org.sfm.benchmark.db.ibatis; public interface DbObjectMapper { @Select("SELECT id, name, email, year_started FROM test_small_benchmark_object ")
List<SmallBenchmarkObject> selectSmallBenchmarkObjects();
arnaudroger/orm-benchmark
src/main/java/org/sfm/benchmark/csv/CsvMapperBenchmark.java
// Path: src/main/java/org/sfm/beans/FinalSmallBenchmarkObject.java // public class FinalSmallBenchmarkObject { // // private final long id; // // private final int yearStarted; // private final String name; // private final String email; // // public FinalSmallBenchmarkObject(long id, int yearStarted, String name, String email) { // this.id = id; // this.yearStarted = yearStarted; // this.name = name; // this.email = email; // } // // public long getId() { // return id; // } // public String getName() { // return name; // } // public String getEmail() { // return email; // } // // public int getYearStarted() { // return yearStarted; // } // // @Override // public String toString() { // return "FinalSmallBenchmarkObject [id=" + id + ", yearStarted=" // + yearStarted + ", name=" + name + ", email=" + email + "]"; // } // // // } // // Path: src/main/java/org/sfm/beans/SmallBenchmarkObject.java // @Entity // @Table(name="test_small_benchmark_object") // public class SmallBenchmarkObject { // // @Id // @RowMapperField(columnName="ID") // private long id; // // @RowMapperField(columnName="YEAR_STARTED") // private int yearStarted; // @RowMapperField(columnName = "NAME") // private String name; // @RowMapperField(columnName="EMAIL") // private String email; // // @Column(name="ID") // public long getId() { // return id; // } // public void setId(long id) { // this.id = id; // } // @Column(name="NAME") // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } // @Column(name="EMAIL") // public String getEmail() { // return email; // } // public void setEmail(String email) { // this.email = email; // } // // @Column(name="YEAR_STARTED") // public int getYearStarted() { // return yearStarted; // } // public void setYearStarted(int yearStarted) { // this.yearStarted = yearStarted; // } // @Override // public String toString() { // return "SmallBenchmarkObject [id=" + id + ", yearStarted=" // + yearStarted + ", name=" + name + ", email=" + email + "]"; // } // // // }
import java.io.*; import java.lang.reflect.Field; import java.util.List; import au.com.bytecode.opencsv.bean.ColumnPositionMappingStrategy; import org.apache.commons.io.FileUtils; import org.apache.commons.io.input.CharSequenceReader; import org.openjdk.jmh.annotations.*; import org.openjdk.jmh.infra.Blackhole; import org.sfm.beans.FinalSmallBenchmarkObject; import org.sfm.beans.SmallBenchmarkObject; import org.sfm.csv.CsvMapper; import org.sfm.csv.CsvMapperBuilder; import org.sfm.csv.CsvMapperFactory; import org.sfm.csv.CsvParser; import org.sfm.utils.RowHandler; import au.com.bytecode.opencsv.CSVReader; import au.com.bytecode.opencsv.bean.CsvToBean; import au.com.bytecode.opencsv.bean.HeaderColumnNameTranslateMappingStrategy; import com.fasterxml.jackson.databind.MappingIterator; import com.fasterxml.jackson.databind.ObjectReader; import com.fasterxml.jackson.dataformat.csv.CsvSchema; import com.univocity.parsers.common.ParsingContext; import com.univocity.parsers.common.processor.BeanProcessor; import com.univocity.parsers.csv.CsvParserSettings;
package org.sfm.benchmark.csv; @State(Scope.Benchmark) public class CsvMapperBenchmark {
// Path: src/main/java/org/sfm/beans/FinalSmallBenchmarkObject.java // public class FinalSmallBenchmarkObject { // // private final long id; // // private final int yearStarted; // private final String name; // private final String email; // // public FinalSmallBenchmarkObject(long id, int yearStarted, String name, String email) { // this.id = id; // this.yearStarted = yearStarted; // this.name = name; // this.email = email; // } // // public long getId() { // return id; // } // public String getName() { // return name; // } // public String getEmail() { // return email; // } // // public int getYearStarted() { // return yearStarted; // } // // @Override // public String toString() { // return "FinalSmallBenchmarkObject [id=" + id + ", yearStarted=" // + yearStarted + ", name=" + name + ", email=" + email + "]"; // } // // // } // // Path: src/main/java/org/sfm/beans/SmallBenchmarkObject.java // @Entity // @Table(name="test_small_benchmark_object") // public class SmallBenchmarkObject { // // @Id // @RowMapperField(columnName="ID") // private long id; // // @RowMapperField(columnName="YEAR_STARTED") // private int yearStarted; // @RowMapperField(columnName = "NAME") // private String name; // @RowMapperField(columnName="EMAIL") // private String email; // // @Column(name="ID") // public long getId() { // return id; // } // public void setId(long id) { // this.id = id; // } // @Column(name="NAME") // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } // @Column(name="EMAIL") // public String getEmail() { // return email; // } // public void setEmail(String email) { // this.email = email; // } // // @Column(name="YEAR_STARTED") // public int getYearStarted() { // return yearStarted; // } // public void setYearStarted(int yearStarted) { // this.yearStarted = yearStarted; // } // @Override // public String toString() { // return "SmallBenchmarkObject [id=" + id + ", yearStarted=" // + yearStarted + ", name=" + name + ", email=" + email + "]"; // } // // // } // Path: src/main/java/org/sfm/benchmark/csv/CsvMapperBenchmark.java import java.io.*; import java.lang.reflect.Field; import java.util.List; import au.com.bytecode.opencsv.bean.ColumnPositionMappingStrategy; import org.apache.commons.io.FileUtils; import org.apache.commons.io.input.CharSequenceReader; import org.openjdk.jmh.annotations.*; import org.openjdk.jmh.infra.Blackhole; import org.sfm.beans.FinalSmallBenchmarkObject; import org.sfm.beans.SmallBenchmarkObject; import org.sfm.csv.CsvMapper; import org.sfm.csv.CsvMapperBuilder; import org.sfm.csv.CsvMapperFactory; import org.sfm.csv.CsvParser; import org.sfm.utils.RowHandler; import au.com.bytecode.opencsv.CSVReader; import au.com.bytecode.opencsv.bean.CsvToBean; import au.com.bytecode.opencsv.bean.HeaderColumnNameTranslateMappingStrategy; import com.fasterxml.jackson.databind.MappingIterator; import com.fasterxml.jackson.databind.ObjectReader; import com.fasterxml.jackson.dataformat.csv.CsvSchema; import com.univocity.parsers.common.ParsingContext; import com.univocity.parsers.common.processor.BeanProcessor; import com.univocity.parsers.csv.CsvParserSettings; package org.sfm.benchmark.csv; @State(Scope.Benchmark) public class CsvMapperBenchmark {
private CsvMapper<SmallBenchmarkObject> mapper;
arnaudroger/orm-benchmark
src/main/java/org/sfm/benchmark/csv/CsvMapperBenchmark.java
// Path: src/main/java/org/sfm/beans/FinalSmallBenchmarkObject.java // public class FinalSmallBenchmarkObject { // // private final long id; // // private final int yearStarted; // private final String name; // private final String email; // // public FinalSmallBenchmarkObject(long id, int yearStarted, String name, String email) { // this.id = id; // this.yearStarted = yearStarted; // this.name = name; // this.email = email; // } // // public long getId() { // return id; // } // public String getName() { // return name; // } // public String getEmail() { // return email; // } // // public int getYearStarted() { // return yearStarted; // } // // @Override // public String toString() { // return "FinalSmallBenchmarkObject [id=" + id + ", yearStarted=" // + yearStarted + ", name=" + name + ", email=" + email + "]"; // } // // // } // // Path: src/main/java/org/sfm/beans/SmallBenchmarkObject.java // @Entity // @Table(name="test_small_benchmark_object") // public class SmallBenchmarkObject { // // @Id // @RowMapperField(columnName="ID") // private long id; // // @RowMapperField(columnName="YEAR_STARTED") // private int yearStarted; // @RowMapperField(columnName = "NAME") // private String name; // @RowMapperField(columnName="EMAIL") // private String email; // // @Column(name="ID") // public long getId() { // return id; // } // public void setId(long id) { // this.id = id; // } // @Column(name="NAME") // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } // @Column(name="EMAIL") // public String getEmail() { // return email; // } // public void setEmail(String email) { // this.email = email; // } // // @Column(name="YEAR_STARTED") // public int getYearStarted() { // return yearStarted; // } // public void setYearStarted(int yearStarted) { // this.yearStarted = yearStarted; // } // @Override // public String toString() { // return "SmallBenchmarkObject [id=" + id + ", yearStarted=" // + yearStarted + ", name=" + name + ", email=" + email + "]"; // } // // // }
import java.io.*; import java.lang.reflect.Field; import java.util.List; import au.com.bytecode.opencsv.bean.ColumnPositionMappingStrategy; import org.apache.commons.io.FileUtils; import org.apache.commons.io.input.CharSequenceReader; import org.openjdk.jmh.annotations.*; import org.openjdk.jmh.infra.Blackhole; import org.sfm.beans.FinalSmallBenchmarkObject; import org.sfm.beans.SmallBenchmarkObject; import org.sfm.csv.CsvMapper; import org.sfm.csv.CsvMapperBuilder; import org.sfm.csv.CsvMapperFactory; import org.sfm.csv.CsvParser; import org.sfm.utils.RowHandler; import au.com.bytecode.opencsv.CSVReader; import au.com.bytecode.opencsv.bean.CsvToBean; import au.com.bytecode.opencsv.bean.HeaderColumnNameTranslateMappingStrategy; import com.fasterxml.jackson.databind.MappingIterator; import com.fasterxml.jackson.databind.ObjectReader; import com.fasterxml.jackson.dataformat.csv.CsvSchema; import com.univocity.parsers.common.ParsingContext; import com.univocity.parsers.common.processor.BeanProcessor; import com.univocity.parsers.csv.CsvParserSettings;
package org.sfm.benchmark.csv; @State(Scope.Benchmark) public class CsvMapperBenchmark { private CsvMapper<SmallBenchmarkObject> mapper;
// Path: src/main/java/org/sfm/beans/FinalSmallBenchmarkObject.java // public class FinalSmallBenchmarkObject { // // private final long id; // // private final int yearStarted; // private final String name; // private final String email; // // public FinalSmallBenchmarkObject(long id, int yearStarted, String name, String email) { // this.id = id; // this.yearStarted = yearStarted; // this.name = name; // this.email = email; // } // // public long getId() { // return id; // } // public String getName() { // return name; // } // public String getEmail() { // return email; // } // // public int getYearStarted() { // return yearStarted; // } // // @Override // public String toString() { // return "FinalSmallBenchmarkObject [id=" + id + ", yearStarted=" // + yearStarted + ", name=" + name + ", email=" + email + "]"; // } // // // } // // Path: src/main/java/org/sfm/beans/SmallBenchmarkObject.java // @Entity // @Table(name="test_small_benchmark_object") // public class SmallBenchmarkObject { // // @Id // @RowMapperField(columnName="ID") // private long id; // // @RowMapperField(columnName="YEAR_STARTED") // private int yearStarted; // @RowMapperField(columnName = "NAME") // private String name; // @RowMapperField(columnName="EMAIL") // private String email; // // @Column(name="ID") // public long getId() { // return id; // } // public void setId(long id) { // this.id = id; // } // @Column(name="NAME") // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } // @Column(name="EMAIL") // public String getEmail() { // return email; // } // public void setEmail(String email) { // this.email = email; // } // // @Column(name="YEAR_STARTED") // public int getYearStarted() { // return yearStarted; // } // public void setYearStarted(int yearStarted) { // this.yearStarted = yearStarted; // } // @Override // public String toString() { // return "SmallBenchmarkObject [id=" + id + ", yearStarted=" // + yearStarted + ", name=" + name + ", email=" + email + "]"; // } // // // } // Path: src/main/java/org/sfm/benchmark/csv/CsvMapperBenchmark.java import java.io.*; import java.lang.reflect.Field; import java.util.List; import au.com.bytecode.opencsv.bean.ColumnPositionMappingStrategy; import org.apache.commons.io.FileUtils; import org.apache.commons.io.input.CharSequenceReader; import org.openjdk.jmh.annotations.*; import org.openjdk.jmh.infra.Blackhole; import org.sfm.beans.FinalSmallBenchmarkObject; import org.sfm.beans.SmallBenchmarkObject; import org.sfm.csv.CsvMapper; import org.sfm.csv.CsvMapperBuilder; import org.sfm.csv.CsvMapperFactory; import org.sfm.csv.CsvParser; import org.sfm.utils.RowHandler; import au.com.bytecode.opencsv.CSVReader; import au.com.bytecode.opencsv.bean.CsvToBean; import au.com.bytecode.opencsv.bean.HeaderColumnNameTranslateMappingStrategy; import com.fasterxml.jackson.databind.MappingIterator; import com.fasterxml.jackson.databind.ObjectReader; import com.fasterxml.jackson.dataformat.csv.CsvSchema; import com.univocity.parsers.common.ParsingContext; import com.univocity.parsers.common.processor.BeanProcessor; import com.univocity.parsers.csv.CsvParserSettings; package org.sfm.benchmark.csv; @State(Scope.Benchmark) public class CsvMapperBenchmark { private CsvMapper<SmallBenchmarkObject> mapper;
private CsvMapper<FinalSmallBenchmarkObject> finalMapper;
arnaudroger/orm-benchmark
src/main/java/org/sfm/benchmark/db/spring/RomaBenchmark.java
// Path: src/main/java/org/sfm/beans/SmallBenchmarkObject.java // @Entity // @Table(name="test_small_benchmark_object") // public class SmallBenchmarkObject { // // @Id // @RowMapperField(columnName="ID") // private long id; // // @RowMapperField(columnName="YEAR_STARTED") // private int yearStarted; // @RowMapperField(columnName = "NAME") // private String name; // @RowMapperField(columnName="EMAIL") // private String email; // // @Column(name="ID") // public long getId() { // return id; // } // public void setId(long id) { // this.id = id; // } // @Column(name="NAME") // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } // @Column(name="EMAIL") // public String getEmail() { // return email; // } // public void setEmail(String email) { // this.email = email; // } // // @Column(name="YEAR_STARTED") // public int getYearStarted() { // return yearStarted; // } // public void setYearStarted(int yearStarted) { // this.yearStarted = yearStarted; // } // @Override // public String toString() { // return "SmallBenchmarkObject [id=" + id + ", yearStarted=" // + yearStarted + ", name=" + name + ", email=" + email + "]"; // } // // // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/ConnectionParam.java // @State(Scope.Benchmark) // public class ConnectionParam { // // @Param(value="MOCK") // public DbTarget db; // // public DataSource dataSource; // // @Setup // public void init() throws SQLException, NamingException { // dataSource = ConnectionHelper.getDataSource(db); // // if (db != DbTarget.MOCK) { // Connection conn = dataSource.getConnection(); // try { // ConnectionHelper.createTableAndInsertData(conn); // } finally { // conn.close(); // } // } // } // // public Connection getConnection() throws SQLException { // return dataSource.getConnection(); // } // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/DbTarget.java // public enum DbTarget { // MOCK { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.MYSQL; // } // }, HSQLDB { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.HSQLDB; // } // }, MYSQL { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.MYSQL; // } // }; // // public abstract SQLDialect getSqlDialect(); // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/LimitParam.java // @State(Scope.Benchmark) // public class LimitParam { // @Param(value={"1", "10", "100", "1000", "10000", "100000", "1000000"}) // public int limit; // }
import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.infra.Blackhole; import org.sfm.beans.SmallBenchmarkObject; import org.sfm.benchmark.db.jmh.ConnectionParam; import org.sfm.benchmark.db.jmh.DbTarget; import org.sfm.benchmark.db.jmh.LimitParam; import org.springframework.jdbc.core.RowMapper; import javax.naming.NamingException;
package org.sfm.benchmark.db.spring; @State(Scope.Benchmark) public class RomaBenchmark {
// Path: src/main/java/org/sfm/beans/SmallBenchmarkObject.java // @Entity // @Table(name="test_small_benchmark_object") // public class SmallBenchmarkObject { // // @Id // @RowMapperField(columnName="ID") // private long id; // // @RowMapperField(columnName="YEAR_STARTED") // private int yearStarted; // @RowMapperField(columnName = "NAME") // private String name; // @RowMapperField(columnName="EMAIL") // private String email; // // @Column(name="ID") // public long getId() { // return id; // } // public void setId(long id) { // this.id = id; // } // @Column(name="NAME") // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } // @Column(name="EMAIL") // public String getEmail() { // return email; // } // public void setEmail(String email) { // this.email = email; // } // // @Column(name="YEAR_STARTED") // public int getYearStarted() { // return yearStarted; // } // public void setYearStarted(int yearStarted) { // this.yearStarted = yearStarted; // } // @Override // public String toString() { // return "SmallBenchmarkObject [id=" + id + ", yearStarted=" // + yearStarted + ", name=" + name + ", email=" + email + "]"; // } // // // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/ConnectionParam.java // @State(Scope.Benchmark) // public class ConnectionParam { // // @Param(value="MOCK") // public DbTarget db; // // public DataSource dataSource; // // @Setup // public void init() throws SQLException, NamingException { // dataSource = ConnectionHelper.getDataSource(db); // // if (db != DbTarget.MOCK) { // Connection conn = dataSource.getConnection(); // try { // ConnectionHelper.createTableAndInsertData(conn); // } finally { // conn.close(); // } // } // } // // public Connection getConnection() throws SQLException { // return dataSource.getConnection(); // } // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/DbTarget.java // public enum DbTarget { // MOCK { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.MYSQL; // } // }, HSQLDB { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.HSQLDB; // } // }, MYSQL { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.MYSQL; // } // }; // // public abstract SQLDialect getSqlDialect(); // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/LimitParam.java // @State(Scope.Benchmark) // public class LimitParam { // @Param(value={"1", "10", "100", "1000", "10000", "100000", "1000000"}) // public int limit; // } // Path: src/main/java/org/sfm/benchmark/db/spring/RomaBenchmark.java import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.infra.Blackhole; import org.sfm.beans.SmallBenchmarkObject; import org.sfm.benchmark.db.jmh.ConnectionParam; import org.sfm.benchmark.db.jmh.DbTarget; import org.sfm.benchmark.db.jmh.LimitParam; import org.springframework.jdbc.core.RowMapper; import javax.naming.NamingException; package org.sfm.benchmark.db.spring; @State(Scope.Benchmark) public class RomaBenchmark {
private RowMapper<SmallBenchmarkObject> mapper ;
arnaudroger/orm-benchmark
src/main/java/org/sfm/benchmark/db/spring/RomaBenchmark.java
// Path: src/main/java/org/sfm/beans/SmallBenchmarkObject.java // @Entity // @Table(name="test_small_benchmark_object") // public class SmallBenchmarkObject { // // @Id // @RowMapperField(columnName="ID") // private long id; // // @RowMapperField(columnName="YEAR_STARTED") // private int yearStarted; // @RowMapperField(columnName = "NAME") // private String name; // @RowMapperField(columnName="EMAIL") // private String email; // // @Column(name="ID") // public long getId() { // return id; // } // public void setId(long id) { // this.id = id; // } // @Column(name="NAME") // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } // @Column(name="EMAIL") // public String getEmail() { // return email; // } // public void setEmail(String email) { // this.email = email; // } // // @Column(name="YEAR_STARTED") // public int getYearStarted() { // return yearStarted; // } // public void setYearStarted(int yearStarted) { // this.yearStarted = yearStarted; // } // @Override // public String toString() { // return "SmallBenchmarkObject [id=" + id + ", yearStarted=" // + yearStarted + ", name=" + name + ", email=" + email + "]"; // } // // // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/ConnectionParam.java // @State(Scope.Benchmark) // public class ConnectionParam { // // @Param(value="MOCK") // public DbTarget db; // // public DataSource dataSource; // // @Setup // public void init() throws SQLException, NamingException { // dataSource = ConnectionHelper.getDataSource(db); // // if (db != DbTarget.MOCK) { // Connection conn = dataSource.getConnection(); // try { // ConnectionHelper.createTableAndInsertData(conn); // } finally { // conn.close(); // } // } // } // // public Connection getConnection() throws SQLException { // return dataSource.getConnection(); // } // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/DbTarget.java // public enum DbTarget { // MOCK { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.MYSQL; // } // }, HSQLDB { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.HSQLDB; // } // }, MYSQL { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.MYSQL; // } // }; // // public abstract SQLDialect getSqlDialect(); // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/LimitParam.java // @State(Scope.Benchmark) // public class LimitParam { // @Param(value={"1", "10", "100", "1000", "10000", "100000", "1000000"}) // public int limit; // }
import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.infra.Blackhole; import org.sfm.beans.SmallBenchmarkObject; import org.sfm.benchmark.db.jmh.ConnectionParam; import org.sfm.benchmark.db.jmh.DbTarget; import org.sfm.benchmark.db.jmh.LimitParam; import org.springframework.jdbc.core.RowMapper; import javax.naming.NamingException;
package org.sfm.benchmark.db.spring; @State(Scope.Benchmark) public class RomaBenchmark { private RowMapper<SmallBenchmarkObject> mapper ; @Setup public void init() { this.mapper = RomaMapperFactory.getRowMapper(); } @Benchmark
// Path: src/main/java/org/sfm/beans/SmallBenchmarkObject.java // @Entity // @Table(name="test_small_benchmark_object") // public class SmallBenchmarkObject { // // @Id // @RowMapperField(columnName="ID") // private long id; // // @RowMapperField(columnName="YEAR_STARTED") // private int yearStarted; // @RowMapperField(columnName = "NAME") // private String name; // @RowMapperField(columnName="EMAIL") // private String email; // // @Column(name="ID") // public long getId() { // return id; // } // public void setId(long id) { // this.id = id; // } // @Column(name="NAME") // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } // @Column(name="EMAIL") // public String getEmail() { // return email; // } // public void setEmail(String email) { // this.email = email; // } // // @Column(name="YEAR_STARTED") // public int getYearStarted() { // return yearStarted; // } // public void setYearStarted(int yearStarted) { // this.yearStarted = yearStarted; // } // @Override // public String toString() { // return "SmallBenchmarkObject [id=" + id + ", yearStarted=" // + yearStarted + ", name=" + name + ", email=" + email + "]"; // } // // // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/ConnectionParam.java // @State(Scope.Benchmark) // public class ConnectionParam { // // @Param(value="MOCK") // public DbTarget db; // // public DataSource dataSource; // // @Setup // public void init() throws SQLException, NamingException { // dataSource = ConnectionHelper.getDataSource(db); // // if (db != DbTarget.MOCK) { // Connection conn = dataSource.getConnection(); // try { // ConnectionHelper.createTableAndInsertData(conn); // } finally { // conn.close(); // } // } // } // // public Connection getConnection() throws SQLException { // return dataSource.getConnection(); // } // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/DbTarget.java // public enum DbTarget { // MOCK { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.MYSQL; // } // }, HSQLDB { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.HSQLDB; // } // }, MYSQL { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.MYSQL; // } // }; // // public abstract SQLDialect getSqlDialect(); // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/LimitParam.java // @State(Scope.Benchmark) // public class LimitParam { // @Param(value={"1", "10", "100", "1000", "10000", "100000", "1000000"}) // public int limit; // } // Path: src/main/java/org/sfm/benchmark/db/spring/RomaBenchmark.java import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.infra.Blackhole; import org.sfm.beans.SmallBenchmarkObject; import org.sfm.benchmark.db.jmh.ConnectionParam; import org.sfm.benchmark.db.jmh.DbTarget; import org.sfm.benchmark.db.jmh.LimitParam; import org.springframework.jdbc.core.RowMapper; import javax.naming.NamingException; package org.sfm.benchmark.db.spring; @State(Scope.Benchmark) public class RomaBenchmark { private RowMapper<SmallBenchmarkObject> mapper ; @Setup public void init() { this.mapper = RomaMapperFactory.getRowMapper(); } @Benchmark
public void testQuery(ConnectionParam connectionHolder, LimitParam limit, final Blackhole blackhole) throws Exception {
arnaudroger/orm-benchmark
src/main/java/org/sfm/benchmark/db/spring/RomaBenchmark.java
// Path: src/main/java/org/sfm/beans/SmallBenchmarkObject.java // @Entity // @Table(name="test_small_benchmark_object") // public class SmallBenchmarkObject { // // @Id // @RowMapperField(columnName="ID") // private long id; // // @RowMapperField(columnName="YEAR_STARTED") // private int yearStarted; // @RowMapperField(columnName = "NAME") // private String name; // @RowMapperField(columnName="EMAIL") // private String email; // // @Column(name="ID") // public long getId() { // return id; // } // public void setId(long id) { // this.id = id; // } // @Column(name="NAME") // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } // @Column(name="EMAIL") // public String getEmail() { // return email; // } // public void setEmail(String email) { // this.email = email; // } // // @Column(name="YEAR_STARTED") // public int getYearStarted() { // return yearStarted; // } // public void setYearStarted(int yearStarted) { // this.yearStarted = yearStarted; // } // @Override // public String toString() { // return "SmallBenchmarkObject [id=" + id + ", yearStarted=" // + yearStarted + ", name=" + name + ", email=" + email + "]"; // } // // // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/ConnectionParam.java // @State(Scope.Benchmark) // public class ConnectionParam { // // @Param(value="MOCK") // public DbTarget db; // // public DataSource dataSource; // // @Setup // public void init() throws SQLException, NamingException { // dataSource = ConnectionHelper.getDataSource(db); // // if (db != DbTarget.MOCK) { // Connection conn = dataSource.getConnection(); // try { // ConnectionHelper.createTableAndInsertData(conn); // } finally { // conn.close(); // } // } // } // // public Connection getConnection() throws SQLException { // return dataSource.getConnection(); // } // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/DbTarget.java // public enum DbTarget { // MOCK { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.MYSQL; // } // }, HSQLDB { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.HSQLDB; // } // }, MYSQL { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.MYSQL; // } // }; // // public abstract SQLDialect getSqlDialect(); // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/LimitParam.java // @State(Scope.Benchmark) // public class LimitParam { // @Param(value={"1", "10", "100", "1000", "10000", "100000", "1000000"}) // public int limit; // }
import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.infra.Blackhole; import org.sfm.beans.SmallBenchmarkObject; import org.sfm.benchmark.db.jmh.ConnectionParam; import org.sfm.benchmark.db.jmh.DbTarget; import org.sfm.benchmark.db.jmh.LimitParam; import org.springframework.jdbc.core.RowMapper; import javax.naming.NamingException;
package org.sfm.benchmark.db.spring; @State(Scope.Benchmark) public class RomaBenchmark { private RowMapper<SmallBenchmarkObject> mapper ; @Setup public void init() { this.mapper = RomaMapperFactory.getRowMapper(); } @Benchmark
// Path: src/main/java/org/sfm/beans/SmallBenchmarkObject.java // @Entity // @Table(name="test_small_benchmark_object") // public class SmallBenchmarkObject { // // @Id // @RowMapperField(columnName="ID") // private long id; // // @RowMapperField(columnName="YEAR_STARTED") // private int yearStarted; // @RowMapperField(columnName = "NAME") // private String name; // @RowMapperField(columnName="EMAIL") // private String email; // // @Column(name="ID") // public long getId() { // return id; // } // public void setId(long id) { // this.id = id; // } // @Column(name="NAME") // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } // @Column(name="EMAIL") // public String getEmail() { // return email; // } // public void setEmail(String email) { // this.email = email; // } // // @Column(name="YEAR_STARTED") // public int getYearStarted() { // return yearStarted; // } // public void setYearStarted(int yearStarted) { // this.yearStarted = yearStarted; // } // @Override // public String toString() { // return "SmallBenchmarkObject [id=" + id + ", yearStarted=" // + yearStarted + ", name=" + name + ", email=" + email + "]"; // } // // // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/ConnectionParam.java // @State(Scope.Benchmark) // public class ConnectionParam { // // @Param(value="MOCK") // public DbTarget db; // // public DataSource dataSource; // // @Setup // public void init() throws SQLException, NamingException { // dataSource = ConnectionHelper.getDataSource(db); // // if (db != DbTarget.MOCK) { // Connection conn = dataSource.getConnection(); // try { // ConnectionHelper.createTableAndInsertData(conn); // } finally { // conn.close(); // } // } // } // // public Connection getConnection() throws SQLException { // return dataSource.getConnection(); // } // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/DbTarget.java // public enum DbTarget { // MOCK { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.MYSQL; // } // }, HSQLDB { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.HSQLDB; // } // }, MYSQL { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.MYSQL; // } // }; // // public abstract SQLDialect getSqlDialect(); // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/LimitParam.java // @State(Scope.Benchmark) // public class LimitParam { // @Param(value={"1", "10", "100", "1000", "10000", "100000", "1000000"}) // public int limit; // } // Path: src/main/java/org/sfm/benchmark/db/spring/RomaBenchmark.java import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.infra.Blackhole; import org.sfm.beans.SmallBenchmarkObject; import org.sfm.benchmark.db.jmh.ConnectionParam; import org.sfm.benchmark.db.jmh.DbTarget; import org.sfm.benchmark.db.jmh.LimitParam; import org.springframework.jdbc.core.RowMapper; import javax.naming.NamingException; package org.sfm.benchmark.db.spring; @State(Scope.Benchmark) public class RomaBenchmark { private RowMapper<SmallBenchmarkObject> mapper ; @Setup public void init() { this.mapper = RomaMapperFactory.getRowMapper(); } @Benchmark
public void testQuery(ConnectionParam connectionHolder, LimitParam limit, final Blackhole blackhole) throws Exception {
arnaudroger/orm-benchmark
src/main/java/org/sfm/benchmark/db/spring/RomaBenchmark.java
// Path: src/main/java/org/sfm/beans/SmallBenchmarkObject.java // @Entity // @Table(name="test_small_benchmark_object") // public class SmallBenchmarkObject { // // @Id // @RowMapperField(columnName="ID") // private long id; // // @RowMapperField(columnName="YEAR_STARTED") // private int yearStarted; // @RowMapperField(columnName = "NAME") // private String name; // @RowMapperField(columnName="EMAIL") // private String email; // // @Column(name="ID") // public long getId() { // return id; // } // public void setId(long id) { // this.id = id; // } // @Column(name="NAME") // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } // @Column(name="EMAIL") // public String getEmail() { // return email; // } // public void setEmail(String email) { // this.email = email; // } // // @Column(name="YEAR_STARTED") // public int getYearStarted() { // return yearStarted; // } // public void setYearStarted(int yearStarted) { // this.yearStarted = yearStarted; // } // @Override // public String toString() { // return "SmallBenchmarkObject [id=" + id + ", yearStarted=" // + yearStarted + ", name=" + name + ", email=" + email + "]"; // } // // // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/ConnectionParam.java // @State(Scope.Benchmark) // public class ConnectionParam { // // @Param(value="MOCK") // public DbTarget db; // // public DataSource dataSource; // // @Setup // public void init() throws SQLException, NamingException { // dataSource = ConnectionHelper.getDataSource(db); // // if (db != DbTarget.MOCK) { // Connection conn = dataSource.getConnection(); // try { // ConnectionHelper.createTableAndInsertData(conn); // } finally { // conn.close(); // } // } // } // // public Connection getConnection() throws SQLException { // return dataSource.getConnection(); // } // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/DbTarget.java // public enum DbTarget { // MOCK { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.MYSQL; // } // }, HSQLDB { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.HSQLDB; // } // }, MYSQL { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.MYSQL; // } // }; // // public abstract SQLDialect getSqlDialect(); // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/LimitParam.java // @State(Scope.Benchmark) // public class LimitParam { // @Param(value={"1", "10", "100", "1000", "10000", "100000", "1000000"}) // public int limit; // }
import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.infra.Blackhole; import org.sfm.beans.SmallBenchmarkObject; import org.sfm.benchmark.db.jmh.ConnectionParam; import org.sfm.benchmark.db.jmh.DbTarget; import org.sfm.benchmark.db.jmh.LimitParam; import org.springframework.jdbc.core.RowMapper; import javax.naming.NamingException;
@Setup public void init() { this.mapper = RomaMapperFactory.getRowMapper(); } @Benchmark public void testQuery(ConnectionParam connectionHolder, LimitParam limit, final Blackhole blackhole) throws Exception { Connection conn = connectionHolder.getConnection(); try { PreparedStatement ps = conn.prepareStatement("SELECT id, name, email, year_started FROM test_small_benchmark_object LIMIT ?"); try { ps.setInt(1, limit.limit); ResultSet rs = ps.executeQuery(); int i = 0; while(rs.next()) { Object o = mapper.mapRow(rs, i); blackhole.consume(o); i++; } }finally { ps.close(); } } finally { conn.close(); } } public static void main(String[] args) throws SQLException, NamingException { ConnectionParam cp = new ConnectionParam();
// Path: src/main/java/org/sfm/beans/SmallBenchmarkObject.java // @Entity // @Table(name="test_small_benchmark_object") // public class SmallBenchmarkObject { // // @Id // @RowMapperField(columnName="ID") // private long id; // // @RowMapperField(columnName="YEAR_STARTED") // private int yearStarted; // @RowMapperField(columnName = "NAME") // private String name; // @RowMapperField(columnName="EMAIL") // private String email; // // @Column(name="ID") // public long getId() { // return id; // } // public void setId(long id) { // this.id = id; // } // @Column(name="NAME") // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } // @Column(name="EMAIL") // public String getEmail() { // return email; // } // public void setEmail(String email) { // this.email = email; // } // // @Column(name="YEAR_STARTED") // public int getYearStarted() { // return yearStarted; // } // public void setYearStarted(int yearStarted) { // this.yearStarted = yearStarted; // } // @Override // public String toString() { // return "SmallBenchmarkObject [id=" + id + ", yearStarted=" // + yearStarted + ", name=" + name + ", email=" + email + "]"; // } // // // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/ConnectionParam.java // @State(Scope.Benchmark) // public class ConnectionParam { // // @Param(value="MOCK") // public DbTarget db; // // public DataSource dataSource; // // @Setup // public void init() throws SQLException, NamingException { // dataSource = ConnectionHelper.getDataSource(db); // // if (db != DbTarget.MOCK) { // Connection conn = dataSource.getConnection(); // try { // ConnectionHelper.createTableAndInsertData(conn); // } finally { // conn.close(); // } // } // } // // public Connection getConnection() throws SQLException { // return dataSource.getConnection(); // } // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/DbTarget.java // public enum DbTarget { // MOCK { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.MYSQL; // } // }, HSQLDB { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.HSQLDB; // } // }, MYSQL { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.MYSQL; // } // }; // // public abstract SQLDialect getSqlDialect(); // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/LimitParam.java // @State(Scope.Benchmark) // public class LimitParam { // @Param(value={"1", "10", "100", "1000", "10000", "100000", "1000000"}) // public int limit; // } // Path: src/main/java/org/sfm/benchmark/db/spring/RomaBenchmark.java import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.infra.Blackhole; import org.sfm.beans.SmallBenchmarkObject; import org.sfm.benchmark.db.jmh.ConnectionParam; import org.sfm.benchmark.db.jmh.DbTarget; import org.sfm.benchmark.db.jmh.LimitParam; import org.springframework.jdbc.core.RowMapper; import javax.naming.NamingException; @Setup public void init() { this.mapper = RomaMapperFactory.getRowMapper(); } @Benchmark public void testQuery(ConnectionParam connectionHolder, LimitParam limit, final Blackhole blackhole) throws Exception { Connection conn = connectionHolder.getConnection(); try { PreparedStatement ps = conn.prepareStatement("SELECT id, name, email, year_started FROM test_small_benchmark_object LIMIT ?"); try { ps.setInt(1, limit.limit); ResultSet rs = ps.executeQuery(); int i = 0; while(rs.next()) { Object o = mapper.mapRow(rs, i); blackhole.consume(o); i++; } }finally { ps.close(); } } finally { conn.close(); } } public static void main(String[] args) throws SQLException, NamingException { ConnectionParam cp = new ConnectionParam();
cp.db = DbTarget.HSQLDB;
arnaudroger/orm-benchmark
src/main/java/org/sfm/benchmark/csv/CsvWriterTest.java
// Path: src/main/java/org/sfm/beans/SmallBenchmarkObject.java // @Entity // @Table(name="test_small_benchmark_object") // public class SmallBenchmarkObject { // // @Id // @RowMapperField(columnName="ID") // private long id; // // @RowMapperField(columnName="YEAR_STARTED") // private int yearStarted; // @RowMapperField(columnName = "NAME") // private String name; // @RowMapperField(columnName="EMAIL") // private String email; // // @Column(name="ID") // public long getId() { // return id; // } // public void setId(long id) { // this.id = id; // } // @Column(name="NAME") // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } // @Column(name="EMAIL") // public String getEmail() { // return email; // } // public void setEmail(String email) { // this.email = email; // } // // @Column(name="YEAR_STARTED") // public int getYearStarted() { // return yearStarted; // } // public void setYearStarted(int yearStarted) { // this.yearStarted = yearStarted; // } // @Override // public String toString() { // return "SmallBenchmarkObject [id=" + id + ", yearStarted=" // + yearStarted + ", name=" + name + ", email=" + email + "]"; // } // // // }
import com.fasterxml.jackson.databind.ObjectWriter; import com.fasterxml.jackson.dataformat.csv.CsvMapper; import com.fasterxml.jackson.dataformat.csv.CsvSchema; import com.univocity.parsers.common.processor.BeanWriterProcessor; import com.univocity.parsers.csv.CsvWriterSettings; import org.apache.commons.io.output.StringBuilderWriter; import org.openjdk.jmh.annotations.*; import org.sfm.beans.SmallBenchmarkObject; import org.sfm.csv.CsvWriter; import java.io.IOException;
package org.sfm.benchmark.csv; @State(Scope.Benchmark) public class CsvWriterTest { public static final int CAPACITY = 64;
// Path: src/main/java/org/sfm/beans/SmallBenchmarkObject.java // @Entity // @Table(name="test_small_benchmark_object") // public class SmallBenchmarkObject { // // @Id // @RowMapperField(columnName="ID") // private long id; // // @RowMapperField(columnName="YEAR_STARTED") // private int yearStarted; // @RowMapperField(columnName = "NAME") // private String name; // @RowMapperField(columnName="EMAIL") // private String email; // // @Column(name="ID") // public long getId() { // return id; // } // public void setId(long id) { // this.id = id; // } // @Column(name="NAME") // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } // @Column(name="EMAIL") // public String getEmail() { // return email; // } // public void setEmail(String email) { // this.email = email; // } // // @Column(name="YEAR_STARTED") // public int getYearStarted() { // return yearStarted; // } // public void setYearStarted(int yearStarted) { // this.yearStarted = yearStarted; // } // @Override // public String toString() { // return "SmallBenchmarkObject [id=" + id + ", yearStarted=" // + yearStarted + ", name=" + name + ", email=" + email + "]"; // } // // // } // Path: src/main/java/org/sfm/benchmark/csv/CsvWriterTest.java import com.fasterxml.jackson.databind.ObjectWriter; import com.fasterxml.jackson.dataformat.csv.CsvMapper; import com.fasterxml.jackson.dataformat.csv.CsvSchema; import com.univocity.parsers.common.processor.BeanWriterProcessor; import com.univocity.parsers.csv.CsvWriterSettings; import org.apache.commons.io.output.StringBuilderWriter; import org.openjdk.jmh.annotations.*; import org.sfm.beans.SmallBenchmarkObject; import org.sfm.csv.CsvWriter; import java.io.IOException; package org.sfm.benchmark.csv; @State(Scope.Benchmark) public class CsvWriterTest { public static final int CAPACITY = 64;
CsvWriter.CsvWriterDSL<SmallBenchmarkObject> dsl;
arnaudroger/orm-benchmark
src/main/java/org/sfm/benchmark/db/sfm/JdbcMapperStaticBenchmark.java
// Path: src/main/java/org/sfm/beans/SmallBenchmarkObject.java // @Entity // @Table(name="test_small_benchmark_object") // public class SmallBenchmarkObject { // // @Id // @RowMapperField(columnName="ID") // private long id; // // @RowMapperField(columnName="YEAR_STARTED") // private int yearStarted; // @RowMapperField(columnName = "NAME") // private String name; // @RowMapperField(columnName="EMAIL") // private String email; // // @Column(name="ID") // public long getId() { // return id; // } // public void setId(long id) { // this.id = id; // } // @Column(name="NAME") // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } // @Column(name="EMAIL") // public String getEmail() { // return email; // } // public void setEmail(String email) { // this.email = email; // } // // @Column(name="YEAR_STARTED") // public int getYearStarted() { // return yearStarted; // } // public void setYearStarted(int yearStarted) { // this.yearStarted = yearStarted; // } // @Override // public String toString() { // return "SmallBenchmarkObject [id=" + id + ", yearStarted=" // + yearStarted + ", name=" + name + ", email=" + email + "]"; // } // // // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/ConnectionParam.java // @State(Scope.Benchmark) // public class ConnectionParam { // // @Param(value="MOCK") // public DbTarget db; // // public DataSource dataSource; // // @Setup // public void init() throws SQLException, NamingException { // dataSource = ConnectionHelper.getDataSource(db); // // if (db != DbTarget.MOCK) { // Connection conn = dataSource.getConnection(); // try { // ConnectionHelper.createTableAndInsertData(conn); // } finally { // conn.close(); // } // } // } // // public Connection getConnection() throws SQLException { // return dataSource.getConnection(); // } // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/LimitParam.java // @State(Scope.Benchmark) // public class LimitParam { // @Param(value={"1", "10", "100", "1000", "10000", "100000", "1000000"}) // public int limit; // }
import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.infra.Blackhole; import org.sfm.beans.SmallBenchmarkObject; import org.sfm.benchmark.db.jmh.ConnectionParam; import org.sfm.benchmark.db.jmh.LimitParam; import org.sfm.jdbc.JdbcMapper; import org.sfm.jdbc.JdbcMapperFactory; import org.sfm.reflect.asm.AsmHelper; import org.sfm.utils.RowHandler;
package org.sfm.benchmark.db.sfm; @State(Scope.Benchmark) public class JdbcMapperStaticBenchmark { public static final String SELECT_BENCHMARK_OBJ_WITH_LIMIT = "SELECT id, name, email, year_started FROM test_small_benchmark_object LIMIT ?";
// Path: src/main/java/org/sfm/beans/SmallBenchmarkObject.java // @Entity // @Table(name="test_small_benchmark_object") // public class SmallBenchmarkObject { // // @Id // @RowMapperField(columnName="ID") // private long id; // // @RowMapperField(columnName="YEAR_STARTED") // private int yearStarted; // @RowMapperField(columnName = "NAME") // private String name; // @RowMapperField(columnName="EMAIL") // private String email; // // @Column(name="ID") // public long getId() { // return id; // } // public void setId(long id) { // this.id = id; // } // @Column(name="NAME") // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } // @Column(name="EMAIL") // public String getEmail() { // return email; // } // public void setEmail(String email) { // this.email = email; // } // // @Column(name="YEAR_STARTED") // public int getYearStarted() { // return yearStarted; // } // public void setYearStarted(int yearStarted) { // this.yearStarted = yearStarted; // } // @Override // public String toString() { // return "SmallBenchmarkObject [id=" + id + ", yearStarted=" // + yearStarted + ", name=" + name + ", email=" + email + "]"; // } // // // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/ConnectionParam.java // @State(Scope.Benchmark) // public class ConnectionParam { // // @Param(value="MOCK") // public DbTarget db; // // public DataSource dataSource; // // @Setup // public void init() throws SQLException, NamingException { // dataSource = ConnectionHelper.getDataSource(db); // // if (db != DbTarget.MOCK) { // Connection conn = dataSource.getConnection(); // try { // ConnectionHelper.createTableAndInsertData(conn); // } finally { // conn.close(); // } // } // } // // public Connection getConnection() throws SQLException { // return dataSource.getConnection(); // } // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/LimitParam.java // @State(Scope.Benchmark) // public class LimitParam { // @Param(value={"1", "10", "100", "1000", "10000", "100000", "1000000"}) // public int limit; // } // Path: src/main/java/org/sfm/benchmark/db/sfm/JdbcMapperStaticBenchmark.java import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.infra.Blackhole; import org.sfm.beans.SmallBenchmarkObject; import org.sfm.benchmark.db.jmh.ConnectionParam; import org.sfm.benchmark.db.jmh.LimitParam; import org.sfm.jdbc.JdbcMapper; import org.sfm.jdbc.JdbcMapperFactory; import org.sfm.reflect.asm.AsmHelper; import org.sfm.utils.RowHandler; package org.sfm.benchmark.db.sfm; @State(Scope.Benchmark) public class JdbcMapperStaticBenchmark { public static final String SELECT_BENCHMARK_OBJ_WITH_LIMIT = "SELECT id, name, email, year_started FROM test_small_benchmark_object LIMIT ?";
private JdbcMapper<SmallBenchmarkObject> mapper;
arnaudroger/orm-benchmark
src/main/java/org/sfm/benchmark/db/sfm/JdbcMapperStaticBenchmark.java
// Path: src/main/java/org/sfm/beans/SmallBenchmarkObject.java // @Entity // @Table(name="test_small_benchmark_object") // public class SmallBenchmarkObject { // // @Id // @RowMapperField(columnName="ID") // private long id; // // @RowMapperField(columnName="YEAR_STARTED") // private int yearStarted; // @RowMapperField(columnName = "NAME") // private String name; // @RowMapperField(columnName="EMAIL") // private String email; // // @Column(name="ID") // public long getId() { // return id; // } // public void setId(long id) { // this.id = id; // } // @Column(name="NAME") // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } // @Column(name="EMAIL") // public String getEmail() { // return email; // } // public void setEmail(String email) { // this.email = email; // } // // @Column(name="YEAR_STARTED") // public int getYearStarted() { // return yearStarted; // } // public void setYearStarted(int yearStarted) { // this.yearStarted = yearStarted; // } // @Override // public String toString() { // return "SmallBenchmarkObject [id=" + id + ", yearStarted=" // + yearStarted + ", name=" + name + ", email=" + email + "]"; // } // // // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/ConnectionParam.java // @State(Scope.Benchmark) // public class ConnectionParam { // // @Param(value="MOCK") // public DbTarget db; // // public DataSource dataSource; // // @Setup // public void init() throws SQLException, NamingException { // dataSource = ConnectionHelper.getDataSource(db); // // if (db != DbTarget.MOCK) { // Connection conn = dataSource.getConnection(); // try { // ConnectionHelper.createTableAndInsertData(conn); // } finally { // conn.close(); // } // } // } // // public Connection getConnection() throws SQLException { // return dataSource.getConnection(); // } // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/LimitParam.java // @State(Scope.Benchmark) // public class LimitParam { // @Param(value={"1", "10", "100", "1000", "10000", "100000", "1000000"}) // public int limit; // }
import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.infra.Blackhole; import org.sfm.beans.SmallBenchmarkObject; import org.sfm.benchmark.db.jmh.ConnectionParam; import org.sfm.benchmark.db.jmh.LimitParam; import org.sfm.jdbc.JdbcMapper; import org.sfm.jdbc.JdbcMapperFactory; import org.sfm.reflect.asm.AsmHelper; import org.sfm.utils.RowHandler;
package org.sfm.benchmark.db.sfm; @State(Scope.Benchmark) public class JdbcMapperStaticBenchmark { public static final String SELECT_BENCHMARK_OBJ_WITH_LIMIT = "SELECT id, name, email, year_started FROM test_small_benchmark_object LIMIT ?"; private JdbcMapper<SmallBenchmarkObject> mapper; @Param(value= {"true", "false"}) private boolean useAsm; @Setup public void init() { if (useAsm && ! AsmHelper.isAsmPresent()) { throw new RuntimeException("Asm not present or incompatible"); } mapper = JdbcMapperFactory.newInstance().useAsm(useAsm).newBuilder(SmallBenchmarkObject.class) .addMapping("id") .addMapping("name") .addMapping("email") .addMapping("year_started").mapper(); } @Benchmark
// Path: src/main/java/org/sfm/beans/SmallBenchmarkObject.java // @Entity // @Table(name="test_small_benchmark_object") // public class SmallBenchmarkObject { // // @Id // @RowMapperField(columnName="ID") // private long id; // // @RowMapperField(columnName="YEAR_STARTED") // private int yearStarted; // @RowMapperField(columnName = "NAME") // private String name; // @RowMapperField(columnName="EMAIL") // private String email; // // @Column(name="ID") // public long getId() { // return id; // } // public void setId(long id) { // this.id = id; // } // @Column(name="NAME") // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } // @Column(name="EMAIL") // public String getEmail() { // return email; // } // public void setEmail(String email) { // this.email = email; // } // // @Column(name="YEAR_STARTED") // public int getYearStarted() { // return yearStarted; // } // public void setYearStarted(int yearStarted) { // this.yearStarted = yearStarted; // } // @Override // public String toString() { // return "SmallBenchmarkObject [id=" + id + ", yearStarted=" // + yearStarted + ", name=" + name + ", email=" + email + "]"; // } // // // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/ConnectionParam.java // @State(Scope.Benchmark) // public class ConnectionParam { // // @Param(value="MOCK") // public DbTarget db; // // public DataSource dataSource; // // @Setup // public void init() throws SQLException, NamingException { // dataSource = ConnectionHelper.getDataSource(db); // // if (db != DbTarget.MOCK) { // Connection conn = dataSource.getConnection(); // try { // ConnectionHelper.createTableAndInsertData(conn); // } finally { // conn.close(); // } // } // } // // public Connection getConnection() throws SQLException { // return dataSource.getConnection(); // } // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/LimitParam.java // @State(Scope.Benchmark) // public class LimitParam { // @Param(value={"1", "10", "100", "1000", "10000", "100000", "1000000"}) // public int limit; // } // Path: src/main/java/org/sfm/benchmark/db/sfm/JdbcMapperStaticBenchmark.java import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.infra.Blackhole; import org.sfm.beans.SmallBenchmarkObject; import org.sfm.benchmark.db.jmh.ConnectionParam; import org.sfm.benchmark.db.jmh.LimitParam; import org.sfm.jdbc.JdbcMapper; import org.sfm.jdbc.JdbcMapperFactory; import org.sfm.reflect.asm.AsmHelper; import org.sfm.utils.RowHandler; package org.sfm.benchmark.db.sfm; @State(Scope.Benchmark) public class JdbcMapperStaticBenchmark { public static final String SELECT_BENCHMARK_OBJ_WITH_LIMIT = "SELECT id, name, email, year_started FROM test_small_benchmark_object LIMIT ?"; private JdbcMapper<SmallBenchmarkObject> mapper; @Param(value= {"true", "false"}) private boolean useAsm; @Setup public void init() { if (useAsm && ! AsmHelper.isAsmPresent()) { throw new RuntimeException("Asm not present or incompatible"); } mapper = JdbcMapperFactory.newInstance().useAsm(useAsm).newBuilder(SmallBenchmarkObject.class) .addMapping("id") .addMapping("name") .addMapping("email") .addMapping("year_started").mapper(); } @Benchmark
public void testQuery(ConnectionParam connectionHolder, LimitParam limit, final Blackhole blackhole) throws Exception {
arnaudroger/orm-benchmark
src/main/java/org/sfm/benchmark/db/sfm/JdbcMapperStaticBenchmark.java
// Path: src/main/java/org/sfm/beans/SmallBenchmarkObject.java // @Entity // @Table(name="test_small_benchmark_object") // public class SmallBenchmarkObject { // // @Id // @RowMapperField(columnName="ID") // private long id; // // @RowMapperField(columnName="YEAR_STARTED") // private int yearStarted; // @RowMapperField(columnName = "NAME") // private String name; // @RowMapperField(columnName="EMAIL") // private String email; // // @Column(name="ID") // public long getId() { // return id; // } // public void setId(long id) { // this.id = id; // } // @Column(name="NAME") // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } // @Column(name="EMAIL") // public String getEmail() { // return email; // } // public void setEmail(String email) { // this.email = email; // } // // @Column(name="YEAR_STARTED") // public int getYearStarted() { // return yearStarted; // } // public void setYearStarted(int yearStarted) { // this.yearStarted = yearStarted; // } // @Override // public String toString() { // return "SmallBenchmarkObject [id=" + id + ", yearStarted=" // + yearStarted + ", name=" + name + ", email=" + email + "]"; // } // // // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/ConnectionParam.java // @State(Scope.Benchmark) // public class ConnectionParam { // // @Param(value="MOCK") // public DbTarget db; // // public DataSource dataSource; // // @Setup // public void init() throws SQLException, NamingException { // dataSource = ConnectionHelper.getDataSource(db); // // if (db != DbTarget.MOCK) { // Connection conn = dataSource.getConnection(); // try { // ConnectionHelper.createTableAndInsertData(conn); // } finally { // conn.close(); // } // } // } // // public Connection getConnection() throws SQLException { // return dataSource.getConnection(); // } // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/LimitParam.java // @State(Scope.Benchmark) // public class LimitParam { // @Param(value={"1", "10", "100", "1000", "10000", "100000", "1000000"}) // public int limit; // }
import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.infra.Blackhole; import org.sfm.beans.SmallBenchmarkObject; import org.sfm.benchmark.db.jmh.ConnectionParam; import org.sfm.benchmark.db.jmh.LimitParam; import org.sfm.jdbc.JdbcMapper; import org.sfm.jdbc.JdbcMapperFactory; import org.sfm.reflect.asm.AsmHelper; import org.sfm.utils.RowHandler;
package org.sfm.benchmark.db.sfm; @State(Scope.Benchmark) public class JdbcMapperStaticBenchmark { public static final String SELECT_BENCHMARK_OBJ_WITH_LIMIT = "SELECT id, name, email, year_started FROM test_small_benchmark_object LIMIT ?"; private JdbcMapper<SmallBenchmarkObject> mapper; @Param(value= {"true", "false"}) private boolean useAsm; @Setup public void init() { if (useAsm && ! AsmHelper.isAsmPresent()) { throw new RuntimeException("Asm not present or incompatible"); } mapper = JdbcMapperFactory.newInstance().useAsm(useAsm).newBuilder(SmallBenchmarkObject.class) .addMapping("id") .addMapping("name") .addMapping("email") .addMapping("year_started").mapper(); } @Benchmark
// Path: src/main/java/org/sfm/beans/SmallBenchmarkObject.java // @Entity // @Table(name="test_small_benchmark_object") // public class SmallBenchmarkObject { // // @Id // @RowMapperField(columnName="ID") // private long id; // // @RowMapperField(columnName="YEAR_STARTED") // private int yearStarted; // @RowMapperField(columnName = "NAME") // private String name; // @RowMapperField(columnName="EMAIL") // private String email; // // @Column(name="ID") // public long getId() { // return id; // } // public void setId(long id) { // this.id = id; // } // @Column(name="NAME") // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } // @Column(name="EMAIL") // public String getEmail() { // return email; // } // public void setEmail(String email) { // this.email = email; // } // // @Column(name="YEAR_STARTED") // public int getYearStarted() { // return yearStarted; // } // public void setYearStarted(int yearStarted) { // this.yearStarted = yearStarted; // } // @Override // public String toString() { // return "SmallBenchmarkObject [id=" + id + ", yearStarted=" // + yearStarted + ", name=" + name + ", email=" + email + "]"; // } // // // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/ConnectionParam.java // @State(Scope.Benchmark) // public class ConnectionParam { // // @Param(value="MOCK") // public DbTarget db; // // public DataSource dataSource; // // @Setup // public void init() throws SQLException, NamingException { // dataSource = ConnectionHelper.getDataSource(db); // // if (db != DbTarget.MOCK) { // Connection conn = dataSource.getConnection(); // try { // ConnectionHelper.createTableAndInsertData(conn); // } finally { // conn.close(); // } // } // } // // public Connection getConnection() throws SQLException { // return dataSource.getConnection(); // } // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/LimitParam.java // @State(Scope.Benchmark) // public class LimitParam { // @Param(value={"1", "10", "100", "1000", "10000", "100000", "1000000"}) // public int limit; // } // Path: src/main/java/org/sfm/benchmark/db/sfm/JdbcMapperStaticBenchmark.java import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.infra.Blackhole; import org.sfm.beans.SmallBenchmarkObject; import org.sfm.benchmark.db.jmh.ConnectionParam; import org.sfm.benchmark.db.jmh.LimitParam; import org.sfm.jdbc.JdbcMapper; import org.sfm.jdbc.JdbcMapperFactory; import org.sfm.reflect.asm.AsmHelper; import org.sfm.utils.RowHandler; package org.sfm.benchmark.db.sfm; @State(Scope.Benchmark) public class JdbcMapperStaticBenchmark { public static final String SELECT_BENCHMARK_OBJ_WITH_LIMIT = "SELECT id, name, email, year_started FROM test_small_benchmark_object LIMIT ?"; private JdbcMapper<SmallBenchmarkObject> mapper; @Param(value= {"true", "false"}) private boolean useAsm; @Setup public void init() { if (useAsm && ! AsmHelper.isAsmPresent()) { throw new RuntimeException("Asm not present or incompatible"); } mapper = JdbcMapperFactory.newInstance().useAsm(useAsm).newBuilder(SmallBenchmarkObject.class) .addMapping("id") .addMapping("name") .addMapping("email") .addMapping("year_started").mapper(); } @Benchmark
public void testQuery(ConnectionParam connectionHolder, LimitParam limit, final Blackhole blackhole) throws Exception {
arnaudroger/orm-benchmark
src/main/java/org/sfm/benchmark/csv/ObjectSizeSfmCsvMapperBenchmark.java
// Path: src/main/java/org/sfm/benchmark/db/sfm/AsmSatus.java // public enum AsmSatus { // FULL_ASM, PARTIAL_ASM, NO_ASM; // }
import com.fasterxml.jackson.dataformat.csv.CsvSchema; import org.openjdk.jmh.annotations.*; import org.openjdk.jmh.infra.Blackhole; import org.sfm.benchmark.db.sfm.AsmSatus; import org.sfm.csv.CsvMapper; import org.sfm.csv.CsvMapperBuilder; import org.sfm.csv.CsvMapperFactory; import org.sfm.csv.CsvParser; import org.sfm.utils.RowHandler; import java.io.*;
package org.sfm.benchmark.csv; @State(Scope.Benchmark) public class ObjectSizeSfmCsvMapperBenchmark { private CsvMapper<?> mapper; private File file; @Param(value = { "2", "4", "8", "16", "32", "64", "128", "256", "512", "1024", "2048" , "4096", "8192" }) private int objectSize; @Param(value= {"FULL_ASM", "PARTIAL_ASM", "NO_ASM"})
// Path: src/main/java/org/sfm/benchmark/db/sfm/AsmSatus.java // public enum AsmSatus { // FULL_ASM, PARTIAL_ASM, NO_ASM; // } // Path: src/main/java/org/sfm/benchmark/csv/ObjectSizeSfmCsvMapperBenchmark.java import com.fasterxml.jackson.dataformat.csv.CsvSchema; import org.openjdk.jmh.annotations.*; import org.openjdk.jmh.infra.Blackhole; import org.sfm.benchmark.db.sfm.AsmSatus; import org.sfm.csv.CsvMapper; import org.sfm.csv.CsvMapperBuilder; import org.sfm.csv.CsvMapperFactory; import org.sfm.csv.CsvParser; import org.sfm.utils.RowHandler; import java.io.*; package org.sfm.benchmark.csv; @State(Scope.Benchmark) public class ObjectSizeSfmCsvMapperBenchmark { private CsvMapper<?> mapper; private File file; @Param(value = { "2", "4", "8", "16", "32", "64", "128", "256", "512", "1024", "2048" , "4096", "8192" }) private int objectSize; @Param(value= {"FULL_ASM", "PARTIAL_ASM", "NO_ASM"})
private AsmSatus useAsm;
arnaudroger/orm-benchmark
src/main/java/org/sfm/benchmark/db/sfm/JdbcMapperDynamicBenchmark.java
// Path: src/main/java/org/sfm/beans/SmallBenchmarkObject.java // @Entity // @Table(name="test_small_benchmark_object") // public class SmallBenchmarkObject { // // @Id // @RowMapperField(columnName="ID") // private long id; // // @RowMapperField(columnName="YEAR_STARTED") // private int yearStarted; // @RowMapperField(columnName = "NAME") // private String name; // @RowMapperField(columnName="EMAIL") // private String email; // // @Column(name="ID") // public long getId() { // return id; // } // public void setId(long id) { // this.id = id; // } // @Column(name="NAME") // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } // @Column(name="EMAIL") // public String getEmail() { // return email; // } // public void setEmail(String email) { // this.email = email; // } // // @Column(name="YEAR_STARTED") // public int getYearStarted() { // return yearStarted; // } // public void setYearStarted(int yearStarted) { // this.yearStarted = yearStarted; // } // @Override // public String toString() { // return "SmallBenchmarkObject [id=" + id + ", yearStarted=" // + yearStarted + ", name=" + name + ", email=" + email + "]"; // } // // // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/ConnectionParam.java // @State(Scope.Benchmark) // public class ConnectionParam { // // @Param(value="MOCK") // public DbTarget db; // // public DataSource dataSource; // // @Setup // public void init() throws SQLException, NamingException { // dataSource = ConnectionHelper.getDataSource(db); // // if (db != DbTarget.MOCK) { // Connection conn = dataSource.getConnection(); // try { // ConnectionHelper.createTableAndInsertData(conn); // } finally { // conn.close(); // } // } // } // // public Connection getConnection() throws SQLException { // return dataSource.getConnection(); // } // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/DbTarget.java // public enum DbTarget { // MOCK { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.MYSQL; // } // }, HSQLDB { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.HSQLDB; // } // }, MYSQL { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.MYSQL; // } // }; // // public abstract SQLDialect getSqlDialect(); // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/LimitParam.java // @State(Scope.Benchmark) // public class LimitParam { // @Param(value={"1", "10", "100", "1000", "10000", "100000", "1000000"}) // public int limit; // }
import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import javax.naming.NamingException; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.infra.Blackhole; import org.sfm.beans.SmallBenchmarkObject; import org.sfm.benchmark.db.jmh.ConnectionParam; import org.sfm.benchmark.db.jmh.DbTarget; import org.sfm.benchmark.db.jmh.LimitParam; import org.sfm.jdbc.JdbcMapper; import org.sfm.jdbc.JdbcMapperFactory; import org.sfm.reflect.asm.AsmHelper; import org.sfm.utils.RowHandler;
}finally { conn.close(); } } @Benchmark public void testQueryForEach(ConnectionParam connectionParam, LimitParam limitParam, final Blackhole blackhole) throws Exception { Connection conn = connectionParam.getConnection(); try { PreparedStatement ps = conn.prepareStatement(JdbcMapperStaticBenchmark.SELECT_BENCHMARK_OBJ_WITH_LIMIT); try { ps.setInt(1, limitParam.limit); ResultSet rs = ps.executeQuery(); mapper.forEach(rs, new RowHandler<SmallBenchmarkObject>() { @Override public void handle(SmallBenchmarkObject smallBenchmarkObject) throws Exception { blackhole.consume(smallBenchmarkObject); } }); }finally { ps.close(); } }finally { conn.close(); } } public static void main(String[] args) throws SQLException, NamingException { ConnectionParam connectionParam = new ConnectionParam();
// Path: src/main/java/org/sfm/beans/SmallBenchmarkObject.java // @Entity // @Table(name="test_small_benchmark_object") // public class SmallBenchmarkObject { // // @Id // @RowMapperField(columnName="ID") // private long id; // // @RowMapperField(columnName="YEAR_STARTED") // private int yearStarted; // @RowMapperField(columnName = "NAME") // private String name; // @RowMapperField(columnName="EMAIL") // private String email; // // @Column(name="ID") // public long getId() { // return id; // } // public void setId(long id) { // this.id = id; // } // @Column(name="NAME") // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } // @Column(name="EMAIL") // public String getEmail() { // return email; // } // public void setEmail(String email) { // this.email = email; // } // // @Column(name="YEAR_STARTED") // public int getYearStarted() { // return yearStarted; // } // public void setYearStarted(int yearStarted) { // this.yearStarted = yearStarted; // } // @Override // public String toString() { // return "SmallBenchmarkObject [id=" + id + ", yearStarted=" // + yearStarted + ", name=" + name + ", email=" + email + "]"; // } // // // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/ConnectionParam.java // @State(Scope.Benchmark) // public class ConnectionParam { // // @Param(value="MOCK") // public DbTarget db; // // public DataSource dataSource; // // @Setup // public void init() throws SQLException, NamingException { // dataSource = ConnectionHelper.getDataSource(db); // // if (db != DbTarget.MOCK) { // Connection conn = dataSource.getConnection(); // try { // ConnectionHelper.createTableAndInsertData(conn); // } finally { // conn.close(); // } // } // } // // public Connection getConnection() throws SQLException { // return dataSource.getConnection(); // } // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/DbTarget.java // public enum DbTarget { // MOCK { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.MYSQL; // } // }, HSQLDB { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.HSQLDB; // } // }, MYSQL { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.MYSQL; // } // }; // // public abstract SQLDialect getSqlDialect(); // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/LimitParam.java // @State(Scope.Benchmark) // public class LimitParam { // @Param(value={"1", "10", "100", "1000", "10000", "100000", "1000000"}) // public int limit; // } // Path: src/main/java/org/sfm/benchmark/db/sfm/JdbcMapperDynamicBenchmark.java import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import javax.naming.NamingException; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.infra.Blackhole; import org.sfm.beans.SmallBenchmarkObject; import org.sfm.benchmark.db.jmh.ConnectionParam; import org.sfm.benchmark.db.jmh.DbTarget; import org.sfm.benchmark.db.jmh.LimitParam; import org.sfm.jdbc.JdbcMapper; import org.sfm.jdbc.JdbcMapperFactory; import org.sfm.reflect.asm.AsmHelper; import org.sfm.utils.RowHandler; }finally { conn.close(); } } @Benchmark public void testQueryForEach(ConnectionParam connectionParam, LimitParam limitParam, final Blackhole blackhole) throws Exception { Connection conn = connectionParam.getConnection(); try { PreparedStatement ps = conn.prepareStatement(JdbcMapperStaticBenchmark.SELECT_BENCHMARK_OBJ_WITH_LIMIT); try { ps.setInt(1, limitParam.limit); ResultSet rs = ps.executeQuery(); mapper.forEach(rs, new RowHandler<SmallBenchmarkObject>() { @Override public void handle(SmallBenchmarkObject smallBenchmarkObject) throws Exception { blackhole.consume(smallBenchmarkObject); } }); }finally { ps.close(); } }finally { conn.close(); } } public static void main(String[] args) throws SQLException, NamingException { ConnectionParam connectionParam = new ConnectionParam();
connectionParam.db = DbTarget.HSQLDB;
arnaudroger/orm-benchmark
src/main/java/org/sfm/benchmark/db/ibatis/MyBatisBenchmark.java
// Path: src/main/java/org/sfm/benchmark/db/jmh/ConnectionParam.java // @State(Scope.Benchmark) // public class ConnectionParam { // // @Param(value="MOCK") // public DbTarget db; // // public DataSource dataSource; // // @Setup // public void init() throws SQLException, NamingException { // dataSource = ConnectionHelper.getDataSource(db); // // if (db != DbTarget.MOCK) { // Connection conn = dataSource.getConnection(); // try { // ConnectionHelper.createTableAndInsertData(conn); // } finally { // conn.close(); // } // } // } // // public Connection getConnection() throws SQLException { // return dataSource.getConnection(); // } // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/DbTarget.java // public enum DbTarget { // MOCK { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.MYSQL; // } // }, HSQLDB { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.HSQLDB; // } // }, MYSQL { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.MYSQL; // } // }; // // public abstract SQLDialect getSqlDialect(); // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/LimitParam.java // @State(Scope.Benchmark) // public class LimitParam { // @Param(value={"1", "10", "100", "1000", "10000", "100000", "1000000"}) // public int limit; // }
import java.sql.SQLException; import org.apache.ibatis.session.ResultContext; import org.apache.ibatis.session.ResultHandler; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.infra.Blackhole; import org.sfm.benchmark.db.jmh.ConnectionParam; import org.sfm.benchmark.db.jmh.DbTarget; import org.sfm.benchmark.db.jmh.LimitParam;
package org.sfm.benchmark.db.ibatis; @State(Scope.Benchmark) public class MyBatisBenchmark { private SqlSessionFactory sqlSessionFactory; @Param(value="MOCK")
// Path: src/main/java/org/sfm/benchmark/db/jmh/ConnectionParam.java // @State(Scope.Benchmark) // public class ConnectionParam { // // @Param(value="MOCK") // public DbTarget db; // // public DataSource dataSource; // // @Setup // public void init() throws SQLException, NamingException { // dataSource = ConnectionHelper.getDataSource(db); // // if (db != DbTarget.MOCK) { // Connection conn = dataSource.getConnection(); // try { // ConnectionHelper.createTableAndInsertData(conn); // } finally { // conn.close(); // } // } // } // // public Connection getConnection() throws SQLException { // return dataSource.getConnection(); // } // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/DbTarget.java // public enum DbTarget { // MOCK { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.MYSQL; // } // }, HSQLDB { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.HSQLDB; // } // }, MYSQL { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.MYSQL; // } // }; // // public abstract SQLDialect getSqlDialect(); // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/LimitParam.java // @State(Scope.Benchmark) // public class LimitParam { // @Param(value={"1", "10", "100", "1000", "10000", "100000", "1000000"}) // public int limit; // } // Path: src/main/java/org/sfm/benchmark/db/ibatis/MyBatisBenchmark.java import java.sql.SQLException; import org.apache.ibatis.session.ResultContext; import org.apache.ibatis.session.ResultHandler; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.infra.Blackhole; import org.sfm.benchmark.db.jmh.ConnectionParam; import org.sfm.benchmark.db.jmh.DbTarget; import org.sfm.benchmark.db.jmh.LimitParam; package org.sfm.benchmark.db.ibatis; @State(Scope.Benchmark) public class MyBatisBenchmark { private SqlSessionFactory sqlSessionFactory; @Param(value="MOCK")
DbTarget db;
arnaudroger/orm-benchmark
src/main/java/org/sfm/benchmark/db/ibatis/MyBatisBenchmark.java
// Path: src/main/java/org/sfm/benchmark/db/jmh/ConnectionParam.java // @State(Scope.Benchmark) // public class ConnectionParam { // // @Param(value="MOCK") // public DbTarget db; // // public DataSource dataSource; // // @Setup // public void init() throws SQLException, NamingException { // dataSource = ConnectionHelper.getDataSource(db); // // if (db != DbTarget.MOCK) { // Connection conn = dataSource.getConnection(); // try { // ConnectionHelper.createTableAndInsertData(conn); // } finally { // conn.close(); // } // } // } // // public Connection getConnection() throws SQLException { // return dataSource.getConnection(); // } // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/DbTarget.java // public enum DbTarget { // MOCK { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.MYSQL; // } // }, HSQLDB { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.HSQLDB; // } // }, MYSQL { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.MYSQL; // } // }; // // public abstract SQLDialect getSqlDialect(); // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/LimitParam.java // @State(Scope.Benchmark) // public class LimitParam { // @Param(value={"1", "10", "100", "1000", "10000", "100000", "1000000"}) // public int limit; // }
import java.sql.SQLException; import org.apache.ibatis.session.ResultContext; import org.apache.ibatis.session.ResultHandler; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.infra.Blackhole; import org.sfm.benchmark.db.jmh.ConnectionParam; import org.sfm.benchmark.db.jmh.DbTarget; import org.sfm.benchmark.db.jmh.LimitParam;
package org.sfm.benchmark.db.ibatis; @State(Scope.Benchmark) public class MyBatisBenchmark { private SqlSessionFactory sqlSessionFactory; @Param(value="MOCK") DbTarget db; @Setup public void init() throws Exception {
// Path: src/main/java/org/sfm/benchmark/db/jmh/ConnectionParam.java // @State(Scope.Benchmark) // public class ConnectionParam { // // @Param(value="MOCK") // public DbTarget db; // // public DataSource dataSource; // // @Setup // public void init() throws SQLException, NamingException { // dataSource = ConnectionHelper.getDataSource(db); // // if (db != DbTarget.MOCK) { // Connection conn = dataSource.getConnection(); // try { // ConnectionHelper.createTableAndInsertData(conn); // } finally { // conn.close(); // } // } // } // // public Connection getConnection() throws SQLException { // return dataSource.getConnection(); // } // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/DbTarget.java // public enum DbTarget { // MOCK { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.MYSQL; // } // }, HSQLDB { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.HSQLDB; // } // }, MYSQL { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.MYSQL; // } // }; // // public abstract SQLDialect getSqlDialect(); // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/LimitParam.java // @State(Scope.Benchmark) // public class LimitParam { // @Param(value={"1", "10", "100", "1000", "10000", "100000", "1000000"}) // public int limit; // } // Path: src/main/java/org/sfm/benchmark/db/ibatis/MyBatisBenchmark.java import java.sql.SQLException; import org.apache.ibatis.session.ResultContext; import org.apache.ibatis.session.ResultHandler; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.infra.Blackhole; import org.sfm.benchmark.db.jmh.ConnectionParam; import org.sfm.benchmark.db.jmh.DbTarget; import org.sfm.benchmark.db.jmh.LimitParam; package org.sfm.benchmark.db.ibatis; @State(Scope.Benchmark) public class MyBatisBenchmark { private SqlSessionFactory sqlSessionFactory; @Param(value="MOCK") DbTarget db; @Setup public void init() throws Exception {
ConnectionParam connParam = new ConnectionParam();
arnaudroger/orm-benchmark
src/main/java/org/sfm/benchmark/db/ibatis/MyBatisBenchmark.java
// Path: src/main/java/org/sfm/benchmark/db/jmh/ConnectionParam.java // @State(Scope.Benchmark) // public class ConnectionParam { // // @Param(value="MOCK") // public DbTarget db; // // public DataSource dataSource; // // @Setup // public void init() throws SQLException, NamingException { // dataSource = ConnectionHelper.getDataSource(db); // // if (db != DbTarget.MOCK) { // Connection conn = dataSource.getConnection(); // try { // ConnectionHelper.createTableAndInsertData(conn); // } finally { // conn.close(); // } // } // } // // public Connection getConnection() throws SQLException { // return dataSource.getConnection(); // } // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/DbTarget.java // public enum DbTarget { // MOCK { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.MYSQL; // } // }, HSQLDB { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.HSQLDB; // } // }, MYSQL { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.MYSQL; // } // }; // // public abstract SQLDialect getSqlDialect(); // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/LimitParam.java // @State(Scope.Benchmark) // public class LimitParam { // @Param(value={"1", "10", "100", "1000", "10000", "100000", "1000000"}) // public int limit; // }
import java.sql.SQLException; import org.apache.ibatis.session.ResultContext; import org.apache.ibatis.session.ResultHandler; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.infra.Blackhole; import org.sfm.benchmark.db.jmh.ConnectionParam; import org.sfm.benchmark.db.jmh.DbTarget; import org.sfm.benchmark.db.jmh.LimitParam;
package org.sfm.benchmark.db.ibatis; @State(Scope.Benchmark) public class MyBatisBenchmark { private SqlSessionFactory sqlSessionFactory; @Param(value="MOCK") DbTarget db; @Setup public void init() throws Exception { ConnectionParam connParam = new ConnectionParam(); connParam.db = db; connParam.init(); this.sqlSessionFactory = SqlSessionFact.getSqlSessionFactory(connParam); } @Benchmark
// Path: src/main/java/org/sfm/benchmark/db/jmh/ConnectionParam.java // @State(Scope.Benchmark) // public class ConnectionParam { // // @Param(value="MOCK") // public DbTarget db; // // public DataSource dataSource; // // @Setup // public void init() throws SQLException, NamingException { // dataSource = ConnectionHelper.getDataSource(db); // // if (db != DbTarget.MOCK) { // Connection conn = dataSource.getConnection(); // try { // ConnectionHelper.createTableAndInsertData(conn); // } finally { // conn.close(); // } // } // } // // public Connection getConnection() throws SQLException { // return dataSource.getConnection(); // } // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/DbTarget.java // public enum DbTarget { // MOCK { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.MYSQL; // } // }, HSQLDB { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.HSQLDB; // } // }, MYSQL { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.MYSQL; // } // }; // // public abstract SQLDialect getSqlDialect(); // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/LimitParam.java // @State(Scope.Benchmark) // public class LimitParam { // @Param(value={"1", "10", "100", "1000", "10000", "100000", "1000000"}) // public int limit; // } // Path: src/main/java/org/sfm/benchmark/db/ibatis/MyBatisBenchmark.java import java.sql.SQLException; import org.apache.ibatis.session.ResultContext; import org.apache.ibatis.session.ResultHandler; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.infra.Blackhole; import org.sfm.benchmark.db.jmh.ConnectionParam; import org.sfm.benchmark.db.jmh.DbTarget; import org.sfm.benchmark.db.jmh.LimitParam; package org.sfm.benchmark.db.ibatis; @State(Scope.Benchmark) public class MyBatisBenchmark { private SqlSessionFactory sqlSessionFactory; @Param(value="MOCK") DbTarget db; @Setup public void init() throws Exception { ConnectionParam connParam = new ConnectionParam(); connParam.db = db; connParam.init(); this.sqlSessionFactory = SqlSessionFact.getSqlSessionFactory(connParam); } @Benchmark
public void testQuery(LimitParam limit, final Blackhole blackhole) throws Exception {
arnaudroger/orm-benchmark
src/main/java/org/sfm/benchmark/db/hibernate/HibernateStatefullBenchmark.java
// Path: src/main/java/org/sfm/benchmark/db/jmh/ConnectionParam.java // @State(Scope.Benchmark) // public class ConnectionParam { // // @Param(value="MOCK") // public DbTarget db; // // public DataSource dataSource; // // @Setup // public void init() throws SQLException, NamingException { // dataSource = ConnectionHelper.getDataSource(db); // // if (db != DbTarget.MOCK) { // Connection conn = dataSource.getConnection(); // try { // ConnectionHelper.createTableAndInsertData(conn); // } finally { // conn.close(); // } // } // } // // public Connection getConnection() throws SQLException { // return dataSource.getConnection(); // } // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/DbTarget.java // public enum DbTarget { // MOCK { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.MYSQL; // } // }, HSQLDB { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.HSQLDB; // } // }, MYSQL { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.MYSQL; // } // }; // // public abstract SQLDialect getSqlDialect(); // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/LimitParam.java // @State(Scope.Benchmark) // public class LimitParam { // @Param(value={"1", "10", "100", "1000", "10000", "100000", "1000000"}) // public int limit; // }
import java.sql.SQLException; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.infra.Blackhole; import org.sfm.benchmark.db.jmh.ConnectionParam; import org.sfm.benchmark.db.jmh.DbTarget; import org.sfm.benchmark.db.jmh.LimitParam;
package org.sfm.benchmark.db.hibernate; @State(Scope.Benchmark) public class HibernateStatefullBenchmark { private SessionFactory sf; @Param(value="MOCK")
// Path: src/main/java/org/sfm/benchmark/db/jmh/ConnectionParam.java // @State(Scope.Benchmark) // public class ConnectionParam { // // @Param(value="MOCK") // public DbTarget db; // // public DataSource dataSource; // // @Setup // public void init() throws SQLException, NamingException { // dataSource = ConnectionHelper.getDataSource(db); // // if (db != DbTarget.MOCK) { // Connection conn = dataSource.getConnection(); // try { // ConnectionHelper.createTableAndInsertData(conn); // } finally { // conn.close(); // } // } // } // // public Connection getConnection() throws SQLException { // return dataSource.getConnection(); // } // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/DbTarget.java // public enum DbTarget { // MOCK { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.MYSQL; // } // }, HSQLDB { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.HSQLDB; // } // }, MYSQL { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.MYSQL; // } // }; // // public abstract SQLDialect getSqlDialect(); // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/LimitParam.java // @State(Scope.Benchmark) // public class LimitParam { // @Param(value={"1", "10", "100", "1000", "10000", "100000", "1000000"}) // public int limit; // } // Path: src/main/java/org/sfm/benchmark/db/hibernate/HibernateStatefullBenchmark.java import java.sql.SQLException; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.infra.Blackhole; import org.sfm.benchmark.db.jmh.ConnectionParam; import org.sfm.benchmark.db.jmh.DbTarget; import org.sfm.benchmark.db.jmh.LimitParam; package org.sfm.benchmark.db.hibernate; @State(Scope.Benchmark) public class HibernateStatefullBenchmark { private SessionFactory sf; @Param(value="MOCK")
DbTarget db;
arnaudroger/orm-benchmark
src/main/java/org/sfm/benchmark/db/hibernate/HibernateStatefullBenchmark.java
// Path: src/main/java/org/sfm/benchmark/db/jmh/ConnectionParam.java // @State(Scope.Benchmark) // public class ConnectionParam { // // @Param(value="MOCK") // public DbTarget db; // // public DataSource dataSource; // // @Setup // public void init() throws SQLException, NamingException { // dataSource = ConnectionHelper.getDataSource(db); // // if (db != DbTarget.MOCK) { // Connection conn = dataSource.getConnection(); // try { // ConnectionHelper.createTableAndInsertData(conn); // } finally { // conn.close(); // } // } // } // // public Connection getConnection() throws SQLException { // return dataSource.getConnection(); // } // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/DbTarget.java // public enum DbTarget { // MOCK { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.MYSQL; // } // }, HSQLDB { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.HSQLDB; // } // }, MYSQL { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.MYSQL; // } // }; // // public abstract SQLDialect getSqlDialect(); // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/LimitParam.java // @State(Scope.Benchmark) // public class LimitParam { // @Param(value={"1", "10", "100", "1000", "10000", "100000", "1000000"}) // public int limit; // }
import java.sql.SQLException; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.infra.Blackhole; import org.sfm.benchmark.db.jmh.ConnectionParam; import org.sfm.benchmark.db.jmh.DbTarget; import org.sfm.benchmark.db.jmh.LimitParam;
package org.sfm.benchmark.db.hibernate; @State(Scope.Benchmark) public class HibernateStatefullBenchmark { private SessionFactory sf; @Param(value="MOCK") DbTarget db; boolean enableCache = false; @Setup public void init() throws Exception {
// Path: src/main/java/org/sfm/benchmark/db/jmh/ConnectionParam.java // @State(Scope.Benchmark) // public class ConnectionParam { // // @Param(value="MOCK") // public DbTarget db; // // public DataSource dataSource; // // @Setup // public void init() throws SQLException, NamingException { // dataSource = ConnectionHelper.getDataSource(db); // // if (db != DbTarget.MOCK) { // Connection conn = dataSource.getConnection(); // try { // ConnectionHelper.createTableAndInsertData(conn); // } finally { // conn.close(); // } // } // } // // public Connection getConnection() throws SQLException { // return dataSource.getConnection(); // } // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/DbTarget.java // public enum DbTarget { // MOCK { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.MYSQL; // } // }, HSQLDB { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.HSQLDB; // } // }, MYSQL { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.MYSQL; // } // }; // // public abstract SQLDialect getSqlDialect(); // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/LimitParam.java // @State(Scope.Benchmark) // public class LimitParam { // @Param(value={"1", "10", "100", "1000", "10000", "100000", "1000000"}) // public int limit; // } // Path: src/main/java/org/sfm/benchmark/db/hibernate/HibernateStatefullBenchmark.java import java.sql.SQLException; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.infra.Blackhole; import org.sfm.benchmark.db.jmh.ConnectionParam; import org.sfm.benchmark.db.jmh.DbTarget; import org.sfm.benchmark.db.jmh.LimitParam; package org.sfm.benchmark.db.hibernate; @State(Scope.Benchmark) public class HibernateStatefullBenchmark { private SessionFactory sf; @Param(value="MOCK") DbTarget db; boolean enableCache = false; @Setup public void init() throws Exception {
ConnectionParam connParam = new ConnectionParam();
arnaudroger/orm-benchmark
src/main/java/org/sfm/benchmark/db/hibernate/HibernateStatefullBenchmark.java
// Path: src/main/java/org/sfm/benchmark/db/jmh/ConnectionParam.java // @State(Scope.Benchmark) // public class ConnectionParam { // // @Param(value="MOCK") // public DbTarget db; // // public DataSource dataSource; // // @Setup // public void init() throws SQLException, NamingException { // dataSource = ConnectionHelper.getDataSource(db); // // if (db != DbTarget.MOCK) { // Connection conn = dataSource.getConnection(); // try { // ConnectionHelper.createTableAndInsertData(conn); // } finally { // conn.close(); // } // } // } // // public Connection getConnection() throws SQLException { // return dataSource.getConnection(); // } // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/DbTarget.java // public enum DbTarget { // MOCK { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.MYSQL; // } // }, HSQLDB { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.HSQLDB; // } // }, MYSQL { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.MYSQL; // } // }; // // public abstract SQLDialect getSqlDialect(); // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/LimitParam.java // @State(Scope.Benchmark) // public class LimitParam { // @Param(value={"1", "10", "100", "1000", "10000", "100000", "1000000"}) // public int limit; // }
import java.sql.SQLException; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.infra.Blackhole; import org.sfm.benchmark.db.jmh.ConnectionParam; import org.sfm.benchmark.db.jmh.DbTarget; import org.sfm.benchmark.db.jmh.LimitParam;
package org.sfm.benchmark.db.hibernate; @State(Scope.Benchmark) public class HibernateStatefullBenchmark { private SessionFactory sf; @Param(value="MOCK") DbTarget db; boolean enableCache = false; @Setup public void init() throws Exception { ConnectionParam connParam = new ConnectionParam(); connParam.db = db; connParam.init(); sf = HibernateHelper.getSessionFactory(enableCache, connParam); } @Benchmark
// Path: src/main/java/org/sfm/benchmark/db/jmh/ConnectionParam.java // @State(Scope.Benchmark) // public class ConnectionParam { // // @Param(value="MOCK") // public DbTarget db; // // public DataSource dataSource; // // @Setup // public void init() throws SQLException, NamingException { // dataSource = ConnectionHelper.getDataSource(db); // // if (db != DbTarget.MOCK) { // Connection conn = dataSource.getConnection(); // try { // ConnectionHelper.createTableAndInsertData(conn); // } finally { // conn.close(); // } // } // } // // public Connection getConnection() throws SQLException { // return dataSource.getConnection(); // } // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/DbTarget.java // public enum DbTarget { // MOCK { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.MYSQL; // } // }, HSQLDB { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.HSQLDB; // } // }, MYSQL { // @Override // public SQLDialect getSqlDialect() { // return SQLDialect.MYSQL; // } // }; // // public abstract SQLDialect getSqlDialect(); // } // // Path: src/main/java/org/sfm/benchmark/db/jmh/LimitParam.java // @State(Scope.Benchmark) // public class LimitParam { // @Param(value={"1", "10", "100", "1000", "10000", "100000", "1000000"}) // public int limit; // } // Path: src/main/java/org/sfm/benchmark/db/hibernate/HibernateStatefullBenchmark.java import java.sql.SQLException; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.infra.Blackhole; import org.sfm.benchmark.db.jmh.ConnectionParam; import org.sfm.benchmark.db.jmh.DbTarget; import org.sfm.benchmark.db.jmh.LimitParam; package org.sfm.benchmark.db.hibernate; @State(Scope.Benchmark) public class HibernateStatefullBenchmark { private SessionFactory sf; @Param(value="MOCK") DbTarget db; boolean enableCache = false; @Setup public void init() throws Exception { ConnectionParam connParam = new ConnectionParam(); connParam.db = db; connParam.init(); sf = HibernateHelper.getSessionFactory(enableCache, connParam); } @Benchmark
public void testQuery(LimitParam limit, final Blackhole blackhole) throws Exception {
neuland/firefly
web/src/de/neuland/firefly/rest/v1/LockController.java
// Path: src/de/neuland/firefly/migration/LockRepository.java // @Repository // @Scope("prototype") // public class LockRepository { // @Autowired private ModelService modelService; // @Autowired private FlexibleSearchService searchService; // // public FireflyLockModel findByPk(PK pk) { // return modelService.get(pk); // } // // public FireflyLockModel create() { // return modelService.create(FireflyLockModel.class); // } // // public Optional<FireflyLockModel> findLock() { // final FlexibleSearchQuery query = new FlexibleSearchQuery( // "SELECT {" + FireflyLockModel.PK + "} " + // "FROM {" + FireflyLockModel._TYPECODE + "}"); // try { // return Optional.fromNullable((FireflyLockModel) searchService.searchUnique(query)); // } catch (ModelNotFoundException e) { // return Optional.absent(); // } catch (AmbiguousIdentifierException e) { // throw new RuntimeException("Found more than one lock.", e); // } // } // // public void save(FireflyLockModel lock) { // modelService.save(lock); // } // // public void remove(FireflyLockModel lock) { // modelService.remove(lock); // } // } // // Path: web/src/de/neuland/firefly/rest/v1/model/Lock.java // @XmlRootElement // @XmlAccessorType(XmlAccessType.FIELD) // public class Lock implements Serializable { // private final Date creationDate; // private final long clusterNode; // // public Lock() { // this(null, // -1); // } // // public Lock(Date creationDate, // long clusterNode) { // this.creationDate = creationDate; // this.clusterNode = clusterNode; // } // // public Date getCreationDate() { // return creationDate; // } // // public long getClusterNode() { // return clusterNode; // } // // @Override public boolean equals(Object o) { // if (this == o) // return true; // // if (!(o instanceof Lock)) // return false; // // Lock lock = (Lock) o; // // return new EqualsBuilder() // .append(getClusterNode(), lock.getClusterNode()) // .append(getCreationDate(), lock.getCreationDate()) // .isEquals(); // } // // @Override public int hashCode() { // return new HashCodeBuilder(17, 37) // .append(getCreationDate()) // .append(getClusterNode()) // .toHashCode(); // } // // @Override public String toString() { // return new ToStringBuilder(this) // .append("creationDate", creationDate) // .append("clusterNode", clusterNode) // .toString(); // } // }
import com.google.common.base.Optional; import de.hybris.platform.core.Registry; import de.neuland.firefly.migration.LockRepository; import de.neuland.firefly.model.FireflyLockModel; import de.neuland.firefly.rest.v1.model.Lock; import org.springframework.stereotype.Controller; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.Response; import static javax.ws.rs.core.MediaType.APPLICATION_JSON; import static javax.ws.rs.core.Response.Status.NOT_FOUND; import static javax.ws.rs.core.Response.Status.NO_CONTENT; import static javax.ws.rs.core.Response.Status.OK;
package de.neuland.firefly.rest.v1; @Controller("lockController-v1") @Path("/v1/lock") public class LockController { @GET @Produces(APPLICATION_JSON) public Response getLock() { Optional<FireflyLockModel> maybeLock = getLockRepository().findLock(); if (maybeLock.isPresent()) { FireflyLockModel lock = maybeLock.get();
// Path: src/de/neuland/firefly/migration/LockRepository.java // @Repository // @Scope("prototype") // public class LockRepository { // @Autowired private ModelService modelService; // @Autowired private FlexibleSearchService searchService; // // public FireflyLockModel findByPk(PK pk) { // return modelService.get(pk); // } // // public FireflyLockModel create() { // return modelService.create(FireflyLockModel.class); // } // // public Optional<FireflyLockModel> findLock() { // final FlexibleSearchQuery query = new FlexibleSearchQuery( // "SELECT {" + FireflyLockModel.PK + "} " + // "FROM {" + FireflyLockModel._TYPECODE + "}"); // try { // return Optional.fromNullable((FireflyLockModel) searchService.searchUnique(query)); // } catch (ModelNotFoundException e) { // return Optional.absent(); // } catch (AmbiguousIdentifierException e) { // throw new RuntimeException("Found more than one lock.", e); // } // } // // public void save(FireflyLockModel lock) { // modelService.save(lock); // } // // public void remove(FireflyLockModel lock) { // modelService.remove(lock); // } // } // // Path: web/src/de/neuland/firefly/rest/v1/model/Lock.java // @XmlRootElement // @XmlAccessorType(XmlAccessType.FIELD) // public class Lock implements Serializable { // private final Date creationDate; // private final long clusterNode; // // public Lock() { // this(null, // -1); // } // // public Lock(Date creationDate, // long clusterNode) { // this.creationDate = creationDate; // this.clusterNode = clusterNode; // } // // public Date getCreationDate() { // return creationDate; // } // // public long getClusterNode() { // return clusterNode; // } // // @Override public boolean equals(Object o) { // if (this == o) // return true; // // if (!(o instanceof Lock)) // return false; // // Lock lock = (Lock) o; // // return new EqualsBuilder() // .append(getClusterNode(), lock.getClusterNode()) // .append(getCreationDate(), lock.getCreationDate()) // .isEquals(); // } // // @Override public int hashCode() { // return new HashCodeBuilder(17, 37) // .append(getCreationDate()) // .append(getClusterNode()) // .toHashCode(); // } // // @Override public String toString() { // return new ToStringBuilder(this) // .append("creationDate", creationDate) // .append("clusterNode", clusterNode) // .toString(); // } // } // Path: web/src/de/neuland/firefly/rest/v1/LockController.java import com.google.common.base.Optional; import de.hybris.platform.core.Registry; import de.neuland.firefly.migration.LockRepository; import de.neuland.firefly.model.FireflyLockModel; import de.neuland.firefly.rest.v1.model.Lock; import org.springframework.stereotype.Controller; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.Response; import static javax.ws.rs.core.MediaType.APPLICATION_JSON; import static javax.ws.rs.core.Response.Status.NOT_FOUND; import static javax.ws.rs.core.Response.Status.NO_CONTENT; import static javax.ws.rs.core.Response.Status.OK; package de.neuland.firefly.rest.v1; @Controller("lockController-v1") @Path("/v1/lock") public class LockController { @GET @Produces(APPLICATION_JSON) public Response getLock() { Optional<FireflyLockModel> maybeLock = getLockRepository().findLock(); if (maybeLock.isPresent()) { FireflyLockModel lock = maybeLock.get();
Lock result = new Lock(lock.getCreationtime(),
neuland/firefly
web/src/de/neuland/firefly/rest/v1/LockController.java
// Path: src/de/neuland/firefly/migration/LockRepository.java // @Repository // @Scope("prototype") // public class LockRepository { // @Autowired private ModelService modelService; // @Autowired private FlexibleSearchService searchService; // // public FireflyLockModel findByPk(PK pk) { // return modelService.get(pk); // } // // public FireflyLockModel create() { // return modelService.create(FireflyLockModel.class); // } // // public Optional<FireflyLockModel> findLock() { // final FlexibleSearchQuery query = new FlexibleSearchQuery( // "SELECT {" + FireflyLockModel.PK + "} " + // "FROM {" + FireflyLockModel._TYPECODE + "}"); // try { // return Optional.fromNullable((FireflyLockModel) searchService.searchUnique(query)); // } catch (ModelNotFoundException e) { // return Optional.absent(); // } catch (AmbiguousIdentifierException e) { // throw new RuntimeException("Found more than one lock.", e); // } // } // // public void save(FireflyLockModel lock) { // modelService.save(lock); // } // // public void remove(FireflyLockModel lock) { // modelService.remove(lock); // } // } // // Path: web/src/de/neuland/firefly/rest/v1/model/Lock.java // @XmlRootElement // @XmlAccessorType(XmlAccessType.FIELD) // public class Lock implements Serializable { // private final Date creationDate; // private final long clusterNode; // // public Lock() { // this(null, // -1); // } // // public Lock(Date creationDate, // long clusterNode) { // this.creationDate = creationDate; // this.clusterNode = clusterNode; // } // // public Date getCreationDate() { // return creationDate; // } // // public long getClusterNode() { // return clusterNode; // } // // @Override public boolean equals(Object o) { // if (this == o) // return true; // // if (!(o instanceof Lock)) // return false; // // Lock lock = (Lock) o; // // return new EqualsBuilder() // .append(getClusterNode(), lock.getClusterNode()) // .append(getCreationDate(), lock.getCreationDate()) // .isEquals(); // } // // @Override public int hashCode() { // return new HashCodeBuilder(17, 37) // .append(getCreationDate()) // .append(getClusterNode()) // .toHashCode(); // } // // @Override public String toString() { // return new ToStringBuilder(this) // .append("creationDate", creationDate) // .append("clusterNode", clusterNode) // .toString(); // } // }
import com.google.common.base.Optional; import de.hybris.platform.core.Registry; import de.neuland.firefly.migration.LockRepository; import de.neuland.firefly.model.FireflyLockModel; import de.neuland.firefly.rest.v1.model.Lock; import org.springframework.stereotype.Controller; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.Response; import static javax.ws.rs.core.MediaType.APPLICATION_JSON; import static javax.ws.rs.core.Response.Status.NOT_FOUND; import static javax.ws.rs.core.Response.Status.NO_CONTENT; import static javax.ws.rs.core.Response.Status.OK;
package de.neuland.firefly.rest.v1; @Controller("lockController-v1") @Path("/v1/lock") public class LockController { @GET @Produces(APPLICATION_JSON) public Response getLock() { Optional<FireflyLockModel> maybeLock = getLockRepository().findLock(); if (maybeLock.isPresent()) { FireflyLockModel lock = maybeLock.get(); Lock result = new Lock(lock.getCreationtime(), lock.getClusterNode()); return Response.status(OK) .entity(result) .build(); } else { return Response.status(NOT_FOUND) .build(); } } @DELETE public Response removeLock() {
// Path: src/de/neuland/firefly/migration/LockRepository.java // @Repository // @Scope("prototype") // public class LockRepository { // @Autowired private ModelService modelService; // @Autowired private FlexibleSearchService searchService; // // public FireflyLockModel findByPk(PK pk) { // return modelService.get(pk); // } // // public FireflyLockModel create() { // return modelService.create(FireflyLockModel.class); // } // // public Optional<FireflyLockModel> findLock() { // final FlexibleSearchQuery query = new FlexibleSearchQuery( // "SELECT {" + FireflyLockModel.PK + "} " + // "FROM {" + FireflyLockModel._TYPECODE + "}"); // try { // return Optional.fromNullable((FireflyLockModel) searchService.searchUnique(query)); // } catch (ModelNotFoundException e) { // return Optional.absent(); // } catch (AmbiguousIdentifierException e) { // throw new RuntimeException("Found more than one lock.", e); // } // } // // public void save(FireflyLockModel lock) { // modelService.save(lock); // } // // public void remove(FireflyLockModel lock) { // modelService.remove(lock); // } // } // // Path: web/src/de/neuland/firefly/rest/v1/model/Lock.java // @XmlRootElement // @XmlAccessorType(XmlAccessType.FIELD) // public class Lock implements Serializable { // private final Date creationDate; // private final long clusterNode; // // public Lock() { // this(null, // -1); // } // // public Lock(Date creationDate, // long clusterNode) { // this.creationDate = creationDate; // this.clusterNode = clusterNode; // } // // public Date getCreationDate() { // return creationDate; // } // // public long getClusterNode() { // return clusterNode; // } // // @Override public boolean equals(Object o) { // if (this == o) // return true; // // if (!(o instanceof Lock)) // return false; // // Lock lock = (Lock) o; // // return new EqualsBuilder() // .append(getClusterNode(), lock.getClusterNode()) // .append(getCreationDate(), lock.getCreationDate()) // .isEquals(); // } // // @Override public int hashCode() { // return new HashCodeBuilder(17, 37) // .append(getCreationDate()) // .append(getClusterNode()) // .toHashCode(); // } // // @Override public String toString() { // return new ToStringBuilder(this) // .append("creationDate", creationDate) // .append("clusterNode", clusterNode) // .toString(); // } // } // Path: web/src/de/neuland/firefly/rest/v1/LockController.java import com.google.common.base.Optional; import de.hybris.platform.core.Registry; import de.neuland.firefly.migration.LockRepository; import de.neuland.firefly.model.FireflyLockModel; import de.neuland.firefly.rest.v1.model.Lock; import org.springframework.stereotype.Controller; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.Response; import static javax.ws.rs.core.MediaType.APPLICATION_JSON; import static javax.ws.rs.core.Response.Status.NOT_FOUND; import static javax.ws.rs.core.Response.Status.NO_CONTENT; import static javax.ws.rs.core.Response.Status.OK; package de.neuland.firefly.rest.v1; @Controller("lockController-v1") @Path("/v1/lock") public class LockController { @GET @Produces(APPLICATION_JSON) public Response getLock() { Optional<FireflyLockModel> maybeLock = getLockRepository().findLock(); if (maybeLock.isPresent()) { FireflyLockModel lock = maybeLock.get(); Lock result = new Lock(lock.getCreationtime(), lock.getClusterNode()); return Response.status(OK) .entity(result) .build(); } else { return Response.status(NOT_FOUND) .build(); } } @DELETE public Response removeLock() {
LockRepository lockRepository = getLockRepository();
neuland/firefly
testsrc/de/neuland/firefly/extensionfinder/HmcResetEventListenerTest.java
// Path: src/de/neuland/firefly/HybrisAdapter.java // @Component // @Scope("prototype") // public class HybrisAdapter { // private static final Logger LOG = Logger.getLogger(HybrisAdapter.class); // private static final String SYSTEM_UPDATE = "System update"; // private static final String HMC_RESET = "HMC Reset"; // @Autowired EventService eventService; // @Autowired CacheController cacheController; // // public void initFirefly() throws Exception { // doInitialize(true); // } // // public void updateSystem(PK migration) throws Exception { // doInitialize(true); // eventService.publishEvent(new SystemUpdatedEvent(getTenantId(), migration)); // } // // private void doInitialize(boolean update) throws Exception { // FireflyJspWriter jspWriter = new FireflyJspWriter(); // try { // MockHttpServletRequest request = new MockHttpServletRequest(); // if (update) { // // up to version 5 // request.addParameter("initmethod", "update"); // request.addParameter("essential", "true"); // // version 6 // request.addParameter("initMethod", "UPDATE"); // request.addParameter("createEssentialData", "true"); // } // request.addParameter("init", "true"); // request.addParameter("default", "false"); // request.addParameter("ALL_EXTENSIONS", "true"); // // up to version 5 // request.addParameter("localizetypes", "true"); // request.addParameter("clearhmc", "true"); // // version 6 // request.addParameter("localizeTypes", "true"); // request.addParameter("clearHMC", "true"); // // JspContext jspContext = new JspContext(jspWriter, request, new MockHttpServletResponse()); // // try { // InitializationLockHandler handler = new InitializationLockHandler(new DefaultInitLockDao()); // String operationName = update ? SYSTEM_UPDATE : HMC_RESET; // // handler.performLocked(Registry.getCurrentTenant(), // createInitializeCallable(jspContext), // operationName); // } catch (NoSuchMethodException e) { // LOG.info(format("Internal reflection unsuccessful: system is not locked while performing '%s only' change.", HMC_RESET)); // Initialization.doInitialize(jspContext); // } // } finally { // LOG.debug(de.hybris.platform.util.Utilities.filterOutHTMLTags(jspWriter.getString())); // } // } // // private Callable<Boolean> createInitializeCallable(final JspContext jspContext) { // return new Callable<Boolean>() { // public Boolean call() throws Exception { // Method m = Initialization.class.getDeclaredMethod("doInitializeImpl", JspContext.class); // m.setAccessible(true); // m.invoke(null, jspContext); // return Boolean.TRUE; // } // }; // } // // public void clearHmcConfiguration(PK migration) throws Exception { // doInitialize(false); // eventService.publishEvent(new HmcResetEvent(getTenantId(), migration)); // } // // public String getTenantId() { // return Registry.getCurrentTenant().getTenantID(); // } // // public void clearJaloCache() { // Registry.getCurrentTenant().getCache().clear(); // } // // /** // * This event is triggered after a system update is done. // */ // public static class SystemUpdatedEvent extends TenantEvent { // private PK migration; // // SystemUpdatedEvent(String tenantId, PK migration) { // super(tenantId); // this.migration = migration; // } // // public PK getMigration() { // return migration; // } // } // // /** // * This event is triggered after a hMC reset is done. // */ // public static class HmcResetEvent extends TenantEvent { // private PK migration; // // HmcResetEvent(String tenantId, PK migration) { // super(tenantId); // this.migration = migration; // } // // public PK getMigration() { // return migration; // } // } // // }
import de.hybris.platform.core.PK; import de.hybris.platform.servicelayer.cluster.ClusterService; import de.hybris.platform.servicelayer.tenant.TenantService; import de.neuland.firefly.HybrisAdapter; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import static org.mockito.BDDMockito.given; import static org.mockito.Matchers.any; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify;
package de.neuland.firefly.extensionfinder; @RunWith(MockitoJUnitRunner.class) public class HmcResetEventListenerTest { private static final String TENANT_ID = "myTestTenant"; private HmcResetEventListener listener; @Mock private FireflyExtension extension;
// Path: src/de/neuland/firefly/HybrisAdapter.java // @Component // @Scope("prototype") // public class HybrisAdapter { // private static final Logger LOG = Logger.getLogger(HybrisAdapter.class); // private static final String SYSTEM_UPDATE = "System update"; // private static final String HMC_RESET = "HMC Reset"; // @Autowired EventService eventService; // @Autowired CacheController cacheController; // // public void initFirefly() throws Exception { // doInitialize(true); // } // // public void updateSystem(PK migration) throws Exception { // doInitialize(true); // eventService.publishEvent(new SystemUpdatedEvent(getTenantId(), migration)); // } // // private void doInitialize(boolean update) throws Exception { // FireflyJspWriter jspWriter = new FireflyJspWriter(); // try { // MockHttpServletRequest request = new MockHttpServletRequest(); // if (update) { // // up to version 5 // request.addParameter("initmethod", "update"); // request.addParameter("essential", "true"); // // version 6 // request.addParameter("initMethod", "UPDATE"); // request.addParameter("createEssentialData", "true"); // } // request.addParameter("init", "true"); // request.addParameter("default", "false"); // request.addParameter("ALL_EXTENSIONS", "true"); // // up to version 5 // request.addParameter("localizetypes", "true"); // request.addParameter("clearhmc", "true"); // // version 6 // request.addParameter("localizeTypes", "true"); // request.addParameter("clearHMC", "true"); // // JspContext jspContext = new JspContext(jspWriter, request, new MockHttpServletResponse()); // // try { // InitializationLockHandler handler = new InitializationLockHandler(new DefaultInitLockDao()); // String operationName = update ? SYSTEM_UPDATE : HMC_RESET; // // handler.performLocked(Registry.getCurrentTenant(), // createInitializeCallable(jspContext), // operationName); // } catch (NoSuchMethodException e) { // LOG.info(format("Internal reflection unsuccessful: system is not locked while performing '%s only' change.", HMC_RESET)); // Initialization.doInitialize(jspContext); // } // } finally { // LOG.debug(de.hybris.platform.util.Utilities.filterOutHTMLTags(jspWriter.getString())); // } // } // // private Callable<Boolean> createInitializeCallable(final JspContext jspContext) { // return new Callable<Boolean>() { // public Boolean call() throws Exception { // Method m = Initialization.class.getDeclaredMethod("doInitializeImpl", JspContext.class); // m.setAccessible(true); // m.invoke(null, jspContext); // return Boolean.TRUE; // } // }; // } // // public void clearHmcConfiguration(PK migration) throws Exception { // doInitialize(false); // eventService.publishEvent(new HmcResetEvent(getTenantId(), migration)); // } // // public String getTenantId() { // return Registry.getCurrentTenant().getTenantID(); // } // // public void clearJaloCache() { // Registry.getCurrentTenant().getCache().clear(); // } // // /** // * This event is triggered after a system update is done. // */ // public static class SystemUpdatedEvent extends TenantEvent { // private PK migration; // // SystemUpdatedEvent(String tenantId, PK migration) { // super(tenantId); // this.migration = migration; // } // // public PK getMigration() { // return migration; // } // } // // /** // * This event is triggered after a hMC reset is done. // */ // public static class HmcResetEvent extends TenantEvent { // private PK migration; // // HmcResetEvent(String tenantId, PK migration) { // super(tenantId); // this.migration = migration; // } // // public PK getMigration() { // return migration; // } // } // // } // Path: testsrc/de/neuland/firefly/extensionfinder/HmcResetEventListenerTest.java import de.hybris.platform.core.PK; import de.hybris.platform.servicelayer.cluster.ClusterService; import de.hybris.platform.servicelayer.tenant.TenantService; import de.neuland.firefly.HybrisAdapter; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import static org.mockito.BDDMockito.given; import static org.mockito.Matchers.any; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; package de.neuland.firefly.extensionfinder; @RunWith(MockitoJUnitRunner.class) public class HmcResetEventListenerTest { private static final String TENANT_ID = "myTestTenant"; private HmcResetEventListener listener; @Mock private FireflyExtension extension;
@Mock private HybrisAdapter.HmcResetEvent hmcResetEvent;
neuland/firefly
testsrc/de/neuland/firefly/extensionfinder/FireflyExtensionTest.java
// Path: src/de/neuland/firefly/migration/MigrationRepository.java // @Repository // @Scope("prototype") // public class MigrationRepository { // @Autowired private ModelService modelService; // // public FireflyMigrationModel findByPk(PK pk) { // return modelService.get(pk); // } // // public FireflyMigrationModel create() { // return modelService.create(FireflyMigrationModel.class); // } // // public void save(FireflyMigrationModel migration) { // modelService.save(migration); // } // } // // Path: testsrc/de/neuland/firefly/TestUtils.java // public static void unwrapException(RuntimeException e) throws Throwable { // if (e.getCause() != null) { // throw e.getCause(); // } else { // throw e; // } // } // // Path: src/de/neuland/firefly/constants/FireflyConstants.java // public static final String NO_HMC_XML_MD5 = "NO_HMC_XML"; // // Path: src/de/neuland/firefly/constants/FireflyConstants.java // public static final String NO_ITEMS_XML_MD5 = "NO_ITEMS_XML"; // // Path: src/de/neuland/firefly/utils/MD5Util.java // public static String generateMD5(String baseValue) { // return generateMD5(baseValue, "UTF-8", "MD5"); // }
import de.hybris.platform.core.PK; import de.neuland.firefly.migration.MigrationRepository; import de.neuland.firefly.model.FireflyExtensionModel; import de.neuland.firefly.model.FireflyExtensionStateModel; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.xml.sax.SAXException; import java.io.File; import java.net.URL; import java.util.ArrayList; import static de.neuland.firefly.TestUtils.unwrapException; import static de.neuland.firefly.constants.FireflyConstants.NO_HMC_XML_MD5; import static de.neuland.firefly.constants.FireflyConstants.NO_ITEMS_XML_MD5; import static de.neuland.firefly.utils.MD5Util.generateMD5; import static java.util.Arrays.asList; import static org.apache.commons.io.FileUtils.getTempDirectory; import static org.junit.Assert.*; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify;
package de.neuland.firefly.extensionfinder; @RunWith(MockitoJUnitRunner.class) public class FireflyExtensionTest { private static final String EXTENSION_WITH_INVALID_ITEMS_XML = "invalid"; private static final String EXTENSION_WITH_ITEMS_XML = "firefly-junit"; private static final String EXTENSION_WITHOUT_ITEMS_XML = "none"; private static final String ITEMS_XML_CONTENT = "<items><a>someValue</a><b/></items>"; private static final String HMC_XML_CONTENT = "<configuration/>"; private static final PK MIGRATION = PK.NULL_PK; private FireflyExtension fireflyExtension; @Mock private FireflyExtensionRepository fireflyExtensionRepository;
// Path: src/de/neuland/firefly/migration/MigrationRepository.java // @Repository // @Scope("prototype") // public class MigrationRepository { // @Autowired private ModelService modelService; // // public FireflyMigrationModel findByPk(PK pk) { // return modelService.get(pk); // } // // public FireflyMigrationModel create() { // return modelService.create(FireflyMigrationModel.class); // } // // public void save(FireflyMigrationModel migration) { // modelService.save(migration); // } // } // // Path: testsrc/de/neuland/firefly/TestUtils.java // public static void unwrapException(RuntimeException e) throws Throwable { // if (e.getCause() != null) { // throw e.getCause(); // } else { // throw e; // } // } // // Path: src/de/neuland/firefly/constants/FireflyConstants.java // public static final String NO_HMC_XML_MD5 = "NO_HMC_XML"; // // Path: src/de/neuland/firefly/constants/FireflyConstants.java // public static final String NO_ITEMS_XML_MD5 = "NO_ITEMS_XML"; // // Path: src/de/neuland/firefly/utils/MD5Util.java // public static String generateMD5(String baseValue) { // return generateMD5(baseValue, "UTF-8", "MD5"); // } // Path: testsrc/de/neuland/firefly/extensionfinder/FireflyExtensionTest.java import de.hybris.platform.core.PK; import de.neuland.firefly.migration.MigrationRepository; import de.neuland.firefly.model.FireflyExtensionModel; import de.neuland.firefly.model.FireflyExtensionStateModel; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.xml.sax.SAXException; import java.io.File; import java.net.URL; import java.util.ArrayList; import static de.neuland.firefly.TestUtils.unwrapException; import static de.neuland.firefly.constants.FireflyConstants.NO_HMC_XML_MD5; import static de.neuland.firefly.constants.FireflyConstants.NO_ITEMS_XML_MD5; import static de.neuland.firefly.utils.MD5Util.generateMD5; import static java.util.Arrays.asList; import static org.apache.commons.io.FileUtils.getTempDirectory; import static org.junit.Assert.*; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; package de.neuland.firefly.extensionfinder; @RunWith(MockitoJUnitRunner.class) public class FireflyExtensionTest { private static final String EXTENSION_WITH_INVALID_ITEMS_XML = "invalid"; private static final String EXTENSION_WITH_ITEMS_XML = "firefly-junit"; private static final String EXTENSION_WITHOUT_ITEMS_XML = "none"; private static final String ITEMS_XML_CONTENT = "<items><a>someValue</a><b/></items>"; private static final String HMC_XML_CONTENT = "<configuration/>"; private static final PK MIGRATION = PK.NULL_PK; private FireflyExtension fireflyExtension; @Mock private FireflyExtensionRepository fireflyExtensionRepository;
@Mock private MigrationRepository migrationRepository;
neuland/firefly
testsrc/de/neuland/firefly/extensionfinder/FireflyExtensionTest.java
// Path: src/de/neuland/firefly/migration/MigrationRepository.java // @Repository // @Scope("prototype") // public class MigrationRepository { // @Autowired private ModelService modelService; // // public FireflyMigrationModel findByPk(PK pk) { // return modelService.get(pk); // } // // public FireflyMigrationModel create() { // return modelService.create(FireflyMigrationModel.class); // } // // public void save(FireflyMigrationModel migration) { // modelService.save(migration); // } // } // // Path: testsrc/de/neuland/firefly/TestUtils.java // public static void unwrapException(RuntimeException e) throws Throwable { // if (e.getCause() != null) { // throw e.getCause(); // } else { // throw e; // } // } // // Path: src/de/neuland/firefly/constants/FireflyConstants.java // public static final String NO_HMC_XML_MD5 = "NO_HMC_XML"; // // Path: src/de/neuland/firefly/constants/FireflyConstants.java // public static final String NO_ITEMS_XML_MD5 = "NO_ITEMS_XML"; // // Path: src/de/neuland/firefly/utils/MD5Util.java // public static String generateMD5(String baseValue) { // return generateMD5(baseValue, "UTF-8", "MD5"); // }
import de.hybris.platform.core.PK; import de.neuland.firefly.migration.MigrationRepository; import de.neuland.firefly.model.FireflyExtensionModel; import de.neuland.firefly.model.FireflyExtensionStateModel; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.xml.sax.SAXException; import java.io.File; import java.net.URL; import java.util.ArrayList; import static de.neuland.firefly.TestUtils.unwrapException; import static de.neuland.firefly.constants.FireflyConstants.NO_HMC_XML_MD5; import static de.neuland.firefly.constants.FireflyConstants.NO_ITEMS_XML_MD5; import static de.neuland.firefly.utils.MD5Util.generateMD5; import static java.util.Arrays.asList; import static org.apache.commons.io.FileUtils.getTempDirectory; import static org.junit.Assert.*; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify;
package de.neuland.firefly.extensionfinder; @RunWith(MockitoJUnitRunner.class) public class FireflyExtensionTest { private static final String EXTENSION_WITH_INVALID_ITEMS_XML = "invalid"; private static final String EXTENSION_WITH_ITEMS_XML = "firefly-junit"; private static final String EXTENSION_WITHOUT_ITEMS_XML = "none"; private static final String ITEMS_XML_CONTENT = "<items><a>someValue</a><b/></items>"; private static final String HMC_XML_CONTENT = "<configuration/>"; private static final PK MIGRATION = PK.NULL_PK; private FireflyExtension fireflyExtension; @Mock private FireflyExtensionRepository fireflyExtensionRepository; @Mock private MigrationRepository migrationRepository; @Captor ArgumentCaptor<ArrayList<FireflyExtensionStateModel>> statesCaptor; @Before public void setUp() throws Exception { fireflyExtension = createExtension(EXTENSION_WITH_ITEMS_XML, false); } @Test public void shouldGetItemsDefinitionHash() throws Exception { // when String resultHash = fireflyExtension.getItemsDefinitionHash(); // then
// Path: src/de/neuland/firefly/migration/MigrationRepository.java // @Repository // @Scope("prototype") // public class MigrationRepository { // @Autowired private ModelService modelService; // // public FireflyMigrationModel findByPk(PK pk) { // return modelService.get(pk); // } // // public FireflyMigrationModel create() { // return modelService.create(FireflyMigrationModel.class); // } // // public void save(FireflyMigrationModel migration) { // modelService.save(migration); // } // } // // Path: testsrc/de/neuland/firefly/TestUtils.java // public static void unwrapException(RuntimeException e) throws Throwable { // if (e.getCause() != null) { // throw e.getCause(); // } else { // throw e; // } // } // // Path: src/de/neuland/firefly/constants/FireflyConstants.java // public static final String NO_HMC_XML_MD5 = "NO_HMC_XML"; // // Path: src/de/neuland/firefly/constants/FireflyConstants.java // public static final String NO_ITEMS_XML_MD5 = "NO_ITEMS_XML"; // // Path: src/de/neuland/firefly/utils/MD5Util.java // public static String generateMD5(String baseValue) { // return generateMD5(baseValue, "UTF-8", "MD5"); // } // Path: testsrc/de/neuland/firefly/extensionfinder/FireflyExtensionTest.java import de.hybris.platform.core.PK; import de.neuland.firefly.migration.MigrationRepository; import de.neuland.firefly.model.FireflyExtensionModel; import de.neuland.firefly.model.FireflyExtensionStateModel; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.xml.sax.SAXException; import java.io.File; import java.net.URL; import java.util.ArrayList; import static de.neuland.firefly.TestUtils.unwrapException; import static de.neuland.firefly.constants.FireflyConstants.NO_HMC_XML_MD5; import static de.neuland.firefly.constants.FireflyConstants.NO_ITEMS_XML_MD5; import static de.neuland.firefly.utils.MD5Util.generateMD5; import static java.util.Arrays.asList; import static org.apache.commons.io.FileUtils.getTempDirectory; import static org.junit.Assert.*; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; package de.neuland.firefly.extensionfinder; @RunWith(MockitoJUnitRunner.class) public class FireflyExtensionTest { private static final String EXTENSION_WITH_INVALID_ITEMS_XML = "invalid"; private static final String EXTENSION_WITH_ITEMS_XML = "firefly-junit"; private static final String EXTENSION_WITHOUT_ITEMS_XML = "none"; private static final String ITEMS_XML_CONTENT = "<items><a>someValue</a><b/></items>"; private static final String HMC_XML_CONTENT = "<configuration/>"; private static final PK MIGRATION = PK.NULL_PK; private FireflyExtension fireflyExtension; @Mock private FireflyExtensionRepository fireflyExtensionRepository; @Mock private MigrationRepository migrationRepository; @Captor ArgumentCaptor<ArrayList<FireflyExtensionStateModel>> statesCaptor; @Before public void setUp() throws Exception { fireflyExtension = createExtension(EXTENSION_WITH_ITEMS_XML, false); } @Test public void shouldGetItemsDefinitionHash() throws Exception { // when String resultHash = fireflyExtension.getItemsDefinitionHash(); // then
assertEquals(generateMD5(ITEMS_XML_CONTENT), resultHash);
neuland/firefly
testsrc/de/neuland/firefly/extensionfinder/FireflyExtensionTest.java
// Path: src/de/neuland/firefly/migration/MigrationRepository.java // @Repository // @Scope("prototype") // public class MigrationRepository { // @Autowired private ModelService modelService; // // public FireflyMigrationModel findByPk(PK pk) { // return modelService.get(pk); // } // // public FireflyMigrationModel create() { // return modelService.create(FireflyMigrationModel.class); // } // // public void save(FireflyMigrationModel migration) { // modelService.save(migration); // } // } // // Path: testsrc/de/neuland/firefly/TestUtils.java // public static void unwrapException(RuntimeException e) throws Throwable { // if (e.getCause() != null) { // throw e.getCause(); // } else { // throw e; // } // } // // Path: src/de/neuland/firefly/constants/FireflyConstants.java // public static final String NO_HMC_XML_MD5 = "NO_HMC_XML"; // // Path: src/de/neuland/firefly/constants/FireflyConstants.java // public static final String NO_ITEMS_XML_MD5 = "NO_ITEMS_XML"; // // Path: src/de/neuland/firefly/utils/MD5Util.java // public static String generateMD5(String baseValue) { // return generateMD5(baseValue, "UTF-8", "MD5"); // }
import de.hybris.platform.core.PK; import de.neuland.firefly.migration.MigrationRepository; import de.neuland.firefly.model.FireflyExtensionModel; import de.neuland.firefly.model.FireflyExtensionStateModel; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.xml.sax.SAXException; import java.io.File; import java.net.URL; import java.util.ArrayList; import static de.neuland.firefly.TestUtils.unwrapException; import static de.neuland.firefly.constants.FireflyConstants.NO_HMC_XML_MD5; import static de.neuland.firefly.constants.FireflyConstants.NO_ITEMS_XML_MD5; import static de.neuland.firefly.utils.MD5Util.generateMD5; import static java.util.Arrays.asList; import static org.apache.commons.io.FileUtils.getTempDirectory; import static org.junit.Assert.*; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify;
@Captor ArgumentCaptor<ArrayList<FireflyExtensionStateModel>> statesCaptor; @Before public void setUp() throws Exception { fireflyExtension = createExtension(EXTENSION_WITH_ITEMS_XML, false); } @Test public void shouldGetItemsDefinitionHash() throws Exception { // when String resultHash = fireflyExtension.getItemsDefinitionHash(); // then assertEquals(generateMD5(ITEMS_XML_CONTENT), resultHash); } @Test public void shouldGetHmcConfigurationHash() throws Exception { // when String resultHash = fireflyExtension.getHmcDefinitionHash(); // then assertEquals(generateMD5(HMC_XML_CONTENT), resultHash); } @Test public void shouldGetDefaultItemsDefinitionHashIfNoItemsXmlWasFound() throws Exception { // given fireflyExtension = createExtension(EXTENSION_WITHOUT_ITEMS_XML, false); // when String resultHash = fireflyExtension.getItemsDefinitionHash(); // then
// Path: src/de/neuland/firefly/migration/MigrationRepository.java // @Repository // @Scope("prototype") // public class MigrationRepository { // @Autowired private ModelService modelService; // // public FireflyMigrationModel findByPk(PK pk) { // return modelService.get(pk); // } // // public FireflyMigrationModel create() { // return modelService.create(FireflyMigrationModel.class); // } // // public void save(FireflyMigrationModel migration) { // modelService.save(migration); // } // } // // Path: testsrc/de/neuland/firefly/TestUtils.java // public static void unwrapException(RuntimeException e) throws Throwable { // if (e.getCause() != null) { // throw e.getCause(); // } else { // throw e; // } // } // // Path: src/de/neuland/firefly/constants/FireflyConstants.java // public static final String NO_HMC_XML_MD5 = "NO_HMC_XML"; // // Path: src/de/neuland/firefly/constants/FireflyConstants.java // public static final String NO_ITEMS_XML_MD5 = "NO_ITEMS_XML"; // // Path: src/de/neuland/firefly/utils/MD5Util.java // public static String generateMD5(String baseValue) { // return generateMD5(baseValue, "UTF-8", "MD5"); // } // Path: testsrc/de/neuland/firefly/extensionfinder/FireflyExtensionTest.java import de.hybris.platform.core.PK; import de.neuland.firefly.migration.MigrationRepository; import de.neuland.firefly.model.FireflyExtensionModel; import de.neuland.firefly.model.FireflyExtensionStateModel; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.xml.sax.SAXException; import java.io.File; import java.net.URL; import java.util.ArrayList; import static de.neuland.firefly.TestUtils.unwrapException; import static de.neuland.firefly.constants.FireflyConstants.NO_HMC_XML_MD5; import static de.neuland.firefly.constants.FireflyConstants.NO_ITEMS_XML_MD5; import static de.neuland.firefly.utils.MD5Util.generateMD5; import static java.util.Arrays.asList; import static org.apache.commons.io.FileUtils.getTempDirectory; import static org.junit.Assert.*; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @Captor ArgumentCaptor<ArrayList<FireflyExtensionStateModel>> statesCaptor; @Before public void setUp() throws Exception { fireflyExtension = createExtension(EXTENSION_WITH_ITEMS_XML, false); } @Test public void shouldGetItemsDefinitionHash() throws Exception { // when String resultHash = fireflyExtension.getItemsDefinitionHash(); // then assertEquals(generateMD5(ITEMS_XML_CONTENT), resultHash); } @Test public void shouldGetHmcConfigurationHash() throws Exception { // when String resultHash = fireflyExtension.getHmcDefinitionHash(); // then assertEquals(generateMD5(HMC_XML_CONTENT), resultHash); } @Test public void shouldGetDefaultItemsDefinitionHashIfNoItemsXmlWasFound() throws Exception { // given fireflyExtension = createExtension(EXTENSION_WITHOUT_ITEMS_XML, false); // when String resultHash = fireflyExtension.getItemsDefinitionHash(); // then
assertEquals(NO_ITEMS_XML_MD5, resultHash);
neuland/firefly
testsrc/de/neuland/firefly/extensionfinder/FireflyExtensionTest.java
// Path: src/de/neuland/firefly/migration/MigrationRepository.java // @Repository // @Scope("prototype") // public class MigrationRepository { // @Autowired private ModelService modelService; // // public FireflyMigrationModel findByPk(PK pk) { // return modelService.get(pk); // } // // public FireflyMigrationModel create() { // return modelService.create(FireflyMigrationModel.class); // } // // public void save(FireflyMigrationModel migration) { // modelService.save(migration); // } // } // // Path: testsrc/de/neuland/firefly/TestUtils.java // public static void unwrapException(RuntimeException e) throws Throwable { // if (e.getCause() != null) { // throw e.getCause(); // } else { // throw e; // } // } // // Path: src/de/neuland/firefly/constants/FireflyConstants.java // public static final String NO_HMC_XML_MD5 = "NO_HMC_XML"; // // Path: src/de/neuland/firefly/constants/FireflyConstants.java // public static final String NO_ITEMS_XML_MD5 = "NO_ITEMS_XML"; // // Path: src/de/neuland/firefly/utils/MD5Util.java // public static String generateMD5(String baseValue) { // return generateMD5(baseValue, "UTF-8", "MD5"); // }
import de.hybris.platform.core.PK; import de.neuland.firefly.migration.MigrationRepository; import de.neuland.firefly.model.FireflyExtensionModel; import de.neuland.firefly.model.FireflyExtensionStateModel; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.xml.sax.SAXException; import java.io.File; import java.net.URL; import java.util.ArrayList; import static de.neuland.firefly.TestUtils.unwrapException; import static de.neuland.firefly.constants.FireflyConstants.NO_HMC_XML_MD5; import static de.neuland.firefly.constants.FireflyConstants.NO_ITEMS_XML_MD5; import static de.neuland.firefly.utils.MD5Util.generateMD5; import static java.util.Arrays.asList; import static org.apache.commons.io.FileUtils.getTempDirectory; import static org.junit.Assert.*; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify;
String resultHash = fireflyExtension.getItemsDefinitionHash(); // then assertEquals(generateMD5(ITEMS_XML_CONTENT), resultHash); } @Test public void shouldGetHmcConfigurationHash() throws Exception { // when String resultHash = fireflyExtension.getHmcDefinitionHash(); // then assertEquals(generateMD5(HMC_XML_CONTENT), resultHash); } @Test public void shouldGetDefaultItemsDefinitionHashIfNoItemsXmlWasFound() throws Exception { // given fireflyExtension = createExtension(EXTENSION_WITHOUT_ITEMS_XML, false); // when String resultHash = fireflyExtension.getItemsDefinitionHash(); // then assertEquals(NO_ITEMS_XML_MD5, resultHash); } @Test public void shouldGetDefaultHmcDefinitionHashIfNoItemsXmlWasFound() throws Exception { // given fireflyExtension = new FireflyExtension(EXTENSION_WITHOUT_ITEMS_XML, getTempDirectory(), fireflyExtensionRepository, migrationRepository, false); // when String resultHash = fireflyExtension.getHmcDefinitionHash(); // then
// Path: src/de/neuland/firefly/migration/MigrationRepository.java // @Repository // @Scope("prototype") // public class MigrationRepository { // @Autowired private ModelService modelService; // // public FireflyMigrationModel findByPk(PK pk) { // return modelService.get(pk); // } // // public FireflyMigrationModel create() { // return modelService.create(FireflyMigrationModel.class); // } // // public void save(FireflyMigrationModel migration) { // modelService.save(migration); // } // } // // Path: testsrc/de/neuland/firefly/TestUtils.java // public static void unwrapException(RuntimeException e) throws Throwable { // if (e.getCause() != null) { // throw e.getCause(); // } else { // throw e; // } // } // // Path: src/de/neuland/firefly/constants/FireflyConstants.java // public static final String NO_HMC_XML_MD5 = "NO_HMC_XML"; // // Path: src/de/neuland/firefly/constants/FireflyConstants.java // public static final String NO_ITEMS_XML_MD5 = "NO_ITEMS_XML"; // // Path: src/de/neuland/firefly/utils/MD5Util.java // public static String generateMD5(String baseValue) { // return generateMD5(baseValue, "UTF-8", "MD5"); // } // Path: testsrc/de/neuland/firefly/extensionfinder/FireflyExtensionTest.java import de.hybris.platform.core.PK; import de.neuland.firefly.migration.MigrationRepository; import de.neuland.firefly.model.FireflyExtensionModel; import de.neuland.firefly.model.FireflyExtensionStateModel; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.xml.sax.SAXException; import java.io.File; import java.net.URL; import java.util.ArrayList; import static de.neuland.firefly.TestUtils.unwrapException; import static de.neuland.firefly.constants.FireflyConstants.NO_HMC_XML_MD5; import static de.neuland.firefly.constants.FireflyConstants.NO_ITEMS_XML_MD5; import static de.neuland.firefly.utils.MD5Util.generateMD5; import static java.util.Arrays.asList; import static org.apache.commons.io.FileUtils.getTempDirectory; import static org.junit.Assert.*; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; String resultHash = fireflyExtension.getItemsDefinitionHash(); // then assertEquals(generateMD5(ITEMS_XML_CONTENT), resultHash); } @Test public void shouldGetHmcConfigurationHash() throws Exception { // when String resultHash = fireflyExtension.getHmcDefinitionHash(); // then assertEquals(generateMD5(HMC_XML_CONTENT), resultHash); } @Test public void shouldGetDefaultItemsDefinitionHashIfNoItemsXmlWasFound() throws Exception { // given fireflyExtension = createExtension(EXTENSION_WITHOUT_ITEMS_XML, false); // when String resultHash = fireflyExtension.getItemsDefinitionHash(); // then assertEquals(NO_ITEMS_XML_MD5, resultHash); } @Test public void shouldGetDefaultHmcDefinitionHashIfNoItemsXmlWasFound() throws Exception { // given fireflyExtension = new FireflyExtension(EXTENSION_WITHOUT_ITEMS_XML, getTempDirectory(), fireflyExtensionRepository, migrationRepository, false); // when String resultHash = fireflyExtension.getHmcDefinitionHash(); // then
assertEquals(NO_HMC_XML_MD5, resultHash);
neuland/firefly
testsrc/de/neuland/firefly/extensionfinder/FireflyExtensionTest.java
// Path: src/de/neuland/firefly/migration/MigrationRepository.java // @Repository // @Scope("prototype") // public class MigrationRepository { // @Autowired private ModelService modelService; // // public FireflyMigrationModel findByPk(PK pk) { // return modelService.get(pk); // } // // public FireflyMigrationModel create() { // return modelService.create(FireflyMigrationModel.class); // } // // public void save(FireflyMigrationModel migration) { // modelService.save(migration); // } // } // // Path: testsrc/de/neuland/firefly/TestUtils.java // public static void unwrapException(RuntimeException e) throws Throwable { // if (e.getCause() != null) { // throw e.getCause(); // } else { // throw e; // } // } // // Path: src/de/neuland/firefly/constants/FireflyConstants.java // public static final String NO_HMC_XML_MD5 = "NO_HMC_XML"; // // Path: src/de/neuland/firefly/constants/FireflyConstants.java // public static final String NO_ITEMS_XML_MD5 = "NO_ITEMS_XML"; // // Path: src/de/neuland/firefly/utils/MD5Util.java // public static String generateMD5(String baseValue) { // return generateMD5(baseValue, "UTF-8", "MD5"); // }
import de.hybris.platform.core.PK; import de.neuland.firefly.migration.MigrationRepository; import de.neuland.firefly.model.FireflyExtensionModel; import de.neuland.firefly.model.FireflyExtensionStateModel; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.xml.sax.SAXException; import java.io.File; import java.net.URL; import java.util.ArrayList; import static de.neuland.firefly.TestUtils.unwrapException; import static de.neuland.firefly.constants.FireflyConstants.NO_HMC_XML_MD5; import static de.neuland.firefly.constants.FireflyConstants.NO_ITEMS_XML_MD5; import static de.neuland.firefly.utils.MD5Util.generateMD5; import static java.util.Arrays.asList; import static org.apache.commons.io.FileUtils.getTempDirectory; import static org.junit.Assert.*; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify;
fireflyExtension.onHmcReset(MIGRATION); // then verify(fireflyExtensionModel).setStates(statesCaptor.capture()); assertEquals(2, statesCaptor.getValue().size()); assertEquals(generateMD5(HMC_XML_CONTENT), statesCaptor.getValue().get(1).getHmcDefinitionHash()); verify(fireflyExtensionRepository).save(fireflyExtensionModel); } @Test public void shouldKeepItemsDefinitionHashOnHmcReset() throws Exception { // given FireflyExtensionModel fireflyExtensionModel = mockExtension(mockState(generateMD5(ITEMS_XML_CONTENT), null)); given(fireflyExtensionRepository.findByName(EXTENSION_WITH_ITEMS_XML)).willReturn(fireflyExtensionModel); // when fireflyExtension.onHmcReset(MIGRATION); // then verify(fireflyExtensionModel).setStates(statesCaptor.capture()); assertEquals(2, statesCaptor.getValue().size()); assertEquals(generateMD5(ITEMS_XML_CONTENT), statesCaptor.getValue().get(1).getItemsDefinitionHash()); verify(fireflyExtensionRepository).save(fireflyExtensionModel); } @Test(expected = SAXException.class) public void shouldHandleExceptionsWhileParsingItemsDefinition() throws Throwable { // given FireflyExtension extensionWithInvalidItemsXml = createExtension(EXTENSION_WITH_INVALID_ITEMS_XML, false); try { // when extensionWithInvalidItemsXml.getItemsDefinitionHash(); } catch (RuntimeException e) {
// Path: src/de/neuland/firefly/migration/MigrationRepository.java // @Repository // @Scope("prototype") // public class MigrationRepository { // @Autowired private ModelService modelService; // // public FireflyMigrationModel findByPk(PK pk) { // return modelService.get(pk); // } // // public FireflyMigrationModel create() { // return modelService.create(FireflyMigrationModel.class); // } // // public void save(FireflyMigrationModel migration) { // modelService.save(migration); // } // } // // Path: testsrc/de/neuland/firefly/TestUtils.java // public static void unwrapException(RuntimeException e) throws Throwable { // if (e.getCause() != null) { // throw e.getCause(); // } else { // throw e; // } // } // // Path: src/de/neuland/firefly/constants/FireflyConstants.java // public static final String NO_HMC_XML_MD5 = "NO_HMC_XML"; // // Path: src/de/neuland/firefly/constants/FireflyConstants.java // public static final String NO_ITEMS_XML_MD5 = "NO_ITEMS_XML"; // // Path: src/de/neuland/firefly/utils/MD5Util.java // public static String generateMD5(String baseValue) { // return generateMD5(baseValue, "UTF-8", "MD5"); // } // Path: testsrc/de/neuland/firefly/extensionfinder/FireflyExtensionTest.java import de.hybris.platform.core.PK; import de.neuland.firefly.migration.MigrationRepository; import de.neuland.firefly.model.FireflyExtensionModel; import de.neuland.firefly.model.FireflyExtensionStateModel; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.xml.sax.SAXException; import java.io.File; import java.net.URL; import java.util.ArrayList; import static de.neuland.firefly.TestUtils.unwrapException; import static de.neuland.firefly.constants.FireflyConstants.NO_HMC_XML_MD5; import static de.neuland.firefly.constants.FireflyConstants.NO_ITEMS_XML_MD5; import static de.neuland.firefly.utils.MD5Util.generateMD5; import static java.util.Arrays.asList; import static org.apache.commons.io.FileUtils.getTempDirectory; import static org.junit.Assert.*; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; fireflyExtension.onHmcReset(MIGRATION); // then verify(fireflyExtensionModel).setStates(statesCaptor.capture()); assertEquals(2, statesCaptor.getValue().size()); assertEquals(generateMD5(HMC_XML_CONTENT), statesCaptor.getValue().get(1).getHmcDefinitionHash()); verify(fireflyExtensionRepository).save(fireflyExtensionModel); } @Test public void shouldKeepItemsDefinitionHashOnHmcReset() throws Exception { // given FireflyExtensionModel fireflyExtensionModel = mockExtension(mockState(generateMD5(ITEMS_XML_CONTENT), null)); given(fireflyExtensionRepository.findByName(EXTENSION_WITH_ITEMS_XML)).willReturn(fireflyExtensionModel); // when fireflyExtension.onHmcReset(MIGRATION); // then verify(fireflyExtensionModel).setStates(statesCaptor.capture()); assertEquals(2, statesCaptor.getValue().size()); assertEquals(generateMD5(ITEMS_XML_CONTENT), statesCaptor.getValue().get(1).getItemsDefinitionHash()); verify(fireflyExtensionRepository).save(fireflyExtensionModel); } @Test(expected = SAXException.class) public void shouldHandleExceptionsWhileParsingItemsDefinition() throws Throwable { // given FireflyExtension extensionWithInvalidItemsXml = createExtension(EXTENSION_WITH_INVALID_ITEMS_XML, false); try { // when extensionWithInvalidItemsXml.getItemsDefinitionHash(); } catch (RuntimeException e) {
unwrapException(e);
neuland/firefly
src/de/neuland/firefly/extensionfinder/FireflySystem.java
// Path: src/de/neuland/firefly/HybrisAdapter.java // @Component // @Scope("prototype") // public class HybrisAdapter { // private static final Logger LOG = Logger.getLogger(HybrisAdapter.class); // private static final String SYSTEM_UPDATE = "System update"; // private static final String HMC_RESET = "HMC Reset"; // @Autowired EventService eventService; // @Autowired CacheController cacheController; // // public void initFirefly() throws Exception { // doInitialize(true); // } // // public void updateSystem(PK migration) throws Exception { // doInitialize(true); // eventService.publishEvent(new SystemUpdatedEvent(getTenantId(), migration)); // } // // private void doInitialize(boolean update) throws Exception { // FireflyJspWriter jspWriter = new FireflyJspWriter(); // try { // MockHttpServletRequest request = new MockHttpServletRequest(); // if (update) { // // up to version 5 // request.addParameter("initmethod", "update"); // request.addParameter("essential", "true"); // // version 6 // request.addParameter("initMethod", "UPDATE"); // request.addParameter("createEssentialData", "true"); // } // request.addParameter("init", "true"); // request.addParameter("default", "false"); // request.addParameter("ALL_EXTENSIONS", "true"); // // up to version 5 // request.addParameter("localizetypes", "true"); // request.addParameter("clearhmc", "true"); // // version 6 // request.addParameter("localizeTypes", "true"); // request.addParameter("clearHMC", "true"); // // JspContext jspContext = new JspContext(jspWriter, request, new MockHttpServletResponse()); // // try { // InitializationLockHandler handler = new InitializationLockHandler(new DefaultInitLockDao()); // String operationName = update ? SYSTEM_UPDATE : HMC_RESET; // // handler.performLocked(Registry.getCurrentTenant(), // createInitializeCallable(jspContext), // operationName); // } catch (NoSuchMethodException e) { // LOG.info(format("Internal reflection unsuccessful: system is not locked while performing '%s only' change.", HMC_RESET)); // Initialization.doInitialize(jspContext); // } // } finally { // LOG.debug(de.hybris.platform.util.Utilities.filterOutHTMLTags(jspWriter.getString())); // } // } // // private Callable<Boolean> createInitializeCallable(final JspContext jspContext) { // return new Callable<Boolean>() { // public Boolean call() throws Exception { // Method m = Initialization.class.getDeclaredMethod("doInitializeImpl", JspContext.class); // m.setAccessible(true); // m.invoke(null, jspContext); // return Boolean.TRUE; // } // }; // } // // public void clearHmcConfiguration(PK migration) throws Exception { // doInitialize(false); // eventService.publishEvent(new HmcResetEvent(getTenantId(), migration)); // } // // public String getTenantId() { // return Registry.getCurrentTenant().getTenantID(); // } // // public void clearJaloCache() { // Registry.getCurrentTenant().getCache().clear(); // } // // /** // * This event is triggered after a system update is done. // */ // public static class SystemUpdatedEvent extends TenantEvent { // private PK migration; // // SystemUpdatedEvent(String tenantId, PK migration) { // super(tenantId); // this.migration = migration; // } // // public PK getMigration() { // return migration; // } // } // // /** // * This event is triggered after a hMC reset is done. // */ // public static class HmcResetEvent extends TenantEvent { // private PK migration; // // HmcResetEvent(String tenantId, PK migration) { // super(tenantId); // this.migration = migration; // } // // public PK getMigration() { // return migration; // } // } // // }
import de.neuland.firefly.HybrisAdapter; import de.neuland.firefly.model.FireflyMigrationModel; import org.apache.log4j.Logger; import org.springframework.util.Assert; import java.io.File; import java.util.*;
package de.neuland.firefly.extensionfinder; /** * Representation of a hybris tenant and its configuration. */ public class FireflySystem { private static final Logger LOG = Logger.getLogger(FireflySystem.class);
// Path: src/de/neuland/firefly/HybrisAdapter.java // @Component // @Scope("prototype") // public class HybrisAdapter { // private static final Logger LOG = Logger.getLogger(HybrisAdapter.class); // private static final String SYSTEM_UPDATE = "System update"; // private static final String HMC_RESET = "HMC Reset"; // @Autowired EventService eventService; // @Autowired CacheController cacheController; // // public void initFirefly() throws Exception { // doInitialize(true); // } // // public void updateSystem(PK migration) throws Exception { // doInitialize(true); // eventService.publishEvent(new SystemUpdatedEvent(getTenantId(), migration)); // } // // private void doInitialize(boolean update) throws Exception { // FireflyJspWriter jspWriter = new FireflyJspWriter(); // try { // MockHttpServletRequest request = new MockHttpServletRequest(); // if (update) { // // up to version 5 // request.addParameter("initmethod", "update"); // request.addParameter("essential", "true"); // // version 6 // request.addParameter("initMethod", "UPDATE"); // request.addParameter("createEssentialData", "true"); // } // request.addParameter("init", "true"); // request.addParameter("default", "false"); // request.addParameter("ALL_EXTENSIONS", "true"); // // up to version 5 // request.addParameter("localizetypes", "true"); // request.addParameter("clearhmc", "true"); // // version 6 // request.addParameter("localizeTypes", "true"); // request.addParameter("clearHMC", "true"); // // JspContext jspContext = new JspContext(jspWriter, request, new MockHttpServletResponse()); // // try { // InitializationLockHandler handler = new InitializationLockHandler(new DefaultInitLockDao()); // String operationName = update ? SYSTEM_UPDATE : HMC_RESET; // // handler.performLocked(Registry.getCurrentTenant(), // createInitializeCallable(jspContext), // operationName); // } catch (NoSuchMethodException e) { // LOG.info(format("Internal reflection unsuccessful: system is not locked while performing '%s only' change.", HMC_RESET)); // Initialization.doInitialize(jspContext); // } // } finally { // LOG.debug(de.hybris.platform.util.Utilities.filterOutHTMLTags(jspWriter.getString())); // } // } // // private Callable<Boolean> createInitializeCallable(final JspContext jspContext) { // return new Callable<Boolean>() { // public Boolean call() throws Exception { // Method m = Initialization.class.getDeclaredMethod("doInitializeImpl", JspContext.class); // m.setAccessible(true); // m.invoke(null, jspContext); // return Boolean.TRUE; // } // }; // } // // public void clearHmcConfiguration(PK migration) throws Exception { // doInitialize(false); // eventService.publishEvent(new HmcResetEvent(getTenantId(), migration)); // } // // public String getTenantId() { // return Registry.getCurrentTenant().getTenantID(); // } // // public void clearJaloCache() { // Registry.getCurrentTenant().getCache().clear(); // } // // /** // * This event is triggered after a system update is done. // */ // public static class SystemUpdatedEvent extends TenantEvent { // private PK migration; // // SystemUpdatedEvent(String tenantId, PK migration) { // super(tenantId); // this.migration = migration; // } // // public PK getMigration() { // return migration; // } // } // // /** // * This event is triggered after a hMC reset is done. // */ // public static class HmcResetEvent extends TenantEvent { // private PK migration; // // HmcResetEvent(String tenantId, PK migration) { // super(tenantId); // this.migration = migration; // } // // public PK getMigration() { // return migration; // } // } // // } // Path: src/de/neuland/firefly/extensionfinder/FireflySystem.java import de.neuland.firefly.HybrisAdapter; import de.neuland.firefly.model.FireflyMigrationModel; import org.apache.log4j.Logger; import org.springframework.util.Assert; import java.io.File; import java.util.*; package de.neuland.firefly.extensionfinder; /** * Representation of a hybris tenant and its configuration. */ public class FireflySystem { private static final Logger LOG = Logger.getLogger(FireflySystem.class);
private HybrisAdapter hybrisAdapter;
neuland/firefly
testsrc/de/neuland/firefly/changes/v1/XMLChangeListTest.java
// Path: testsrc/de/neuland/firefly/TestUtils.java // public class TestUtils { // public static void unwrapException(RuntimeException e) throws Throwable { // if (e.getCause() != null) { // throw e.getCause(); // } else { // throw e; // } // } // // public static <T> T loadXML(Class<T> type, String xmlFile) { // T result = XMLUtil.loadXML(type, getFileFromClasspath(xmlFile)); // assertNotNull(result); // return result; // } // // public static File getFileFromClasspath(String filename) { // URL currentClassPathFolder = TestUtils.class.getClassLoader().getResource(""); // File result = new File(currentClassPathFolder.getFile(), filename); // assertTrue(result.exists()); // return result; // } // }
import de.neuland.firefly.TestUtils; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue;
package de.neuland.firefly.changes.v1; public class XMLChangeListTest { @Test public void shouldParseXmlFile() throws Exception { // given String xmlFile = "resources/changes/v1/changeList.xml"; // when
// Path: testsrc/de/neuland/firefly/TestUtils.java // public class TestUtils { // public static void unwrapException(RuntimeException e) throws Throwable { // if (e.getCause() != null) { // throw e.getCause(); // } else { // throw e; // } // } // // public static <T> T loadXML(Class<T> type, String xmlFile) { // T result = XMLUtil.loadXML(type, getFileFromClasspath(xmlFile)); // assertNotNull(result); // return result; // } // // public static File getFileFromClasspath(String filename) { // URL currentClassPathFolder = TestUtils.class.getClassLoader().getResource(""); // File result = new File(currentClassPathFolder.getFile(), filename); // assertTrue(result.exists()); // return result; // } // } // Path: testsrc/de/neuland/firefly/changes/v1/XMLChangeListTest.java import de.neuland.firefly.TestUtils; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; package de.neuland.firefly.changes.v1; public class XMLChangeListTest { @Test public void shouldParseXmlFile() throws Exception { // given String xmlFile = "resources/changes/v1/changeList.xml"; // when
XMLChangeList changeList = TestUtils.loadXML(XMLChangeList.class, xmlFile);
neuland/firefly
src/de/neuland/firefly/changes/ChangeExecutedEventListener.java
// Path: src/de/neuland/firefly/EventDistributor.java // public abstract class EventDistributor<T extends AbstractEvent, L> extends AbstractEventListener<T> { // private HashMap<String, Set<L>> registeredListener = new HashMap<>(); // // public EventDistributor(ClusterService clusterService, // TenantService tenantService) { // setClusterService(clusterService); // setTenantService(tenantService); // } // // public void registerListener(String tenantId, L listener) { // hasText(tenantId); // notNull(listener); // final Set<L> listeners; // if (registeredListener.containsKey(tenantId)) { // listeners = registeredListener.get(tenantId); // } else { // listeners = new WeakHashSet(); // registeredListener.put(tenantId, listeners); // } // listeners.add(listener); // } // // public void unregisterListener(L listener) { // for (Set<L> listeners : registeredListener.values()) { // listeners.remove(listener); // } // } // // public boolean isListenerRegistered(L listener) { // for (Set<L> listeners : registeredListener.values()) { // if (listeners.contains(listener)) { // return true; // } // } // return false; // } // // protected boolean hasListenersForTenant(String tenantId) { // return registeredListener.containsKey(tenantId); // } // // protected Set<L> getListenersForTenant(String tenantId) { // return registeredListener.get(tenantId); // } // // // overridden to neutralize @Required annotation of method id super class // @Override // public void setClusterService(ClusterService clusterService) { // super.setClusterService(clusterService); // } // // // overridden to neutralize @Required annotation of method id super class // @Override // public void setTenantService(TenantService tenantService) { // super.setTenantService(tenantService); // } // } // // Path: src/de/neuland/firefly/extensionfinder/FireflyExtensionRepository.java // @Repository // @Scope("prototype") // public class FireflyExtensionRepository { // @Autowired ModelService modelService; // @Autowired FlexibleSearchService searchService; // // public FireflyExtensionModel findByName(String name) throws FireflyExtensionNotFoundException, FireflyNotInstalledException { // final FlexibleSearchQuery query = new FlexibleSearchQuery( // "SELECT {" + FireflyExtensionModel.PK + "} " + // "FROM {" + FireflyExtensionModel._TYPECODE + "} " + // "WHERE {" + FireflyExtensionModel.NAME + "} = ?name"); // query.addQueryParameter("name", name); // try { // return searchService.searchUnique(query); // } catch (FlexibleSearchException e) { // throw new FireflyNotInstalledException(e); // } catch (ModelNotFoundException e) { // throw new FireflyExtensionNotFoundException(name); // } // } // // public FireflyExtensionModel create(String name) { // Assert.hasText(name); // FireflyExtensionModel result = new FireflyExtensionModel(); // result.setName(name); // result.setStates(new ArrayList<FireflyExtensionStateModel>()); // return result; // } // // public void save(FireflyExtensionModel model) { // modelService.save(model); // } // // public static class FireflyNotInstalledException extends RuntimeException { // public FireflyNotInstalledException(Exception e) { // super(e); // } // } // // public static class FireflyExtensionNotFoundException extends Exception { // private String name; // // public FireflyExtensionNotFoundException(String name) { // super("No " + FireflyExtensionModel._TYPECODE + " found for name=" + name); // this.name = name; // } // // public String getName() { // return name; // } // } // }
import de.hybris.platform.servicelayer.cluster.ClusterService; import de.hybris.platform.servicelayer.tenant.TenantService; import de.neuland.firefly.EventDistributor; import de.neuland.firefly.extensionfinder.FireflyExtensionRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component;
package de.neuland.firefly.changes; @Component @Scope("singleton")
// Path: src/de/neuland/firefly/EventDistributor.java // public abstract class EventDistributor<T extends AbstractEvent, L> extends AbstractEventListener<T> { // private HashMap<String, Set<L>> registeredListener = new HashMap<>(); // // public EventDistributor(ClusterService clusterService, // TenantService tenantService) { // setClusterService(clusterService); // setTenantService(tenantService); // } // // public void registerListener(String tenantId, L listener) { // hasText(tenantId); // notNull(listener); // final Set<L> listeners; // if (registeredListener.containsKey(tenantId)) { // listeners = registeredListener.get(tenantId); // } else { // listeners = new WeakHashSet(); // registeredListener.put(tenantId, listeners); // } // listeners.add(listener); // } // // public void unregisterListener(L listener) { // for (Set<L> listeners : registeredListener.values()) { // listeners.remove(listener); // } // } // // public boolean isListenerRegistered(L listener) { // for (Set<L> listeners : registeredListener.values()) { // if (listeners.contains(listener)) { // return true; // } // } // return false; // } // // protected boolean hasListenersForTenant(String tenantId) { // return registeredListener.containsKey(tenantId); // } // // protected Set<L> getListenersForTenant(String tenantId) { // return registeredListener.get(tenantId); // } // // // overridden to neutralize @Required annotation of method id super class // @Override // public void setClusterService(ClusterService clusterService) { // super.setClusterService(clusterService); // } // // // overridden to neutralize @Required annotation of method id super class // @Override // public void setTenantService(TenantService tenantService) { // super.setTenantService(tenantService); // } // } // // Path: src/de/neuland/firefly/extensionfinder/FireflyExtensionRepository.java // @Repository // @Scope("prototype") // public class FireflyExtensionRepository { // @Autowired ModelService modelService; // @Autowired FlexibleSearchService searchService; // // public FireflyExtensionModel findByName(String name) throws FireflyExtensionNotFoundException, FireflyNotInstalledException { // final FlexibleSearchQuery query = new FlexibleSearchQuery( // "SELECT {" + FireflyExtensionModel.PK + "} " + // "FROM {" + FireflyExtensionModel._TYPECODE + "} " + // "WHERE {" + FireflyExtensionModel.NAME + "} = ?name"); // query.addQueryParameter("name", name); // try { // return searchService.searchUnique(query); // } catch (FlexibleSearchException e) { // throw new FireflyNotInstalledException(e); // } catch (ModelNotFoundException e) { // throw new FireflyExtensionNotFoundException(name); // } // } // // public FireflyExtensionModel create(String name) { // Assert.hasText(name); // FireflyExtensionModel result = new FireflyExtensionModel(); // result.setName(name); // result.setStates(new ArrayList<FireflyExtensionStateModel>()); // return result; // } // // public void save(FireflyExtensionModel model) { // modelService.save(model); // } // // public static class FireflyNotInstalledException extends RuntimeException { // public FireflyNotInstalledException(Exception e) { // super(e); // } // } // // public static class FireflyExtensionNotFoundException extends Exception { // private String name; // // public FireflyExtensionNotFoundException(String name) { // super("No " + FireflyExtensionModel._TYPECODE + " found for name=" + name); // this.name = name; // } // // public String getName() { // return name; // } // } // } // Path: src/de/neuland/firefly/changes/ChangeExecutedEventListener.java import de.hybris.platform.servicelayer.cluster.ClusterService; import de.hybris.platform.servicelayer.tenant.TenantService; import de.neuland.firefly.EventDistributor; import de.neuland.firefly.extensionfinder.FireflyExtensionRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; package de.neuland.firefly.changes; @Component @Scope("singleton")
public class ChangeExecutedEventListener extends EventDistributor<ChangeExecutedEvent, Change> {
neuland/firefly
src/de/neuland/firefly/changes/ChangeExecutedEventListener.java
// Path: src/de/neuland/firefly/EventDistributor.java // public abstract class EventDistributor<T extends AbstractEvent, L> extends AbstractEventListener<T> { // private HashMap<String, Set<L>> registeredListener = new HashMap<>(); // // public EventDistributor(ClusterService clusterService, // TenantService tenantService) { // setClusterService(clusterService); // setTenantService(tenantService); // } // // public void registerListener(String tenantId, L listener) { // hasText(tenantId); // notNull(listener); // final Set<L> listeners; // if (registeredListener.containsKey(tenantId)) { // listeners = registeredListener.get(tenantId); // } else { // listeners = new WeakHashSet(); // registeredListener.put(tenantId, listeners); // } // listeners.add(listener); // } // // public void unregisterListener(L listener) { // for (Set<L> listeners : registeredListener.values()) { // listeners.remove(listener); // } // } // // public boolean isListenerRegistered(L listener) { // for (Set<L> listeners : registeredListener.values()) { // if (listeners.contains(listener)) { // return true; // } // } // return false; // } // // protected boolean hasListenersForTenant(String tenantId) { // return registeredListener.containsKey(tenantId); // } // // protected Set<L> getListenersForTenant(String tenantId) { // return registeredListener.get(tenantId); // } // // // overridden to neutralize @Required annotation of method id super class // @Override // public void setClusterService(ClusterService clusterService) { // super.setClusterService(clusterService); // } // // // overridden to neutralize @Required annotation of method id super class // @Override // public void setTenantService(TenantService tenantService) { // super.setTenantService(tenantService); // } // } // // Path: src/de/neuland/firefly/extensionfinder/FireflyExtensionRepository.java // @Repository // @Scope("prototype") // public class FireflyExtensionRepository { // @Autowired ModelService modelService; // @Autowired FlexibleSearchService searchService; // // public FireflyExtensionModel findByName(String name) throws FireflyExtensionNotFoundException, FireflyNotInstalledException { // final FlexibleSearchQuery query = new FlexibleSearchQuery( // "SELECT {" + FireflyExtensionModel.PK + "} " + // "FROM {" + FireflyExtensionModel._TYPECODE + "} " + // "WHERE {" + FireflyExtensionModel.NAME + "} = ?name"); // query.addQueryParameter("name", name); // try { // return searchService.searchUnique(query); // } catch (FlexibleSearchException e) { // throw new FireflyNotInstalledException(e); // } catch (ModelNotFoundException e) { // throw new FireflyExtensionNotFoundException(name); // } // } // // public FireflyExtensionModel create(String name) { // Assert.hasText(name); // FireflyExtensionModel result = new FireflyExtensionModel(); // result.setName(name); // result.setStates(new ArrayList<FireflyExtensionStateModel>()); // return result; // } // // public void save(FireflyExtensionModel model) { // modelService.save(model); // } // // public static class FireflyNotInstalledException extends RuntimeException { // public FireflyNotInstalledException(Exception e) { // super(e); // } // } // // public static class FireflyExtensionNotFoundException extends Exception { // private String name; // // public FireflyExtensionNotFoundException(String name) { // super("No " + FireflyExtensionModel._TYPECODE + " found for name=" + name); // this.name = name; // } // // public String getName() { // return name; // } // } // }
import de.hybris.platform.servicelayer.cluster.ClusterService; import de.hybris.platform.servicelayer.tenant.TenantService; import de.neuland.firefly.EventDistributor; import de.neuland.firefly.extensionfinder.FireflyExtensionRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component;
package de.neuland.firefly.changes; @Component @Scope("singleton") public class ChangeExecutedEventListener extends EventDistributor<ChangeExecutedEvent, Change> { @Autowired public ChangeExecutedEventListener(ClusterService clusterService, TenantService tenantService, ApplicationContext applicationContext) { super(clusterService, tenantService); super.setApplicationContext(applicationContext); } @Override protected void onEvent(ChangeExecutedEvent event) { if (!hasListenersForTenant(event.getTenantId())) { return; } try { for (Change change : getListenersForTenant(event.getTenantId())) { if (change.equals(event.getChange())) { change.onExecution(event.getMigration()); } }
// Path: src/de/neuland/firefly/EventDistributor.java // public abstract class EventDistributor<T extends AbstractEvent, L> extends AbstractEventListener<T> { // private HashMap<String, Set<L>> registeredListener = new HashMap<>(); // // public EventDistributor(ClusterService clusterService, // TenantService tenantService) { // setClusterService(clusterService); // setTenantService(tenantService); // } // // public void registerListener(String tenantId, L listener) { // hasText(tenantId); // notNull(listener); // final Set<L> listeners; // if (registeredListener.containsKey(tenantId)) { // listeners = registeredListener.get(tenantId); // } else { // listeners = new WeakHashSet(); // registeredListener.put(tenantId, listeners); // } // listeners.add(listener); // } // // public void unregisterListener(L listener) { // for (Set<L> listeners : registeredListener.values()) { // listeners.remove(listener); // } // } // // public boolean isListenerRegistered(L listener) { // for (Set<L> listeners : registeredListener.values()) { // if (listeners.contains(listener)) { // return true; // } // } // return false; // } // // protected boolean hasListenersForTenant(String tenantId) { // return registeredListener.containsKey(tenantId); // } // // protected Set<L> getListenersForTenant(String tenantId) { // return registeredListener.get(tenantId); // } // // // overridden to neutralize @Required annotation of method id super class // @Override // public void setClusterService(ClusterService clusterService) { // super.setClusterService(clusterService); // } // // // overridden to neutralize @Required annotation of method id super class // @Override // public void setTenantService(TenantService tenantService) { // super.setTenantService(tenantService); // } // } // // Path: src/de/neuland/firefly/extensionfinder/FireflyExtensionRepository.java // @Repository // @Scope("prototype") // public class FireflyExtensionRepository { // @Autowired ModelService modelService; // @Autowired FlexibleSearchService searchService; // // public FireflyExtensionModel findByName(String name) throws FireflyExtensionNotFoundException, FireflyNotInstalledException { // final FlexibleSearchQuery query = new FlexibleSearchQuery( // "SELECT {" + FireflyExtensionModel.PK + "} " + // "FROM {" + FireflyExtensionModel._TYPECODE + "} " + // "WHERE {" + FireflyExtensionModel.NAME + "} = ?name"); // query.addQueryParameter("name", name); // try { // return searchService.searchUnique(query); // } catch (FlexibleSearchException e) { // throw new FireflyNotInstalledException(e); // } catch (ModelNotFoundException e) { // throw new FireflyExtensionNotFoundException(name); // } // } // // public FireflyExtensionModel create(String name) { // Assert.hasText(name); // FireflyExtensionModel result = new FireflyExtensionModel(); // result.setName(name); // result.setStates(new ArrayList<FireflyExtensionStateModel>()); // return result; // } // // public void save(FireflyExtensionModel model) { // modelService.save(model); // } // // public static class FireflyNotInstalledException extends RuntimeException { // public FireflyNotInstalledException(Exception e) { // super(e); // } // } // // public static class FireflyExtensionNotFoundException extends Exception { // private String name; // // public FireflyExtensionNotFoundException(String name) { // super("No " + FireflyExtensionModel._TYPECODE + " found for name=" + name); // this.name = name; // } // // public String getName() { // return name; // } // } // } // Path: src/de/neuland/firefly/changes/ChangeExecutedEventListener.java import de.hybris.platform.servicelayer.cluster.ClusterService; import de.hybris.platform.servicelayer.tenant.TenantService; import de.neuland.firefly.EventDistributor; import de.neuland.firefly.extensionfinder.FireflyExtensionRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; package de.neuland.firefly.changes; @Component @Scope("singleton") public class ChangeExecutedEventListener extends EventDistributor<ChangeExecutedEvent, Change> { @Autowired public ChangeExecutedEventListener(ClusterService clusterService, TenantService tenantService, ApplicationContext applicationContext) { super(clusterService, tenantService); super.setApplicationContext(applicationContext); } @Override protected void onEvent(ChangeExecutedEvent event) { if (!hasListenersForTenant(event.getTenantId())) { return; } try { for (Change change : getListenersForTenant(event.getTenantId())) { if (change.equals(event.getChange())) { change.onExecution(event.getMigration()); } }
} catch (FireflyExtensionRepository.FireflyExtensionNotFoundException e) {
neuland/firefly
testsrc/de/neuland/firefly/changes/v1/XMLChangeDescriptionTest.java
// Path: testsrc/de/neuland/firefly/TestUtils.java // public class TestUtils { // public static void unwrapException(RuntimeException e) throws Throwable { // if (e.getCause() != null) { // throw e.getCause(); // } else { // throw e; // } // } // // public static <T> T loadXML(Class<T> type, String xmlFile) { // T result = XMLUtil.loadXML(type, getFileFromClasspath(xmlFile)); // assertNotNull(result); // return result; // } // // public static File getFileFromClasspath(String filename) { // URL currentClassPathFolder = TestUtils.class.getClassLoader().getResource(""); // File result = new File(currentClassPathFolder.getFile(), filename); // assertTrue(result.exists()); // return result; // } // }
import de.neuland.firefly.TestUtils; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue;
package de.neuland.firefly.changes.v1; public class XMLChangeDescriptionTest { @Test public void shouldParseChangeList() throws Exception { // given String xmlFile = "resources/changes/v1/changeDescription.xml"; // when
// Path: testsrc/de/neuland/firefly/TestUtils.java // public class TestUtils { // public static void unwrapException(RuntimeException e) throws Throwable { // if (e.getCause() != null) { // throw e.getCause(); // } else { // throw e; // } // } // // public static <T> T loadXML(Class<T> type, String xmlFile) { // T result = XMLUtil.loadXML(type, getFileFromClasspath(xmlFile)); // assertNotNull(result); // return result; // } // // public static File getFileFromClasspath(String filename) { // URL currentClassPathFolder = TestUtils.class.getClassLoader().getResource(""); // File result = new File(currentClassPathFolder.getFile(), filename); // assertTrue(result.exists()); // return result; // } // } // Path: testsrc/de/neuland/firefly/changes/v1/XMLChangeDescriptionTest.java import de.neuland.firefly.TestUtils; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; package de.neuland.firefly.changes.v1; public class XMLChangeDescriptionTest { @Test public void shouldParseChangeList() throws Exception { // given String xmlFile = "resources/changes/v1/changeDescription.xml"; // when
XMLChangeDescription changeDescription = TestUtils.loadXML(XMLChangeDescription.class, xmlFile);
neuland/firefly
testsrc/de/neuland/firefly/TestUtils.java
// Path: src/de/neuland/firefly/utils/XMLUtil.java // public class XMLUtil { // public static String loadAndNormalizeXML(File xmlFile) throws ParserConfigurationException, SAXException, IOException, TransformerException { // DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); // DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); // Document doc = dBuilder.parse(xmlFile); // // removeRecursively(doc); // doc.normalizeDocument(); // // TransformerFactory tf = TransformerFactory.newInstance(); // Transformer transformer = tf.newTransformer(); // transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); // transformer.setOutputProperty(OutputKeys.INDENT, "no"); // StringWriter normalizedXml = new StringWriter(); // transformer.transform(new DOMSource(doc), new StreamResult(normalizedXml)); // return normalizedXml.toString(); // } // // public static <T> T loadXML(Class<T> type, File sourceFile) { // return loadXML(type, null, sourceFile); // } // // public static <T> T loadXML(Class<T> type, String schemaLocation, File sourceFile) { // try { // Unmarshaller unmarshaller = JAXBContext.newInstance(type).createUnmarshaller(); // if (isNotEmpty(schemaLocation)) { // unmarshaller.setSchema(SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(type.getClassLoader().getResource(schemaLocation))); // } // return (T) unmarshaller.unmarshal(sourceFile); // } catch (JAXBException | SAXException e) { // throw new RuntimeException(e); // } // } // // static void removeRecursively(Node node) { // if (node == null) { // return; // } // if (isIrrelevantNode(node)) { // removeRecursively(node.getNextSibling()); // node.getParentNode().removeChild(node); // } else { // NodeList childNotes = node.getChildNodes(); // for (int i = 0; i < childNotes.getLength(); i++) { // removeRecursively(childNotes.item(i)); // } // } // } // // private static boolean isIrrelevantNode(Node node) { // if (COMMENT_NODE == node.getNodeType()) { // return true; // } // return TEXT_NODE == node.getNodeType() && isBlank(node.getTextContent()); // } // }
import de.neuland.firefly.utils.XMLUtil; import java.io.File; import java.net.URL; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue;
package de.neuland.firefly; public class TestUtils { public static void unwrapException(RuntimeException e) throws Throwable { if (e.getCause() != null) { throw e.getCause(); } else { throw e; } } public static <T> T loadXML(Class<T> type, String xmlFile) {
// Path: src/de/neuland/firefly/utils/XMLUtil.java // public class XMLUtil { // public static String loadAndNormalizeXML(File xmlFile) throws ParserConfigurationException, SAXException, IOException, TransformerException { // DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); // DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); // Document doc = dBuilder.parse(xmlFile); // // removeRecursively(doc); // doc.normalizeDocument(); // // TransformerFactory tf = TransformerFactory.newInstance(); // Transformer transformer = tf.newTransformer(); // transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); // transformer.setOutputProperty(OutputKeys.INDENT, "no"); // StringWriter normalizedXml = new StringWriter(); // transformer.transform(new DOMSource(doc), new StreamResult(normalizedXml)); // return normalizedXml.toString(); // } // // public static <T> T loadXML(Class<T> type, File sourceFile) { // return loadXML(type, null, sourceFile); // } // // public static <T> T loadXML(Class<T> type, String schemaLocation, File sourceFile) { // try { // Unmarshaller unmarshaller = JAXBContext.newInstance(type).createUnmarshaller(); // if (isNotEmpty(schemaLocation)) { // unmarshaller.setSchema(SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(type.getClassLoader().getResource(schemaLocation))); // } // return (T) unmarshaller.unmarshal(sourceFile); // } catch (JAXBException | SAXException e) { // throw new RuntimeException(e); // } // } // // static void removeRecursively(Node node) { // if (node == null) { // return; // } // if (isIrrelevantNode(node)) { // removeRecursively(node.getNextSibling()); // node.getParentNode().removeChild(node); // } else { // NodeList childNotes = node.getChildNodes(); // for (int i = 0; i < childNotes.getLength(); i++) { // removeRecursively(childNotes.item(i)); // } // } // } // // private static boolean isIrrelevantNode(Node node) { // if (COMMENT_NODE == node.getNodeType()) { // return true; // } // return TEXT_NODE == node.getNodeType() && isBlank(node.getTextContent()); // } // } // Path: testsrc/de/neuland/firefly/TestUtils.java import de.neuland.firefly.utils.XMLUtil; import java.io.File; import java.net.URL; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; package de.neuland.firefly; public class TestUtils { public static void unwrapException(RuntimeException e) throws Throwable { if (e.getCause() != null) { throw e.getCause(); } else { throw e; } } public static <T> T loadXML(Class<T> type, String xmlFile) {
T result = XMLUtil.loadXML(type, getFileFromClasspath(xmlFile));
neuland/firefly
testsrc/de/neuland/firefly/changes/ChangeFactoryTest.java
// Path: testsrc/de/neuland/firefly/TestUtils.java // public class TestUtils { // public static void unwrapException(RuntimeException e) throws Throwable { // if (e.getCause() != null) { // throw e.getCause(); // } else { // throw e; // } // } // // public static <T> T loadXML(Class<T> type, String xmlFile) { // T result = XMLUtil.loadXML(type, getFileFromClasspath(xmlFile)); // assertNotNull(result); // return result; // } // // public static File getFileFromClasspath(String filename) { // URL currentClassPathFolder = TestUtils.class.getClassLoader().getResource(""); // File result = new File(currentClassPathFolder.getFile(), filename); // assertTrue(result.exists()); // return result; // } // } // // Path: testsrc/de/neuland/firefly/TestUtils.java // public static File getFileFromClasspath(String filename) { // URL currentClassPathFolder = TestUtils.class.getClassLoader().getResource(""); // File result = new File(currentClassPathFolder.getFile(), filename); // assertTrue(result.exists()); // return result; // }
import de.neuland.firefly.TestUtils; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.runners.MockitoJUnitRunner; import java.io.File; import java.net.URL; import static de.neuland.firefly.TestUtils.getFileFromClasspath; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue;
package de.neuland.firefly.changes; @RunWith(MockitoJUnitRunner.class) public class ChangeFactoryTest { private ChangeFactory changeFactory = new ChangeFactory();
// Path: testsrc/de/neuland/firefly/TestUtils.java // public class TestUtils { // public static void unwrapException(RuntimeException e) throws Throwable { // if (e.getCause() != null) { // throw e.getCause(); // } else { // throw e; // } // } // // public static <T> T loadXML(Class<T> type, String xmlFile) { // T result = XMLUtil.loadXML(type, getFileFromClasspath(xmlFile)); // assertNotNull(result); // return result; // } // // public static File getFileFromClasspath(String filename) { // URL currentClassPathFolder = TestUtils.class.getClassLoader().getResource(""); // File result = new File(currentClassPathFolder.getFile(), filename); // assertTrue(result.exists()); // return result; // } // } // // Path: testsrc/de/neuland/firefly/TestUtils.java // public static File getFileFromClasspath(String filename) { // URL currentClassPathFolder = TestUtils.class.getClassLoader().getResource(""); // File result = new File(currentClassPathFolder.getFile(), filename); // assertTrue(result.exists()); // return result; // } // Path: testsrc/de/neuland/firefly/changes/ChangeFactoryTest.java import de.neuland.firefly.TestUtils; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.runners.MockitoJUnitRunner; import java.io.File; import java.net.URL; import static de.neuland.firefly.TestUtils.getFileFromClasspath; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; package de.neuland.firefly.changes; @RunWith(MockitoJUnitRunner.class) public class ChangeFactoryTest { private ChangeFactory changeFactory = new ChangeFactory();
private File changeList = getFileFromClasspath("resources/changes/v1/changeList.xml");
neuland/firefly
src/de/neuland/firefly/extensionfinder/FireflySystemFactory.java
// Path: src/de/neuland/firefly/HybrisAdapter.java // @Component // @Scope("prototype") // public class HybrisAdapter { // private static final Logger LOG = Logger.getLogger(HybrisAdapter.class); // private static final String SYSTEM_UPDATE = "System update"; // private static final String HMC_RESET = "HMC Reset"; // @Autowired EventService eventService; // @Autowired CacheController cacheController; // // public void initFirefly() throws Exception { // doInitialize(true); // } // // public void updateSystem(PK migration) throws Exception { // doInitialize(true); // eventService.publishEvent(new SystemUpdatedEvent(getTenantId(), migration)); // } // // private void doInitialize(boolean update) throws Exception { // FireflyJspWriter jspWriter = new FireflyJspWriter(); // try { // MockHttpServletRequest request = new MockHttpServletRequest(); // if (update) { // // up to version 5 // request.addParameter("initmethod", "update"); // request.addParameter("essential", "true"); // // version 6 // request.addParameter("initMethod", "UPDATE"); // request.addParameter("createEssentialData", "true"); // } // request.addParameter("init", "true"); // request.addParameter("default", "false"); // request.addParameter("ALL_EXTENSIONS", "true"); // // up to version 5 // request.addParameter("localizetypes", "true"); // request.addParameter("clearhmc", "true"); // // version 6 // request.addParameter("localizeTypes", "true"); // request.addParameter("clearHMC", "true"); // // JspContext jspContext = new JspContext(jspWriter, request, new MockHttpServletResponse()); // // try { // InitializationLockHandler handler = new InitializationLockHandler(new DefaultInitLockDao()); // String operationName = update ? SYSTEM_UPDATE : HMC_RESET; // // handler.performLocked(Registry.getCurrentTenant(), // createInitializeCallable(jspContext), // operationName); // } catch (NoSuchMethodException e) { // LOG.info(format("Internal reflection unsuccessful: system is not locked while performing '%s only' change.", HMC_RESET)); // Initialization.doInitialize(jspContext); // } // } finally { // LOG.debug(de.hybris.platform.util.Utilities.filterOutHTMLTags(jspWriter.getString())); // } // } // // private Callable<Boolean> createInitializeCallable(final JspContext jspContext) { // return new Callable<Boolean>() { // public Boolean call() throws Exception { // Method m = Initialization.class.getDeclaredMethod("doInitializeImpl", JspContext.class); // m.setAccessible(true); // m.invoke(null, jspContext); // return Boolean.TRUE; // } // }; // } // // public void clearHmcConfiguration(PK migration) throws Exception { // doInitialize(false); // eventService.publishEvent(new HmcResetEvent(getTenantId(), migration)); // } // // public String getTenantId() { // return Registry.getCurrentTenant().getTenantID(); // } // // public void clearJaloCache() { // Registry.getCurrentTenant().getCache().clear(); // } // // /** // * This event is triggered after a system update is done. // */ // public static class SystemUpdatedEvent extends TenantEvent { // private PK migration; // // SystemUpdatedEvent(String tenantId, PK migration) { // super(tenantId); // this.migration = migration; // } // // public PK getMigration() { // return migration; // } // } // // /** // * This event is triggered after a hMC reset is done. // */ // public static class HmcResetEvent extends TenantEvent { // private PK migration; // // HmcResetEvent(String tenantId, PK migration) { // super(tenantId); // this.migration = migration; // } // // public PK getMigration() { // return migration; // } // } // // } // // Path: src/de/neuland/firefly/migration/MigrationRepository.java // @Repository // @Scope("prototype") // public class MigrationRepository { // @Autowired private ModelService modelService; // // public FireflyMigrationModel findByPk(PK pk) { // return modelService.get(pk); // } // // public FireflyMigrationModel create() { // return modelService.create(FireflyMigrationModel.class); // } // // public void save(FireflyMigrationModel migration) { // modelService.save(migration); // } // }
import de.hybris.bootstrap.config.ExtensionInfo; import de.hybris.platform.core.Registry; import de.hybris.platform.util.Utilities; import de.neuland.firefly.HybrisAdapter; import de.neuland.firefly.migration.MigrationRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import java.util.ArrayList; import java.util.List;
package de.neuland.firefly.extensionfinder; @Component @Scope("prototype") public class FireflySystemFactory { @Autowired private FireflyExtensionRepository fireflyExtensionRepository;
// Path: src/de/neuland/firefly/HybrisAdapter.java // @Component // @Scope("prototype") // public class HybrisAdapter { // private static final Logger LOG = Logger.getLogger(HybrisAdapter.class); // private static final String SYSTEM_UPDATE = "System update"; // private static final String HMC_RESET = "HMC Reset"; // @Autowired EventService eventService; // @Autowired CacheController cacheController; // // public void initFirefly() throws Exception { // doInitialize(true); // } // // public void updateSystem(PK migration) throws Exception { // doInitialize(true); // eventService.publishEvent(new SystemUpdatedEvent(getTenantId(), migration)); // } // // private void doInitialize(boolean update) throws Exception { // FireflyJspWriter jspWriter = new FireflyJspWriter(); // try { // MockHttpServletRequest request = new MockHttpServletRequest(); // if (update) { // // up to version 5 // request.addParameter("initmethod", "update"); // request.addParameter("essential", "true"); // // version 6 // request.addParameter("initMethod", "UPDATE"); // request.addParameter("createEssentialData", "true"); // } // request.addParameter("init", "true"); // request.addParameter("default", "false"); // request.addParameter("ALL_EXTENSIONS", "true"); // // up to version 5 // request.addParameter("localizetypes", "true"); // request.addParameter("clearhmc", "true"); // // version 6 // request.addParameter("localizeTypes", "true"); // request.addParameter("clearHMC", "true"); // // JspContext jspContext = new JspContext(jspWriter, request, new MockHttpServletResponse()); // // try { // InitializationLockHandler handler = new InitializationLockHandler(new DefaultInitLockDao()); // String operationName = update ? SYSTEM_UPDATE : HMC_RESET; // // handler.performLocked(Registry.getCurrentTenant(), // createInitializeCallable(jspContext), // operationName); // } catch (NoSuchMethodException e) { // LOG.info(format("Internal reflection unsuccessful: system is not locked while performing '%s only' change.", HMC_RESET)); // Initialization.doInitialize(jspContext); // } // } finally { // LOG.debug(de.hybris.platform.util.Utilities.filterOutHTMLTags(jspWriter.getString())); // } // } // // private Callable<Boolean> createInitializeCallable(final JspContext jspContext) { // return new Callable<Boolean>() { // public Boolean call() throws Exception { // Method m = Initialization.class.getDeclaredMethod("doInitializeImpl", JspContext.class); // m.setAccessible(true); // m.invoke(null, jspContext); // return Boolean.TRUE; // } // }; // } // // public void clearHmcConfiguration(PK migration) throws Exception { // doInitialize(false); // eventService.publishEvent(new HmcResetEvent(getTenantId(), migration)); // } // // public String getTenantId() { // return Registry.getCurrentTenant().getTenantID(); // } // // public void clearJaloCache() { // Registry.getCurrentTenant().getCache().clear(); // } // // /** // * This event is triggered after a system update is done. // */ // public static class SystemUpdatedEvent extends TenantEvent { // private PK migration; // // SystemUpdatedEvent(String tenantId, PK migration) { // super(tenantId); // this.migration = migration; // } // // public PK getMigration() { // return migration; // } // } // // /** // * This event is triggered after a hMC reset is done. // */ // public static class HmcResetEvent extends TenantEvent { // private PK migration; // // HmcResetEvent(String tenantId, PK migration) { // super(tenantId); // this.migration = migration; // } // // public PK getMigration() { // return migration; // } // } // // } // // Path: src/de/neuland/firefly/migration/MigrationRepository.java // @Repository // @Scope("prototype") // public class MigrationRepository { // @Autowired private ModelService modelService; // // public FireflyMigrationModel findByPk(PK pk) { // return modelService.get(pk); // } // // public FireflyMigrationModel create() { // return modelService.create(FireflyMigrationModel.class); // } // // public void save(FireflyMigrationModel migration) { // modelService.save(migration); // } // } // Path: src/de/neuland/firefly/extensionfinder/FireflySystemFactory.java import de.hybris.bootstrap.config.ExtensionInfo; import de.hybris.platform.core.Registry; import de.hybris.platform.util.Utilities; import de.neuland.firefly.HybrisAdapter; import de.neuland.firefly.migration.MigrationRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import java.util.ArrayList; import java.util.List; package de.neuland.firefly.extensionfinder; @Component @Scope("prototype") public class FireflySystemFactory { @Autowired private FireflyExtensionRepository fireflyExtensionRepository;
@Autowired private MigrationRepository migrationRepository;
neuland/firefly
src/de/neuland/firefly/extensionfinder/FireflySystemFactory.java
// Path: src/de/neuland/firefly/HybrisAdapter.java // @Component // @Scope("prototype") // public class HybrisAdapter { // private static final Logger LOG = Logger.getLogger(HybrisAdapter.class); // private static final String SYSTEM_UPDATE = "System update"; // private static final String HMC_RESET = "HMC Reset"; // @Autowired EventService eventService; // @Autowired CacheController cacheController; // // public void initFirefly() throws Exception { // doInitialize(true); // } // // public void updateSystem(PK migration) throws Exception { // doInitialize(true); // eventService.publishEvent(new SystemUpdatedEvent(getTenantId(), migration)); // } // // private void doInitialize(boolean update) throws Exception { // FireflyJspWriter jspWriter = new FireflyJspWriter(); // try { // MockHttpServletRequest request = new MockHttpServletRequest(); // if (update) { // // up to version 5 // request.addParameter("initmethod", "update"); // request.addParameter("essential", "true"); // // version 6 // request.addParameter("initMethod", "UPDATE"); // request.addParameter("createEssentialData", "true"); // } // request.addParameter("init", "true"); // request.addParameter("default", "false"); // request.addParameter("ALL_EXTENSIONS", "true"); // // up to version 5 // request.addParameter("localizetypes", "true"); // request.addParameter("clearhmc", "true"); // // version 6 // request.addParameter("localizeTypes", "true"); // request.addParameter("clearHMC", "true"); // // JspContext jspContext = new JspContext(jspWriter, request, new MockHttpServletResponse()); // // try { // InitializationLockHandler handler = new InitializationLockHandler(new DefaultInitLockDao()); // String operationName = update ? SYSTEM_UPDATE : HMC_RESET; // // handler.performLocked(Registry.getCurrentTenant(), // createInitializeCallable(jspContext), // operationName); // } catch (NoSuchMethodException e) { // LOG.info(format("Internal reflection unsuccessful: system is not locked while performing '%s only' change.", HMC_RESET)); // Initialization.doInitialize(jspContext); // } // } finally { // LOG.debug(de.hybris.platform.util.Utilities.filterOutHTMLTags(jspWriter.getString())); // } // } // // private Callable<Boolean> createInitializeCallable(final JspContext jspContext) { // return new Callable<Boolean>() { // public Boolean call() throws Exception { // Method m = Initialization.class.getDeclaredMethod("doInitializeImpl", JspContext.class); // m.setAccessible(true); // m.invoke(null, jspContext); // return Boolean.TRUE; // } // }; // } // // public void clearHmcConfiguration(PK migration) throws Exception { // doInitialize(false); // eventService.publishEvent(new HmcResetEvent(getTenantId(), migration)); // } // // public String getTenantId() { // return Registry.getCurrentTenant().getTenantID(); // } // // public void clearJaloCache() { // Registry.getCurrentTenant().getCache().clear(); // } // // /** // * This event is triggered after a system update is done. // */ // public static class SystemUpdatedEvent extends TenantEvent { // private PK migration; // // SystemUpdatedEvent(String tenantId, PK migration) { // super(tenantId); // this.migration = migration; // } // // public PK getMigration() { // return migration; // } // } // // /** // * This event is triggered after a hMC reset is done. // */ // public static class HmcResetEvent extends TenantEvent { // private PK migration; // // HmcResetEvent(String tenantId, PK migration) { // super(tenantId); // this.migration = migration; // } // // public PK getMigration() { // return migration; // } // } // // } // // Path: src/de/neuland/firefly/migration/MigrationRepository.java // @Repository // @Scope("prototype") // public class MigrationRepository { // @Autowired private ModelService modelService; // // public FireflyMigrationModel findByPk(PK pk) { // return modelService.get(pk); // } // // public FireflyMigrationModel create() { // return modelService.create(FireflyMigrationModel.class); // } // // public void save(FireflyMigrationModel migration) { // modelService.save(migration); // } // }
import de.hybris.bootstrap.config.ExtensionInfo; import de.hybris.platform.core.Registry; import de.hybris.platform.util.Utilities; import de.neuland.firefly.HybrisAdapter; import de.neuland.firefly.migration.MigrationRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import java.util.ArrayList; import java.util.List;
package de.neuland.firefly.extensionfinder; @Component @Scope("prototype") public class FireflySystemFactory { @Autowired private FireflyExtensionRepository fireflyExtensionRepository; @Autowired private MigrationRepository migrationRepository;
// Path: src/de/neuland/firefly/HybrisAdapter.java // @Component // @Scope("prototype") // public class HybrisAdapter { // private static final Logger LOG = Logger.getLogger(HybrisAdapter.class); // private static final String SYSTEM_UPDATE = "System update"; // private static final String HMC_RESET = "HMC Reset"; // @Autowired EventService eventService; // @Autowired CacheController cacheController; // // public void initFirefly() throws Exception { // doInitialize(true); // } // // public void updateSystem(PK migration) throws Exception { // doInitialize(true); // eventService.publishEvent(new SystemUpdatedEvent(getTenantId(), migration)); // } // // private void doInitialize(boolean update) throws Exception { // FireflyJspWriter jspWriter = new FireflyJspWriter(); // try { // MockHttpServletRequest request = new MockHttpServletRequest(); // if (update) { // // up to version 5 // request.addParameter("initmethod", "update"); // request.addParameter("essential", "true"); // // version 6 // request.addParameter("initMethod", "UPDATE"); // request.addParameter("createEssentialData", "true"); // } // request.addParameter("init", "true"); // request.addParameter("default", "false"); // request.addParameter("ALL_EXTENSIONS", "true"); // // up to version 5 // request.addParameter("localizetypes", "true"); // request.addParameter("clearhmc", "true"); // // version 6 // request.addParameter("localizeTypes", "true"); // request.addParameter("clearHMC", "true"); // // JspContext jspContext = new JspContext(jspWriter, request, new MockHttpServletResponse()); // // try { // InitializationLockHandler handler = new InitializationLockHandler(new DefaultInitLockDao()); // String operationName = update ? SYSTEM_UPDATE : HMC_RESET; // // handler.performLocked(Registry.getCurrentTenant(), // createInitializeCallable(jspContext), // operationName); // } catch (NoSuchMethodException e) { // LOG.info(format("Internal reflection unsuccessful: system is not locked while performing '%s only' change.", HMC_RESET)); // Initialization.doInitialize(jspContext); // } // } finally { // LOG.debug(de.hybris.platform.util.Utilities.filterOutHTMLTags(jspWriter.getString())); // } // } // // private Callable<Boolean> createInitializeCallable(final JspContext jspContext) { // return new Callable<Boolean>() { // public Boolean call() throws Exception { // Method m = Initialization.class.getDeclaredMethod("doInitializeImpl", JspContext.class); // m.setAccessible(true); // m.invoke(null, jspContext); // return Boolean.TRUE; // } // }; // } // // public void clearHmcConfiguration(PK migration) throws Exception { // doInitialize(false); // eventService.publishEvent(new HmcResetEvent(getTenantId(), migration)); // } // // public String getTenantId() { // return Registry.getCurrentTenant().getTenantID(); // } // // public void clearJaloCache() { // Registry.getCurrentTenant().getCache().clear(); // } // // /** // * This event is triggered after a system update is done. // */ // public static class SystemUpdatedEvent extends TenantEvent { // private PK migration; // // SystemUpdatedEvent(String tenantId, PK migration) { // super(tenantId); // this.migration = migration; // } // // public PK getMigration() { // return migration; // } // } // // /** // * This event is triggered after a hMC reset is done. // */ // public static class HmcResetEvent extends TenantEvent { // private PK migration; // // HmcResetEvent(String tenantId, PK migration) { // super(tenantId); // this.migration = migration; // } // // public PK getMigration() { // return migration; // } // } // // } // // Path: src/de/neuland/firefly/migration/MigrationRepository.java // @Repository // @Scope("prototype") // public class MigrationRepository { // @Autowired private ModelService modelService; // // public FireflyMigrationModel findByPk(PK pk) { // return modelService.get(pk); // } // // public FireflyMigrationModel create() { // return modelService.create(FireflyMigrationModel.class); // } // // public void save(FireflyMigrationModel migration) { // modelService.save(migration); // } // } // Path: src/de/neuland/firefly/extensionfinder/FireflySystemFactory.java import de.hybris.bootstrap.config.ExtensionInfo; import de.hybris.platform.core.Registry; import de.hybris.platform.util.Utilities; import de.neuland.firefly.HybrisAdapter; import de.neuland.firefly.migration.MigrationRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import java.util.ArrayList; import java.util.List; package de.neuland.firefly.extensionfinder; @Component @Scope("prototype") public class FireflySystemFactory { @Autowired private FireflyExtensionRepository fireflyExtensionRepository; @Autowired private MigrationRepository migrationRepository;
@Autowired private HybrisAdapter hybrisAdapter;
neuland/firefly
testsrc/de/neuland/firefly/changes/v1/XMLChangeTest.java
// Path: testsrc/de/neuland/firefly/TestUtils.java // public class TestUtils { // public static void unwrapException(RuntimeException e) throws Throwable { // if (e.getCause() != null) { // throw e.getCause(); // } else { // throw e; // } // } // // public static <T> T loadXML(Class<T> type, String xmlFile) { // T result = XMLUtil.loadXML(type, getFileFromClasspath(xmlFile)); // assertNotNull(result); // return result; // } // // public static File getFileFromClasspath(String filename) { // URL currentClassPathFolder = TestUtils.class.getClassLoader().getResource(""); // File result = new File(currentClassPathFolder.getFile(), filename); // assertTrue(result.exists()); // return result; // } // }
import de.neuland.firefly.TestUtils; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue;
public void shoulduseDefaultOnPreconditionFail() throws Exception { // given String xmlFile = "resources/changes/v1/changeDescription-details.xml"; // XMLChange change = loadXML(xmlFile, 0); // then assertEquals(XMLPreconditionBehaviour.HALT, change.getOnPreconditionFail()); } @Test public void shouldParseChangeContent() throws Exception { // given String xmlFile = "resources/changes/v1/changeDescription-details.xml"; // when XMLChange change = loadXML(xmlFile, 1); // then assertEquals("print(ctx.getBeanDefinitionNames());", change.getChangeContent()); } @Test public void shouldOverwriteToString() throws Exception { // given String xmlFile = "resources/changes/v1/changeDescription-details.xml"; // when XMLChange change = loadXML(xmlFile, 0); // then assertTrue(change.toString().contains(FILE)); } private XMLChange loadXML(String xmlFile, int changeIndex) {
// Path: testsrc/de/neuland/firefly/TestUtils.java // public class TestUtils { // public static void unwrapException(RuntimeException e) throws Throwable { // if (e.getCause() != null) { // throw e.getCause(); // } else { // throw e; // } // } // // public static <T> T loadXML(Class<T> type, String xmlFile) { // T result = XMLUtil.loadXML(type, getFileFromClasspath(xmlFile)); // assertNotNull(result); // return result; // } // // public static File getFileFromClasspath(String filename) { // URL currentClassPathFolder = TestUtils.class.getClassLoader().getResource(""); // File result = new File(currentClassPathFolder.getFile(), filename); // assertTrue(result.exists()); // return result; // } // } // Path: testsrc/de/neuland/firefly/changes/v1/XMLChangeTest.java import de.neuland.firefly.TestUtils; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; public void shoulduseDefaultOnPreconditionFail() throws Exception { // given String xmlFile = "resources/changes/v1/changeDescription-details.xml"; // XMLChange change = loadXML(xmlFile, 0); // then assertEquals(XMLPreconditionBehaviour.HALT, change.getOnPreconditionFail()); } @Test public void shouldParseChangeContent() throws Exception { // given String xmlFile = "resources/changes/v1/changeDescription-details.xml"; // when XMLChange change = loadXML(xmlFile, 1); // then assertEquals("print(ctx.getBeanDefinitionNames());", change.getChangeContent()); } @Test public void shouldOverwriteToString() throws Exception { // given String xmlFile = "resources/changes/v1/changeDescription-details.xml"; // when XMLChange change = loadXML(xmlFile, 0); // then assertTrue(change.toString().contains(FILE)); } private XMLChange loadXML(String xmlFile, int changeIndex) {
XMLChangeDescription changeDescription = TestUtils.loadXML(XMLChangeDescription.class, xmlFile);
neuland/firefly
testsrc/de/neuland/firefly/extensionfinder/SystemUpdateEventListenerTest.java
// Path: src/de/neuland/firefly/HybrisAdapter.java // @Component // @Scope("prototype") // public class HybrisAdapter { // private static final Logger LOG = Logger.getLogger(HybrisAdapter.class); // private static final String SYSTEM_UPDATE = "System update"; // private static final String HMC_RESET = "HMC Reset"; // @Autowired EventService eventService; // @Autowired CacheController cacheController; // // public void initFirefly() throws Exception { // doInitialize(true); // } // // public void updateSystem(PK migration) throws Exception { // doInitialize(true); // eventService.publishEvent(new SystemUpdatedEvent(getTenantId(), migration)); // } // // private void doInitialize(boolean update) throws Exception { // FireflyJspWriter jspWriter = new FireflyJspWriter(); // try { // MockHttpServletRequest request = new MockHttpServletRequest(); // if (update) { // // up to version 5 // request.addParameter("initmethod", "update"); // request.addParameter("essential", "true"); // // version 6 // request.addParameter("initMethod", "UPDATE"); // request.addParameter("createEssentialData", "true"); // } // request.addParameter("init", "true"); // request.addParameter("default", "false"); // request.addParameter("ALL_EXTENSIONS", "true"); // // up to version 5 // request.addParameter("localizetypes", "true"); // request.addParameter("clearhmc", "true"); // // version 6 // request.addParameter("localizeTypes", "true"); // request.addParameter("clearHMC", "true"); // // JspContext jspContext = new JspContext(jspWriter, request, new MockHttpServletResponse()); // // try { // InitializationLockHandler handler = new InitializationLockHandler(new DefaultInitLockDao()); // String operationName = update ? SYSTEM_UPDATE : HMC_RESET; // // handler.performLocked(Registry.getCurrentTenant(), // createInitializeCallable(jspContext), // operationName); // } catch (NoSuchMethodException e) { // LOG.info(format("Internal reflection unsuccessful: system is not locked while performing '%s only' change.", HMC_RESET)); // Initialization.doInitialize(jspContext); // } // } finally { // LOG.debug(de.hybris.platform.util.Utilities.filterOutHTMLTags(jspWriter.getString())); // } // } // // private Callable<Boolean> createInitializeCallable(final JspContext jspContext) { // return new Callable<Boolean>() { // public Boolean call() throws Exception { // Method m = Initialization.class.getDeclaredMethod("doInitializeImpl", JspContext.class); // m.setAccessible(true); // m.invoke(null, jspContext); // return Boolean.TRUE; // } // }; // } // // public void clearHmcConfiguration(PK migration) throws Exception { // doInitialize(false); // eventService.publishEvent(new HmcResetEvent(getTenantId(), migration)); // } // // public String getTenantId() { // return Registry.getCurrentTenant().getTenantID(); // } // // public void clearJaloCache() { // Registry.getCurrentTenant().getCache().clear(); // } // // /** // * This event is triggered after a system update is done. // */ // public static class SystemUpdatedEvent extends TenantEvent { // private PK migration; // // SystemUpdatedEvent(String tenantId, PK migration) { // super(tenantId); // this.migration = migration; // } // // public PK getMigration() { // return migration; // } // } // // /** // * This event is triggered after a hMC reset is done. // */ // public static class HmcResetEvent extends TenantEvent { // private PK migration; // // HmcResetEvent(String tenantId, PK migration) { // super(tenantId); // this.migration = migration; // } // // public PK getMigration() { // return migration; // } // } // // }
import de.hybris.platform.core.PK; import de.hybris.platform.servicelayer.cluster.ClusterService; import de.hybris.platform.servicelayer.tenant.TenantService; import de.neuland.firefly.HybrisAdapter; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import static org.mockito.BDDMockito.given; import static org.mockito.Matchers.any; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify;
package de.neuland.firefly.extensionfinder; @RunWith(MockitoJUnitRunner.class) public class SystemUpdateEventListenerTest { private static final String TENANT_ID = "myTestTenant"; private static final PK MIGRATION = PK.NULL_PK; private SystemUpdateEventListener listener; @Mock private FireflyExtension extension;
// Path: src/de/neuland/firefly/HybrisAdapter.java // @Component // @Scope("prototype") // public class HybrisAdapter { // private static final Logger LOG = Logger.getLogger(HybrisAdapter.class); // private static final String SYSTEM_UPDATE = "System update"; // private static final String HMC_RESET = "HMC Reset"; // @Autowired EventService eventService; // @Autowired CacheController cacheController; // // public void initFirefly() throws Exception { // doInitialize(true); // } // // public void updateSystem(PK migration) throws Exception { // doInitialize(true); // eventService.publishEvent(new SystemUpdatedEvent(getTenantId(), migration)); // } // // private void doInitialize(boolean update) throws Exception { // FireflyJspWriter jspWriter = new FireflyJspWriter(); // try { // MockHttpServletRequest request = new MockHttpServletRequest(); // if (update) { // // up to version 5 // request.addParameter("initmethod", "update"); // request.addParameter("essential", "true"); // // version 6 // request.addParameter("initMethod", "UPDATE"); // request.addParameter("createEssentialData", "true"); // } // request.addParameter("init", "true"); // request.addParameter("default", "false"); // request.addParameter("ALL_EXTENSIONS", "true"); // // up to version 5 // request.addParameter("localizetypes", "true"); // request.addParameter("clearhmc", "true"); // // version 6 // request.addParameter("localizeTypes", "true"); // request.addParameter("clearHMC", "true"); // // JspContext jspContext = new JspContext(jspWriter, request, new MockHttpServletResponse()); // // try { // InitializationLockHandler handler = new InitializationLockHandler(new DefaultInitLockDao()); // String operationName = update ? SYSTEM_UPDATE : HMC_RESET; // // handler.performLocked(Registry.getCurrentTenant(), // createInitializeCallable(jspContext), // operationName); // } catch (NoSuchMethodException e) { // LOG.info(format("Internal reflection unsuccessful: system is not locked while performing '%s only' change.", HMC_RESET)); // Initialization.doInitialize(jspContext); // } // } finally { // LOG.debug(de.hybris.platform.util.Utilities.filterOutHTMLTags(jspWriter.getString())); // } // } // // private Callable<Boolean> createInitializeCallable(final JspContext jspContext) { // return new Callable<Boolean>() { // public Boolean call() throws Exception { // Method m = Initialization.class.getDeclaredMethod("doInitializeImpl", JspContext.class); // m.setAccessible(true); // m.invoke(null, jspContext); // return Boolean.TRUE; // } // }; // } // // public void clearHmcConfiguration(PK migration) throws Exception { // doInitialize(false); // eventService.publishEvent(new HmcResetEvent(getTenantId(), migration)); // } // // public String getTenantId() { // return Registry.getCurrentTenant().getTenantID(); // } // // public void clearJaloCache() { // Registry.getCurrentTenant().getCache().clear(); // } // // /** // * This event is triggered after a system update is done. // */ // public static class SystemUpdatedEvent extends TenantEvent { // private PK migration; // // SystemUpdatedEvent(String tenantId, PK migration) { // super(tenantId); // this.migration = migration; // } // // public PK getMigration() { // return migration; // } // } // // /** // * This event is triggered after a hMC reset is done. // */ // public static class HmcResetEvent extends TenantEvent { // private PK migration; // // HmcResetEvent(String tenantId, PK migration) { // super(tenantId); // this.migration = migration; // } // // public PK getMigration() { // return migration; // } // } // // } // Path: testsrc/de/neuland/firefly/extensionfinder/SystemUpdateEventListenerTest.java import de.hybris.platform.core.PK; import de.hybris.platform.servicelayer.cluster.ClusterService; import de.hybris.platform.servicelayer.tenant.TenantService; import de.neuland.firefly.HybrisAdapter; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import static org.mockito.BDDMockito.given; import static org.mockito.Matchers.any; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; package de.neuland.firefly.extensionfinder; @RunWith(MockitoJUnitRunner.class) public class SystemUpdateEventListenerTest { private static final String TENANT_ID = "myTestTenant"; private static final PK MIGRATION = PK.NULL_PK; private SystemUpdateEventListener listener; @Mock private FireflyExtension extension;
@Mock private HybrisAdapter.SystemUpdatedEvent systemUpdatedEvent;
neuland/firefly
src/de/neuland/firefly/changes/ChangeList.java
// Path: src/de/neuland/firefly/changes/Change.java // public static class ChangeModifiedException extends Exception { // public ChangeModifiedException(Change change) { // super("Change " + change.getFile() + ":" + change.getAuthor() + ":" + change.getId() + " has been modified since execution."); // } // } // // Path: src/de/neuland/firefly/extensionfinder/FireflyExtensionRepository.java // @Repository // @Scope("prototype") // public class FireflyExtensionRepository { // @Autowired ModelService modelService; // @Autowired FlexibleSearchService searchService; // // public FireflyExtensionModel findByName(String name) throws FireflyExtensionNotFoundException, FireflyNotInstalledException { // final FlexibleSearchQuery query = new FlexibleSearchQuery( // "SELECT {" + FireflyExtensionModel.PK + "} " + // "FROM {" + FireflyExtensionModel._TYPECODE + "} " + // "WHERE {" + FireflyExtensionModel.NAME + "} = ?name"); // query.addQueryParameter("name", name); // try { // return searchService.searchUnique(query); // } catch (FlexibleSearchException e) { // throw new FireflyNotInstalledException(e); // } catch (ModelNotFoundException e) { // throw new FireflyExtensionNotFoundException(name); // } // } // // public FireflyExtensionModel create(String name) { // Assert.hasText(name); // FireflyExtensionModel result = new FireflyExtensionModel(); // result.setName(name); // result.setStates(new ArrayList<FireflyExtensionStateModel>()); // return result; // } // // public void save(FireflyExtensionModel model) { // modelService.save(model); // } // // public static class FireflyNotInstalledException extends RuntimeException { // public FireflyNotInstalledException(Exception e) { // super(e); // } // } // // public static class FireflyExtensionNotFoundException extends Exception { // private String name; // // public FireflyExtensionNotFoundException(String name) { // super("No " + FireflyExtensionModel._TYPECODE + " found for name=" + name); // this.name = name; // } // // public String getName() { // return name; // } // } // }
import de.neuland.firefly.changes.Change.ChangeModifiedException; import de.neuland.firefly.extensionfinder.FireflyExtensionRepository; import de.neuland.firefly.model.FireflyMigrationModel; import java.util.ArrayList; import java.util.List; import static java.util.Collections.unmodifiableList;
package de.neuland.firefly.changes; public class ChangeList { private List<Change> changes = new ArrayList<>(); void addChange(Change change) { if (change != null && !contains(change.getFile(), change.getAuthor(), change.getId())) { changes.add(change); } } void addChanges(List<Change> changes) { if (changes != null) { for (Change change : changes) { addChange(change); } } } List<Change> getChanges() { return unmodifiableList(changes); } boolean contains(String file, String author, String id) { for (Change change : changes) { if (file.equals(change.getFile()) && author.equals(change.getAuthor()) && id.equals(change.getId())) { return true; } } return false; }
// Path: src/de/neuland/firefly/changes/Change.java // public static class ChangeModifiedException extends Exception { // public ChangeModifiedException(Change change) { // super("Change " + change.getFile() + ":" + change.getAuthor() + ":" + change.getId() + " has been modified since execution."); // } // } // // Path: src/de/neuland/firefly/extensionfinder/FireflyExtensionRepository.java // @Repository // @Scope("prototype") // public class FireflyExtensionRepository { // @Autowired ModelService modelService; // @Autowired FlexibleSearchService searchService; // // public FireflyExtensionModel findByName(String name) throws FireflyExtensionNotFoundException, FireflyNotInstalledException { // final FlexibleSearchQuery query = new FlexibleSearchQuery( // "SELECT {" + FireflyExtensionModel.PK + "} " + // "FROM {" + FireflyExtensionModel._TYPECODE + "} " + // "WHERE {" + FireflyExtensionModel.NAME + "} = ?name"); // query.addQueryParameter("name", name); // try { // return searchService.searchUnique(query); // } catch (FlexibleSearchException e) { // throw new FireflyNotInstalledException(e); // } catch (ModelNotFoundException e) { // throw new FireflyExtensionNotFoundException(name); // } // } // // public FireflyExtensionModel create(String name) { // Assert.hasText(name); // FireflyExtensionModel result = new FireflyExtensionModel(); // result.setName(name); // result.setStates(new ArrayList<FireflyExtensionStateModel>()); // return result; // } // // public void save(FireflyExtensionModel model) { // modelService.save(model); // } // // public static class FireflyNotInstalledException extends RuntimeException { // public FireflyNotInstalledException(Exception e) { // super(e); // } // } // // public static class FireflyExtensionNotFoundException extends Exception { // private String name; // // public FireflyExtensionNotFoundException(String name) { // super("No " + FireflyExtensionModel._TYPECODE + " found for name=" + name); // this.name = name; // } // // public String getName() { // return name; // } // } // } // Path: src/de/neuland/firefly/changes/ChangeList.java import de.neuland.firefly.changes.Change.ChangeModifiedException; import de.neuland.firefly.extensionfinder.FireflyExtensionRepository; import de.neuland.firefly.model.FireflyMigrationModel; import java.util.ArrayList; import java.util.List; import static java.util.Collections.unmodifiableList; package de.neuland.firefly.changes; public class ChangeList { private List<Change> changes = new ArrayList<>(); void addChange(Change change) { if (change != null && !contains(change.getFile(), change.getAuthor(), change.getId())) { changes.add(change); } } void addChanges(List<Change> changes) { if (changes != null) { for (Change change : changes) { addChange(change); } } } List<Change> getChanges() { return unmodifiableList(changes); } boolean contains(String file, String author, String id) { for (Change change : changes) { if (file.equals(change.getFile()) && author.equals(change.getAuthor()) && id.equals(change.getId())) { return true; } } return false; }
public List<Change> getChangesThatRequiredExecution() throws ChangeModifiedException {
neuland/firefly
src/de/neuland/firefly/changes/ChangeList.java
// Path: src/de/neuland/firefly/changes/Change.java // public static class ChangeModifiedException extends Exception { // public ChangeModifiedException(Change change) { // super("Change " + change.getFile() + ":" + change.getAuthor() + ":" + change.getId() + " has been modified since execution."); // } // } // // Path: src/de/neuland/firefly/extensionfinder/FireflyExtensionRepository.java // @Repository // @Scope("prototype") // public class FireflyExtensionRepository { // @Autowired ModelService modelService; // @Autowired FlexibleSearchService searchService; // // public FireflyExtensionModel findByName(String name) throws FireflyExtensionNotFoundException, FireflyNotInstalledException { // final FlexibleSearchQuery query = new FlexibleSearchQuery( // "SELECT {" + FireflyExtensionModel.PK + "} " + // "FROM {" + FireflyExtensionModel._TYPECODE + "} " + // "WHERE {" + FireflyExtensionModel.NAME + "} = ?name"); // query.addQueryParameter("name", name); // try { // return searchService.searchUnique(query); // } catch (FlexibleSearchException e) { // throw new FireflyNotInstalledException(e); // } catch (ModelNotFoundException e) { // throw new FireflyExtensionNotFoundException(name); // } // } // // public FireflyExtensionModel create(String name) { // Assert.hasText(name); // FireflyExtensionModel result = new FireflyExtensionModel(); // result.setName(name); // result.setStates(new ArrayList<FireflyExtensionStateModel>()); // return result; // } // // public void save(FireflyExtensionModel model) { // modelService.save(model); // } // // public static class FireflyNotInstalledException extends RuntimeException { // public FireflyNotInstalledException(Exception e) { // super(e); // } // } // // public static class FireflyExtensionNotFoundException extends Exception { // private String name; // // public FireflyExtensionNotFoundException(String name) { // super("No " + FireflyExtensionModel._TYPECODE + " found for name=" + name); // this.name = name; // } // // public String getName() { // return name; // } // } // }
import de.neuland.firefly.changes.Change.ChangeModifiedException; import de.neuland.firefly.extensionfinder.FireflyExtensionRepository; import de.neuland.firefly.model.FireflyMigrationModel; import java.util.ArrayList; import java.util.List; import static java.util.Collections.unmodifiableList;
return unmodifiableList(changes); } boolean contains(String file, String author, String id) { for (Change change : changes) { if (file.equals(change.getFile()) && author.equals(change.getAuthor()) && id.equals(change.getId())) { return true; } } return false; } public List<Change> getChangesThatRequiredExecution() throws ChangeModifiedException { List<Change> result = new ArrayList<>(); for (Change change : getChanges()) { if (change.executionRequired()) { result.add(change); } } return result; } public void executeChanges(FireflyMigrationModel migration) throws ChangeExecutionException, ChangeModifiedException, PreconditionFailedException { for (Change change : getChangesThatRequiredExecution()) { change.execute(migration); } }
// Path: src/de/neuland/firefly/changes/Change.java // public static class ChangeModifiedException extends Exception { // public ChangeModifiedException(Change change) { // super("Change " + change.getFile() + ":" + change.getAuthor() + ":" + change.getId() + " has been modified since execution."); // } // } // // Path: src/de/neuland/firefly/extensionfinder/FireflyExtensionRepository.java // @Repository // @Scope("prototype") // public class FireflyExtensionRepository { // @Autowired ModelService modelService; // @Autowired FlexibleSearchService searchService; // // public FireflyExtensionModel findByName(String name) throws FireflyExtensionNotFoundException, FireflyNotInstalledException { // final FlexibleSearchQuery query = new FlexibleSearchQuery( // "SELECT {" + FireflyExtensionModel.PK + "} " + // "FROM {" + FireflyExtensionModel._TYPECODE + "} " + // "WHERE {" + FireflyExtensionModel.NAME + "} = ?name"); // query.addQueryParameter("name", name); // try { // return searchService.searchUnique(query); // } catch (FlexibleSearchException e) { // throw new FireflyNotInstalledException(e); // } catch (ModelNotFoundException e) { // throw new FireflyExtensionNotFoundException(name); // } // } // // public FireflyExtensionModel create(String name) { // Assert.hasText(name); // FireflyExtensionModel result = new FireflyExtensionModel(); // result.setName(name); // result.setStates(new ArrayList<FireflyExtensionStateModel>()); // return result; // } // // public void save(FireflyExtensionModel model) { // modelService.save(model); // } // // public static class FireflyNotInstalledException extends RuntimeException { // public FireflyNotInstalledException(Exception e) { // super(e); // } // } // // public static class FireflyExtensionNotFoundException extends Exception { // private String name; // // public FireflyExtensionNotFoundException(String name) { // super("No " + FireflyExtensionModel._TYPECODE + " found for name=" + name); // this.name = name; // } // // public String getName() { // return name; // } // } // } // Path: src/de/neuland/firefly/changes/ChangeList.java import de.neuland.firefly.changes.Change.ChangeModifiedException; import de.neuland.firefly.extensionfinder.FireflyExtensionRepository; import de.neuland.firefly.model.FireflyMigrationModel; import java.util.ArrayList; import java.util.List; import static java.util.Collections.unmodifiableList; return unmodifiableList(changes); } boolean contains(String file, String author, String id) { for (Change change : changes) { if (file.equals(change.getFile()) && author.equals(change.getAuthor()) && id.equals(change.getId())) { return true; } } return false; } public List<Change> getChangesThatRequiredExecution() throws ChangeModifiedException { List<Change> result = new ArrayList<>(); for (Change change : getChanges()) { if (change.executionRequired()) { result.add(change); } } return result; } public void executeChanges(FireflyMigrationModel migration) throws ChangeExecutionException, ChangeModifiedException, PreconditionFailedException { for (Change change : getChangesThatRequiredExecution()) { change.execute(migration); } }
public void markChangesAsExecuted(FireflyMigrationModel migration) throws ChangeModifiedException, FireflyExtensionRepository.FireflyExtensionNotFoundException {
neuland/firefly
testsrc/de/neuland/firefly/extensionfinder/FireflySystemTest.java
// Path: src/de/neuland/firefly/HybrisAdapter.java // @Component // @Scope("prototype") // public class HybrisAdapter { // private static final Logger LOG = Logger.getLogger(HybrisAdapter.class); // private static final String SYSTEM_UPDATE = "System update"; // private static final String HMC_RESET = "HMC Reset"; // @Autowired EventService eventService; // @Autowired CacheController cacheController; // // public void initFirefly() throws Exception { // doInitialize(true); // } // // public void updateSystem(PK migration) throws Exception { // doInitialize(true); // eventService.publishEvent(new SystemUpdatedEvent(getTenantId(), migration)); // } // // private void doInitialize(boolean update) throws Exception { // FireflyJspWriter jspWriter = new FireflyJspWriter(); // try { // MockHttpServletRequest request = new MockHttpServletRequest(); // if (update) { // // up to version 5 // request.addParameter("initmethod", "update"); // request.addParameter("essential", "true"); // // version 6 // request.addParameter("initMethod", "UPDATE"); // request.addParameter("createEssentialData", "true"); // } // request.addParameter("init", "true"); // request.addParameter("default", "false"); // request.addParameter("ALL_EXTENSIONS", "true"); // // up to version 5 // request.addParameter("localizetypes", "true"); // request.addParameter("clearhmc", "true"); // // version 6 // request.addParameter("localizeTypes", "true"); // request.addParameter("clearHMC", "true"); // // JspContext jspContext = new JspContext(jspWriter, request, new MockHttpServletResponse()); // // try { // InitializationLockHandler handler = new InitializationLockHandler(new DefaultInitLockDao()); // String operationName = update ? SYSTEM_UPDATE : HMC_RESET; // // handler.performLocked(Registry.getCurrentTenant(), // createInitializeCallable(jspContext), // operationName); // } catch (NoSuchMethodException e) { // LOG.info(format("Internal reflection unsuccessful: system is not locked while performing '%s only' change.", HMC_RESET)); // Initialization.doInitialize(jspContext); // } // } finally { // LOG.debug(de.hybris.platform.util.Utilities.filterOutHTMLTags(jspWriter.getString())); // } // } // // private Callable<Boolean> createInitializeCallable(final JspContext jspContext) { // return new Callable<Boolean>() { // public Boolean call() throws Exception { // Method m = Initialization.class.getDeclaredMethod("doInitializeImpl", JspContext.class); // m.setAccessible(true); // m.invoke(null, jspContext); // return Boolean.TRUE; // } // }; // } // // public void clearHmcConfiguration(PK migration) throws Exception { // doInitialize(false); // eventService.publishEvent(new HmcResetEvent(getTenantId(), migration)); // } // // public String getTenantId() { // return Registry.getCurrentTenant().getTenantID(); // } // // public void clearJaloCache() { // Registry.getCurrentTenant().getCache().clear(); // } // // /** // * This event is triggered after a system update is done. // */ // public static class SystemUpdatedEvent extends TenantEvent { // private PK migration; // // SystemUpdatedEvent(String tenantId, PK migration) { // super(tenantId); // this.migration = migration; // } // // public PK getMigration() { // return migration; // } // } // // /** // * This event is triggered after a hMC reset is done. // */ // public static class HmcResetEvent extends TenantEvent { // private PK migration; // // HmcResetEvent(String tenantId, PK migration) { // super(tenantId); // this.migration = migration; // } // // public PK getMigration() { // return migration; // } // } // // }
import de.hybris.platform.core.PK; import de.neuland.firefly.HybrisAdapter; import de.neuland.firefly.model.FireflyMigrationModel; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.invocation.InvocationOnMock; import org.mockito.runners.MockitoJUnitRunner; import org.mockito.stubbing.Answer; import java.io.File; import java.util.Arrays; import java.util.Map; import static org.junit.Assert.*; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.*;
package de.neuland.firefly.extensionfinder; @RunWith(MockitoJUnitRunner.class) public class FireflySystemTest { public static final PK MIGRATION_PK = PK.fromLong(4711); @Mock private FireflyExtension extensionAlice; @Mock private FireflyExtension extensionBob; @Mock private FireflyMigrationModel migration;
// Path: src/de/neuland/firefly/HybrisAdapter.java // @Component // @Scope("prototype") // public class HybrisAdapter { // private static final Logger LOG = Logger.getLogger(HybrisAdapter.class); // private static final String SYSTEM_UPDATE = "System update"; // private static final String HMC_RESET = "HMC Reset"; // @Autowired EventService eventService; // @Autowired CacheController cacheController; // // public void initFirefly() throws Exception { // doInitialize(true); // } // // public void updateSystem(PK migration) throws Exception { // doInitialize(true); // eventService.publishEvent(new SystemUpdatedEvent(getTenantId(), migration)); // } // // private void doInitialize(boolean update) throws Exception { // FireflyJspWriter jspWriter = new FireflyJspWriter(); // try { // MockHttpServletRequest request = new MockHttpServletRequest(); // if (update) { // // up to version 5 // request.addParameter("initmethod", "update"); // request.addParameter("essential", "true"); // // version 6 // request.addParameter("initMethod", "UPDATE"); // request.addParameter("createEssentialData", "true"); // } // request.addParameter("init", "true"); // request.addParameter("default", "false"); // request.addParameter("ALL_EXTENSIONS", "true"); // // up to version 5 // request.addParameter("localizetypes", "true"); // request.addParameter("clearhmc", "true"); // // version 6 // request.addParameter("localizeTypes", "true"); // request.addParameter("clearHMC", "true"); // // JspContext jspContext = new JspContext(jspWriter, request, new MockHttpServletResponse()); // // try { // InitializationLockHandler handler = new InitializationLockHandler(new DefaultInitLockDao()); // String operationName = update ? SYSTEM_UPDATE : HMC_RESET; // // handler.performLocked(Registry.getCurrentTenant(), // createInitializeCallable(jspContext), // operationName); // } catch (NoSuchMethodException e) { // LOG.info(format("Internal reflection unsuccessful: system is not locked while performing '%s only' change.", HMC_RESET)); // Initialization.doInitialize(jspContext); // } // } finally { // LOG.debug(de.hybris.platform.util.Utilities.filterOutHTMLTags(jspWriter.getString())); // } // } // // private Callable<Boolean> createInitializeCallable(final JspContext jspContext) { // return new Callable<Boolean>() { // public Boolean call() throws Exception { // Method m = Initialization.class.getDeclaredMethod("doInitializeImpl", JspContext.class); // m.setAccessible(true); // m.invoke(null, jspContext); // return Boolean.TRUE; // } // }; // } // // public void clearHmcConfiguration(PK migration) throws Exception { // doInitialize(false); // eventService.publishEvent(new HmcResetEvent(getTenantId(), migration)); // } // // public String getTenantId() { // return Registry.getCurrentTenant().getTenantID(); // } // // public void clearJaloCache() { // Registry.getCurrentTenant().getCache().clear(); // } // // /** // * This event is triggered after a system update is done. // */ // public static class SystemUpdatedEvent extends TenantEvent { // private PK migration; // // SystemUpdatedEvent(String tenantId, PK migration) { // super(tenantId); // this.migration = migration; // } // // public PK getMigration() { // return migration; // } // } // // /** // * This event is triggered after a hMC reset is done. // */ // public static class HmcResetEvent extends TenantEvent { // private PK migration; // // HmcResetEvent(String tenantId, PK migration) { // super(tenantId); // this.migration = migration; // } // // public PK getMigration() { // return migration; // } // } // // } // Path: testsrc/de/neuland/firefly/extensionfinder/FireflySystemTest.java import de.hybris.platform.core.PK; import de.neuland.firefly.HybrisAdapter; import de.neuland.firefly.model.FireflyMigrationModel; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.invocation.InvocationOnMock; import org.mockito.runners.MockitoJUnitRunner; import org.mockito.stubbing.Answer; import java.io.File; import java.util.Arrays; import java.util.Map; import static org.junit.Assert.*; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.*; package de.neuland.firefly.extensionfinder; @RunWith(MockitoJUnitRunner.class) public class FireflySystemTest { public static final PK MIGRATION_PK = PK.fromLong(4711); @Mock private FireflyExtension extensionAlice; @Mock private FireflyExtension extensionBob; @Mock private FireflyMigrationModel migration;
@Mock private HybrisAdapter hybrisAdapter;
neuland/firefly
testsrc/de/neuland/firefly/utils/MD5UtilTest.java
// Path: testsrc/de/neuland/firefly/TestUtils.java // public static void unwrapException(RuntimeException e) throws Throwable { // if (e.getCause() != null) { // throw e.getCause(); // } else { // throw e; // } // }
import org.junit.Test; import java.io.UnsupportedEncodingException; import java.security.NoSuchAlgorithmException; import static de.neuland.firefly.TestUtils.unwrapException; import static org.junit.Assert.assertEquals;
package de.neuland.firefly.utils; public class MD5UtilTest { @Test public void shouldGenerateForString() throws Exception { // when String hash = MD5Util.generateMD5("<items><itemtypes/></items>"); // then assertEquals("5b4422df25563a6e8cd98a6a1327aaa4", hash); } @Test(expected = UnsupportedEncodingException.class) public void shouldHandleUnsupportedEncodingException() throws Throwable { try { // when MD5Util.generateMD5("someValue", "myEncoding", "MD5"); } catch (RuntimeException e) { // then
// Path: testsrc/de/neuland/firefly/TestUtils.java // public static void unwrapException(RuntimeException e) throws Throwable { // if (e.getCause() != null) { // throw e.getCause(); // } else { // throw e; // } // } // Path: testsrc/de/neuland/firefly/utils/MD5UtilTest.java import org.junit.Test; import java.io.UnsupportedEncodingException; import java.security.NoSuchAlgorithmException; import static de.neuland.firefly.TestUtils.unwrapException; import static org.junit.Assert.assertEquals; package de.neuland.firefly.utils; public class MD5UtilTest { @Test public void shouldGenerateForString() throws Exception { // when String hash = MD5Util.generateMD5("<items><itemtypes/></items>"); // then assertEquals("5b4422df25563a6e8cd98a6a1327aaa4", hash); } @Test(expected = UnsupportedEncodingException.class) public void shouldHandleUnsupportedEncodingException() throws Throwable { try { // when MD5Util.generateMD5("someValue", "myEncoding", "MD5"); } catch (RuntimeException e) { // then
unwrapException(e);
neuland/firefly
src/de/neuland/firefly/jalo/FireflyManager.java
// Path: src/de/neuland/firefly/constants/FireflyConstants.java // public final class FireflyConstants extends GeneratedFireflyConstants { // public static final String NO_ITEMS_XML_MD5 = "NO_ITEMS_XML"; // public static final String NO_HMC_XML_MD5 = "NO_HMC_XML"; // }
import de.hybris.platform.jalo.JaloSession; import de.hybris.platform.jalo.extension.ExtensionManager; import de.neuland.firefly.constants.FireflyConstants;
package de.neuland.firefly.jalo; public class FireflyManager extends GeneratedFireflyManager { public static FireflyManager getInstance() { ExtensionManager em = JaloSession.getCurrentSession().getExtensionManager();
// Path: src/de/neuland/firefly/constants/FireflyConstants.java // public final class FireflyConstants extends GeneratedFireflyConstants { // public static final String NO_ITEMS_XML_MD5 = "NO_ITEMS_XML"; // public static final String NO_HMC_XML_MD5 = "NO_HMC_XML"; // } // Path: src/de/neuland/firefly/jalo/FireflyManager.java import de.hybris.platform.jalo.JaloSession; import de.hybris.platform.jalo.extension.ExtensionManager; import de.neuland.firefly.constants.FireflyConstants; package de.neuland.firefly.jalo; public class FireflyManager extends GeneratedFireflyManager { public static FireflyManager getInstance() { ExtensionManager em = JaloSession.getCurrentSession().getExtensionManager();
return (FireflyManager) em.getExtension(FireflyConstants.EXTENSIONNAME);
neuland/firefly
src/de/neuland/firefly/extensionfinder/FireflyExtension.java
// Path: src/de/neuland/firefly/migration/MigrationRepository.java // @Repository // @Scope("prototype") // public class MigrationRepository { // @Autowired private ModelService modelService; // // public FireflyMigrationModel findByPk(PK pk) { // return modelService.get(pk); // } // // public FireflyMigrationModel create() { // return modelService.create(FireflyMigrationModel.class); // } // // public void save(FireflyMigrationModel migration) { // modelService.save(migration); // } // } // // Path: src/de/neuland/firefly/constants/FireflyConstants.java // public static final String NO_HMC_XML_MD5 = "NO_HMC_XML"; // // Path: src/de/neuland/firefly/constants/FireflyConstants.java // public static final String NO_ITEMS_XML_MD5 = "NO_ITEMS_XML"; // // Path: src/de/neuland/firefly/utils/MD5Util.java // public static String generateMD5(String baseValue) { // return generateMD5(baseValue, "UTF-8", "MD5"); // } // // Path: src/de/neuland/firefly/utils/XMLUtil.java // public static String loadAndNormalizeXML(File xmlFile) throws ParserConfigurationException, SAXException, IOException, TransformerException { // DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); // DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); // Document doc = dBuilder.parse(xmlFile); // // removeRecursively(doc); // doc.normalizeDocument(); // // TransformerFactory tf = TransformerFactory.newInstance(); // Transformer transformer = tf.newTransformer(); // transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); // transformer.setOutputProperty(OutputKeys.INDENT, "no"); // StringWriter normalizedXml = new StringWriter(); // transformer.transform(new DOMSource(doc), new StreamResult(normalizedXml)); // return normalizedXml.toString(); // }
import de.hybris.platform.core.PK; import de.neuland.firefly.migration.MigrationRepository; import de.neuland.firefly.model.FireflyExtensionModel; import de.neuland.firefly.model.FireflyExtensionStateModel; import de.neuland.firefly.model.FireflyMigrationModel; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.builder.ToStringBuilder; import org.xml.sax.SAXException; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerException; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import static de.neuland.firefly.constants.FireflyConstants.NO_HMC_XML_MD5; import static de.neuland.firefly.constants.FireflyConstants.NO_ITEMS_XML_MD5; import static de.neuland.firefly.utils.MD5Util.generateMD5; import static de.neuland.firefly.utils.XMLUtil.loadAndNormalizeXML; import static java.util.Arrays.asList;
package de.neuland.firefly.extensionfinder; /** * Representation of a single hybris extension. */ public class FireflyExtension { private FireflyExtensionRepository fireflyExtensionRepository;
// Path: src/de/neuland/firefly/migration/MigrationRepository.java // @Repository // @Scope("prototype") // public class MigrationRepository { // @Autowired private ModelService modelService; // // public FireflyMigrationModel findByPk(PK pk) { // return modelService.get(pk); // } // // public FireflyMigrationModel create() { // return modelService.create(FireflyMigrationModel.class); // } // // public void save(FireflyMigrationModel migration) { // modelService.save(migration); // } // } // // Path: src/de/neuland/firefly/constants/FireflyConstants.java // public static final String NO_HMC_XML_MD5 = "NO_HMC_XML"; // // Path: src/de/neuland/firefly/constants/FireflyConstants.java // public static final String NO_ITEMS_XML_MD5 = "NO_ITEMS_XML"; // // Path: src/de/neuland/firefly/utils/MD5Util.java // public static String generateMD5(String baseValue) { // return generateMD5(baseValue, "UTF-8", "MD5"); // } // // Path: src/de/neuland/firefly/utils/XMLUtil.java // public static String loadAndNormalizeXML(File xmlFile) throws ParserConfigurationException, SAXException, IOException, TransformerException { // DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); // DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); // Document doc = dBuilder.parse(xmlFile); // // removeRecursively(doc); // doc.normalizeDocument(); // // TransformerFactory tf = TransformerFactory.newInstance(); // Transformer transformer = tf.newTransformer(); // transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); // transformer.setOutputProperty(OutputKeys.INDENT, "no"); // StringWriter normalizedXml = new StringWriter(); // transformer.transform(new DOMSource(doc), new StreamResult(normalizedXml)); // return normalizedXml.toString(); // } // Path: src/de/neuland/firefly/extensionfinder/FireflyExtension.java import de.hybris.platform.core.PK; import de.neuland.firefly.migration.MigrationRepository; import de.neuland.firefly.model.FireflyExtensionModel; import de.neuland.firefly.model.FireflyExtensionStateModel; import de.neuland.firefly.model.FireflyMigrationModel; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.builder.ToStringBuilder; import org.xml.sax.SAXException; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerException; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import static de.neuland.firefly.constants.FireflyConstants.NO_HMC_XML_MD5; import static de.neuland.firefly.constants.FireflyConstants.NO_ITEMS_XML_MD5; import static de.neuland.firefly.utils.MD5Util.generateMD5; import static de.neuland.firefly.utils.XMLUtil.loadAndNormalizeXML; import static java.util.Arrays.asList; package de.neuland.firefly.extensionfinder; /** * Representation of a single hybris extension. */ public class FireflyExtension { private FireflyExtensionRepository fireflyExtensionRepository;
private MigrationRepository migrationRepository;
neuland/firefly
src/de/neuland/firefly/extensionfinder/FireflyExtension.java
// Path: src/de/neuland/firefly/migration/MigrationRepository.java // @Repository // @Scope("prototype") // public class MigrationRepository { // @Autowired private ModelService modelService; // // public FireflyMigrationModel findByPk(PK pk) { // return modelService.get(pk); // } // // public FireflyMigrationModel create() { // return modelService.create(FireflyMigrationModel.class); // } // // public void save(FireflyMigrationModel migration) { // modelService.save(migration); // } // } // // Path: src/de/neuland/firefly/constants/FireflyConstants.java // public static final String NO_HMC_XML_MD5 = "NO_HMC_XML"; // // Path: src/de/neuland/firefly/constants/FireflyConstants.java // public static final String NO_ITEMS_XML_MD5 = "NO_ITEMS_XML"; // // Path: src/de/neuland/firefly/utils/MD5Util.java // public static String generateMD5(String baseValue) { // return generateMD5(baseValue, "UTF-8", "MD5"); // } // // Path: src/de/neuland/firefly/utils/XMLUtil.java // public static String loadAndNormalizeXML(File xmlFile) throws ParserConfigurationException, SAXException, IOException, TransformerException { // DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); // DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); // Document doc = dBuilder.parse(xmlFile); // // removeRecursively(doc); // doc.normalizeDocument(); // // TransformerFactory tf = TransformerFactory.newInstance(); // Transformer transformer = tf.newTransformer(); // transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); // transformer.setOutputProperty(OutputKeys.INDENT, "no"); // StringWriter normalizedXml = new StringWriter(); // transformer.transform(new DOMSource(doc), new StreamResult(normalizedXml)); // return normalizedXml.toString(); // }
import de.hybris.platform.core.PK; import de.neuland.firefly.migration.MigrationRepository; import de.neuland.firefly.model.FireflyExtensionModel; import de.neuland.firefly.model.FireflyExtensionStateModel; import de.neuland.firefly.model.FireflyMigrationModel; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.builder.ToStringBuilder; import org.xml.sax.SAXException; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerException; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import static de.neuland.firefly.constants.FireflyConstants.NO_HMC_XML_MD5; import static de.neuland.firefly.constants.FireflyConstants.NO_ITEMS_XML_MD5; import static de.neuland.firefly.utils.MD5Util.generateMD5; import static de.neuland.firefly.utils.XMLUtil.loadAndNormalizeXML; import static java.util.Arrays.asList;
createState(fireflyExtensionModel, migrationModel, lastState != null ? lastState.getItemsDefinitionHash() : getItemsDefinitionHash(), getHmcDefinitionHash()); } fireflyExtensionRepository.save(fireflyExtensionModel); } public void onUpdate(PK migration) { FireflyMigrationModel migrationModel = migrationRepository.findByPk(migration); FireflyExtensionModel fireflyExtensionModel = getOrCreateFireflyExtensionModel(); String itemsDefinitionHash = getItemsDefinitionHash(); String hmcDefinitionHash = getHmcDefinitionHash(); if (!equalsHash(getLastState(fireflyExtensionModel), itemsDefinitionHash, hmcDefinitionHash)) { createState(fireflyExtensionModel, migrationModel, itemsDefinitionHash, hmcDefinitionHash); } fireflyExtensionRepository.save(fireflyExtensionModel); } String getName() { return name; } File getRootPath() { return rootPath; } String getItemsDefinitionHash() {
// Path: src/de/neuland/firefly/migration/MigrationRepository.java // @Repository // @Scope("prototype") // public class MigrationRepository { // @Autowired private ModelService modelService; // // public FireflyMigrationModel findByPk(PK pk) { // return modelService.get(pk); // } // // public FireflyMigrationModel create() { // return modelService.create(FireflyMigrationModel.class); // } // // public void save(FireflyMigrationModel migration) { // modelService.save(migration); // } // } // // Path: src/de/neuland/firefly/constants/FireflyConstants.java // public static final String NO_HMC_XML_MD5 = "NO_HMC_XML"; // // Path: src/de/neuland/firefly/constants/FireflyConstants.java // public static final String NO_ITEMS_XML_MD5 = "NO_ITEMS_XML"; // // Path: src/de/neuland/firefly/utils/MD5Util.java // public static String generateMD5(String baseValue) { // return generateMD5(baseValue, "UTF-8", "MD5"); // } // // Path: src/de/neuland/firefly/utils/XMLUtil.java // public static String loadAndNormalizeXML(File xmlFile) throws ParserConfigurationException, SAXException, IOException, TransformerException { // DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); // DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); // Document doc = dBuilder.parse(xmlFile); // // removeRecursively(doc); // doc.normalizeDocument(); // // TransformerFactory tf = TransformerFactory.newInstance(); // Transformer transformer = tf.newTransformer(); // transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); // transformer.setOutputProperty(OutputKeys.INDENT, "no"); // StringWriter normalizedXml = new StringWriter(); // transformer.transform(new DOMSource(doc), new StreamResult(normalizedXml)); // return normalizedXml.toString(); // } // Path: src/de/neuland/firefly/extensionfinder/FireflyExtension.java import de.hybris.platform.core.PK; import de.neuland.firefly.migration.MigrationRepository; import de.neuland.firefly.model.FireflyExtensionModel; import de.neuland.firefly.model.FireflyExtensionStateModel; import de.neuland.firefly.model.FireflyMigrationModel; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.builder.ToStringBuilder; import org.xml.sax.SAXException; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerException; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import static de.neuland.firefly.constants.FireflyConstants.NO_HMC_XML_MD5; import static de.neuland.firefly.constants.FireflyConstants.NO_ITEMS_XML_MD5; import static de.neuland.firefly.utils.MD5Util.generateMD5; import static de.neuland.firefly.utils.XMLUtil.loadAndNormalizeXML; import static java.util.Arrays.asList; createState(fireflyExtensionModel, migrationModel, lastState != null ? lastState.getItemsDefinitionHash() : getItemsDefinitionHash(), getHmcDefinitionHash()); } fireflyExtensionRepository.save(fireflyExtensionModel); } public void onUpdate(PK migration) { FireflyMigrationModel migrationModel = migrationRepository.findByPk(migration); FireflyExtensionModel fireflyExtensionModel = getOrCreateFireflyExtensionModel(); String itemsDefinitionHash = getItemsDefinitionHash(); String hmcDefinitionHash = getHmcDefinitionHash(); if (!equalsHash(getLastState(fireflyExtensionModel), itemsDefinitionHash, hmcDefinitionHash)) { createState(fireflyExtensionModel, migrationModel, itemsDefinitionHash, hmcDefinitionHash); } fireflyExtensionRepository.save(fireflyExtensionModel); } String getName() { return name; } File getRootPath() { return rootPath; } String getItemsDefinitionHash() {
return getHashFromFile(new File(rootPath, "resources/" + name + "-items.xml"), NO_ITEMS_XML_MD5);
neuland/firefly
src/de/neuland/firefly/extensionfinder/FireflyExtension.java
// Path: src/de/neuland/firefly/migration/MigrationRepository.java // @Repository // @Scope("prototype") // public class MigrationRepository { // @Autowired private ModelService modelService; // // public FireflyMigrationModel findByPk(PK pk) { // return modelService.get(pk); // } // // public FireflyMigrationModel create() { // return modelService.create(FireflyMigrationModel.class); // } // // public void save(FireflyMigrationModel migration) { // modelService.save(migration); // } // } // // Path: src/de/neuland/firefly/constants/FireflyConstants.java // public static final String NO_HMC_XML_MD5 = "NO_HMC_XML"; // // Path: src/de/neuland/firefly/constants/FireflyConstants.java // public static final String NO_ITEMS_XML_MD5 = "NO_ITEMS_XML"; // // Path: src/de/neuland/firefly/utils/MD5Util.java // public static String generateMD5(String baseValue) { // return generateMD5(baseValue, "UTF-8", "MD5"); // } // // Path: src/de/neuland/firefly/utils/XMLUtil.java // public static String loadAndNormalizeXML(File xmlFile) throws ParserConfigurationException, SAXException, IOException, TransformerException { // DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); // DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); // Document doc = dBuilder.parse(xmlFile); // // removeRecursively(doc); // doc.normalizeDocument(); // // TransformerFactory tf = TransformerFactory.newInstance(); // Transformer transformer = tf.newTransformer(); // transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); // transformer.setOutputProperty(OutputKeys.INDENT, "no"); // StringWriter normalizedXml = new StringWriter(); // transformer.transform(new DOMSource(doc), new StreamResult(normalizedXml)); // return normalizedXml.toString(); // }
import de.hybris.platform.core.PK; import de.neuland.firefly.migration.MigrationRepository; import de.neuland.firefly.model.FireflyExtensionModel; import de.neuland.firefly.model.FireflyExtensionStateModel; import de.neuland.firefly.model.FireflyMigrationModel; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.builder.ToStringBuilder; import org.xml.sax.SAXException; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerException; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import static de.neuland.firefly.constants.FireflyConstants.NO_HMC_XML_MD5; import static de.neuland.firefly.constants.FireflyConstants.NO_ITEMS_XML_MD5; import static de.neuland.firefly.utils.MD5Util.generateMD5; import static de.neuland.firefly.utils.XMLUtil.loadAndNormalizeXML; import static java.util.Arrays.asList;
} fireflyExtensionRepository.save(fireflyExtensionModel); } public void onUpdate(PK migration) { FireflyMigrationModel migrationModel = migrationRepository.findByPk(migration); FireflyExtensionModel fireflyExtensionModel = getOrCreateFireflyExtensionModel(); String itemsDefinitionHash = getItemsDefinitionHash(); String hmcDefinitionHash = getHmcDefinitionHash(); if (!equalsHash(getLastState(fireflyExtensionModel), itemsDefinitionHash, hmcDefinitionHash)) { createState(fireflyExtensionModel, migrationModel, itemsDefinitionHash, hmcDefinitionHash); } fireflyExtensionRepository.save(fireflyExtensionModel); } String getName() { return name; } File getRootPath() { return rootPath; } String getItemsDefinitionHash() { return getHashFromFile(new File(rootPath, "resources/" + name + "-items.xml"), NO_ITEMS_XML_MD5); } String getHmcDefinitionHash() {
// Path: src/de/neuland/firefly/migration/MigrationRepository.java // @Repository // @Scope("prototype") // public class MigrationRepository { // @Autowired private ModelService modelService; // // public FireflyMigrationModel findByPk(PK pk) { // return modelService.get(pk); // } // // public FireflyMigrationModel create() { // return modelService.create(FireflyMigrationModel.class); // } // // public void save(FireflyMigrationModel migration) { // modelService.save(migration); // } // } // // Path: src/de/neuland/firefly/constants/FireflyConstants.java // public static final String NO_HMC_XML_MD5 = "NO_HMC_XML"; // // Path: src/de/neuland/firefly/constants/FireflyConstants.java // public static final String NO_ITEMS_XML_MD5 = "NO_ITEMS_XML"; // // Path: src/de/neuland/firefly/utils/MD5Util.java // public static String generateMD5(String baseValue) { // return generateMD5(baseValue, "UTF-8", "MD5"); // } // // Path: src/de/neuland/firefly/utils/XMLUtil.java // public static String loadAndNormalizeXML(File xmlFile) throws ParserConfigurationException, SAXException, IOException, TransformerException { // DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); // DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); // Document doc = dBuilder.parse(xmlFile); // // removeRecursively(doc); // doc.normalizeDocument(); // // TransformerFactory tf = TransformerFactory.newInstance(); // Transformer transformer = tf.newTransformer(); // transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); // transformer.setOutputProperty(OutputKeys.INDENT, "no"); // StringWriter normalizedXml = new StringWriter(); // transformer.transform(new DOMSource(doc), new StreamResult(normalizedXml)); // return normalizedXml.toString(); // } // Path: src/de/neuland/firefly/extensionfinder/FireflyExtension.java import de.hybris.platform.core.PK; import de.neuland.firefly.migration.MigrationRepository; import de.neuland.firefly.model.FireflyExtensionModel; import de.neuland.firefly.model.FireflyExtensionStateModel; import de.neuland.firefly.model.FireflyMigrationModel; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.builder.ToStringBuilder; import org.xml.sax.SAXException; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerException; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import static de.neuland.firefly.constants.FireflyConstants.NO_HMC_XML_MD5; import static de.neuland.firefly.constants.FireflyConstants.NO_ITEMS_XML_MD5; import static de.neuland.firefly.utils.MD5Util.generateMD5; import static de.neuland.firefly.utils.XMLUtil.loadAndNormalizeXML; import static java.util.Arrays.asList; } fireflyExtensionRepository.save(fireflyExtensionModel); } public void onUpdate(PK migration) { FireflyMigrationModel migrationModel = migrationRepository.findByPk(migration); FireflyExtensionModel fireflyExtensionModel = getOrCreateFireflyExtensionModel(); String itemsDefinitionHash = getItemsDefinitionHash(); String hmcDefinitionHash = getHmcDefinitionHash(); if (!equalsHash(getLastState(fireflyExtensionModel), itemsDefinitionHash, hmcDefinitionHash)) { createState(fireflyExtensionModel, migrationModel, itemsDefinitionHash, hmcDefinitionHash); } fireflyExtensionRepository.save(fireflyExtensionModel); } String getName() { return name; } File getRootPath() { return rootPath; } String getItemsDefinitionHash() { return getHashFromFile(new File(rootPath, "resources/" + name + "-items.xml"), NO_ITEMS_XML_MD5); } String getHmcDefinitionHash() {
return getHashFromFile(new File(rootPath, "hmc/resources/hmc.xml"), NO_HMC_XML_MD5);
neuland/firefly
src/de/neuland/firefly/extensionfinder/FireflyExtension.java
// Path: src/de/neuland/firefly/migration/MigrationRepository.java // @Repository // @Scope("prototype") // public class MigrationRepository { // @Autowired private ModelService modelService; // // public FireflyMigrationModel findByPk(PK pk) { // return modelService.get(pk); // } // // public FireflyMigrationModel create() { // return modelService.create(FireflyMigrationModel.class); // } // // public void save(FireflyMigrationModel migration) { // modelService.save(migration); // } // } // // Path: src/de/neuland/firefly/constants/FireflyConstants.java // public static final String NO_HMC_XML_MD5 = "NO_HMC_XML"; // // Path: src/de/neuland/firefly/constants/FireflyConstants.java // public static final String NO_ITEMS_XML_MD5 = "NO_ITEMS_XML"; // // Path: src/de/neuland/firefly/utils/MD5Util.java // public static String generateMD5(String baseValue) { // return generateMD5(baseValue, "UTF-8", "MD5"); // } // // Path: src/de/neuland/firefly/utils/XMLUtil.java // public static String loadAndNormalizeXML(File xmlFile) throws ParserConfigurationException, SAXException, IOException, TransformerException { // DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); // DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); // Document doc = dBuilder.parse(xmlFile); // // removeRecursively(doc); // doc.normalizeDocument(); // // TransformerFactory tf = TransformerFactory.newInstance(); // Transformer transformer = tf.newTransformer(); // transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); // transformer.setOutputProperty(OutputKeys.INDENT, "no"); // StringWriter normalizedXml = new StringWriter(); // transformer.transform(new DOMSource(doc), new StreamResult(normalizedXml)); // return normalizedXml.toString(); // }
import de.hybris.platform.core.PK; import de.neuland.firefly.migration.MigrationRepository; import de.neuland.firefly.model.FireflyExtensionModel; import de.neuland.firefly.model.FireflyExtensionStateModel; import de.neuland.firefly.model.FireflyMigrationModel; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.builder.ToStringBuilder; import org.xml.sax.SAXException; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerException; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import static de.neuland.firefly.constants.FireflyConstants.NO_HMC_XML_MD5; import static de.neuland.firefly.constants.FireflyConstants.NO_ITEMS_XML_MD5; import static de.neuland.firefly.utils.MD5Util.generateMD5; import static de.neuland.firefly.utils.XMLUtil.loadAndNormalizeXML; import static java.util.Arrays.asList;
return ToStringBuilder.reflectionToString(this); } private boolean containsItemDefinitionHash(String itemsDefinitionHash, List<FireflyExtensionStateModel> states) { for (FireflyExtensionStateModel state : states) { if (StringUtils.equals(itemsDefinitionHash, state.getItemsDefinitionHash())) { return true; } } return false; } private boolean containsHmcDefinitionHash(String hmcDefinitionHash, List<FireflyExtensionStateModel> states) { for (FireflyExtensionStateModel state : states) { if (StringUtils.equals(hmcDefinitionHash, state.getHmcDefinitionHash())) { return true; } } return false; } private boolean equalsHash(FireflyExtensionStateModel lastState, String itemsDefinitionHash, String hmcDefinitionHash) { return lastState != null && StringUtils.equals(lastState.getItemsDefinitionHash(), itemsDefinitionHash) && StringUtils.equals(lastState.getHmcDefinitionHash(), hmcDefinitionHash); } private String getHashFromFile(File xml, String defaultHash) { if (xml.exists()) { try {
// Path: src/de/neuland/firefly/migration/MigrationRepository.java // @Repository // @Scope("prototype") // public class MigrationRepository { // @Autowired private ModelService modelService; // // public FireflyMigrationModel findByPk(PK pk) { // return modelService.get(pk); // } // // public FireflyMigrationModel create() { // return modelService.create(FireflyMigrationModel.class); // } // // public void save(FireflyMigrationModel migration) { // modelService.save(migration); // } // } // // Path: src/de/neuland/firefly/constants/FireflyConstants.java // public static final String NO_HMC_XML_MD5 = "NO_HMC_XML"; // // Path: src/de/neuland/firefly/constants/FireflyConstants.java // public static final String NO_ITEMS_XML_MD5 = "NO_ITEMS_XML"; // // Path: src/de/neuland/firefly/utils/MD5Util.java // public static String generateMD5(String baseValue) { // return generateMD5(baseValue, "UTF-8", "MD5"); // } // // Path: src/de/neuland/firefly/utils/XMLUtil.java // public static String loadAndNormalizeXML(File xmlFile) throws ParserConfigurationException, SAXException, IOException, TransformerException { // DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); // DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); // Document doc = dBuilder.parse(xmlFile); // // removeRecursively(doc); // doc.normalizeDocument(); // // TransformerFactory tf = TransformerFactory.newInstance(); // Transformer transformer = tf.newTransformer(); // transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); // transformer.setOutputProperty(OutputKeys.INDENT, "no"); // StringWriter normalizedXml = new StringWriter(); // transformer.transform(new DOMSource(doc), new StreamResult(normalizedXml)); // return normalizedXml.toString(); // } // Path: src/de/neuland/firefly/extensionfinder/FireflyExtension.java import de.hybris.platform.core.PK; import de.neuland.firefly.migration.MigrationRepository; import de.neuland.firefly.model.FireflyExtensionModel; import de.neuland.firefly.model.FireflyExtensionStateModel; import de.neuland.firefly.model.FireflyMigrationModel; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.builder.ToStringBuilder; import org.xml.sax.SAXException; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerException; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import static de.neuland.firefly.constants.FireflyConstants.NO_HMC_XML_MD5; import static de.neuland.firefly.constants.FireflyConstants.NO_ITEMS_XML_MD5; import static de.neuland.firefly.utils.MD5Util.generateMD5; import static de.neuland.firefly.utils.XMLUtil.loadAndNormalizeXML; import static java.util.Arrays.asList; return ToStringBuilder.reflectionToString(this); } private boolean containsItemDefinitionHash(String itemsDefinitionHash, List<FireflyExtensionStateModel> states) { for (FireflyExtensionStateModel state : states) { if (StringUtils.equals(itemsDefinitionHash, state.getItemsDefinitionHash())) { return true; } } return false; } private boolean containsHmcDefinitionHash(String hmcDefinitionHash, List<FireflyExtensionStateModel> states) { for (FireflyExtensionStateModel state : states) { if (StringUtils.equals(hmcDefinitionHash, state.getHmcDefinitionHash())) { return true; } } return false; } private boolean equalsHash(FireflyExtensionStateModel lastState, String itemsDefinitionHash, String hmcDefinitionHash) { return lastState != null && StringUtils.equals(lastState.getItemsDefinitionHash(), itemsDefinitionHash) && StringUtils.equals(lastState.getHmcDefinitionHash(), hmcDefinitionHash); } private String getHashFromFile(File xml, String defaultHash) { if (xml.exists()) { try {
return generateMD5(loadAndNormalizeXML(xml));
neuland/firefly
src/de/neuland/firefly/extensionfinder/FireflyExtension.java
// Path: src/de/neuland/firefly/migration/MigrationRepository.java // @Repository // @Scope("prototype") // public class MigrationRepository { // @Autowired private ModelService modelService; // // public FireflyMigrationModel findByPk(PK pk) { // return modelService.get(pk); // } // // public FireflyMigrationModel create() { // return modelService.create(FireflyMigrationModel.class); // } // // public void save(FireflyMigrationModel migration) { // modelService.save(migration); // } // } // // Path: src/de/neuland/firefly/constants/FireflyConstants.java // public static final String NO_HMC_XML_MD5 = "NO_HMC_XML"; // // Path: src/de/neuland/firefly/constants/FireflyConstants.java // public static final String NO_ITEMS_XML_MD5 = "NO_ITEMS_XML"; // // Path: src/de/neuland/firefly/utils/MD5Util.java // public static String generateMD5(String baseValue) { // return generateMD5(baseValue, "UTF-8", "MD5"); // } // // Path: src/de/neuland/firefly/utils/XMLUtil.java // public static String loadAndNormalizeXML(File xmlFile) throws ParserConfigurationException, SAXException, IOException, TransformerException { // DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); // DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); // Document doc = dBuilder.parse(xmlFile); // // removeRecursively(doc); // doc.normalizeDocument(); // // TransformerFactory tf = TransformerFactory.newInstance(); // Transformer transformer = tf.newTransformer(); // transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); // transformer.setOutputProperty(OutputKeys.INDENT, "no"); // StringWriter normalizedXml = new StringWriter(); // transformer.transform(new DOMSource(doc), new StreamResult(normalizedXml)); // return normalizedXml.toString(); // }
import de.hybris.platform.core.PK; import de.neuland.firefly.migration.MigrationRepository; import de.neuland.firefly.model.FireflyExtensionModel; import de.neuland.firefly.model.FireflyExtensionStateModel; import de.neuland.firefly.model.FireflyMigrationModel; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.builder.ToStringBuilder; import org.xml.sax.SAXException; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerException; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import static de.neuland.firefly.constants.FireflyConstants.NO_HMC_XML_MD5; import static de.neuland.firefly.constants.FireflyConstants.NO_ITEMS_XML_MD5; import static de.neuland.firefly.utils.MD5Util.generateMD5; import static de.neuland.firefly.utils.XMLUtil.loadAndNormalizeXML; import static java.util.Arrays.asList;
return ToStringBuilder.reflectionToString(this); } private boolean containsItemDefinitionHash(String itemsDefinitionHash, List<FireflyExtensionStateModel> states) { for (FireflyExtensionStateModel state : states) { if (StringUtils.equals(itemsDefinitionHash, state.getItemsDefinitionHash())) { return true; } } return false; } private boolean containsHmcDefinitionHash(String hmcDefinitionHash, List<FireflyExtensionStateModel> states) { for (FireflyExtensionStateModel state : states) { if (StringUtils.equals(hmcDefinitionHash, state.getHmcDefinitionHash())) { return true; } } return false; } private boolean equalsHash(FireflyExtensionStateModel lastState, String itemsDefinitionHash, String hmcDefinitionHash) { return lastState != null && StringUtils.equals(lastState.getItemsDefinitionHash(), itemsDefinitionHash) && StringUtils.equals(lastState.getHmcDefinitionHash(), hmcDefinitionHash); } private String getHashFromFile(File xml, String defaultHash) { if (xml.exists()) { try {
// Path: src/de/neuland/firefly/migration/MigrationRepository.java // @Repository // @Scope("prototype") // public class MigrationRepository { // @Autowired private ModelService modelService; // // public FireflyMigrationModel findByPk(PK pk) { // return modelService.get(pk); // } // // public FireflyMigrationModel create() { // return modelService.create(FireflyMigrationModel.class); // } // // public void save(FireflyMigrationModel migration) { // modelService.save(migration); // } // } // // Path: src/de/neuland/firefly/constants/FireflyConstants.java // public static final String NO_HMC_XML_MD5 = "NO_HMC_XML"; // // Path: src/de/neuland/firefly/constants/FireflyConstants.java // public static final String NO_ITEMS_XML_MD5 = "NO_ITEMS_XML"; // // Path: src/de/neuland/firefly/utils/MD5Util.java // public static String generateMD5(String baseValue) { // return generateMD5(baseValue, "UTF-8", "MD5"); // } // // Path: src/de/neuland/firefly/utils/XMLUtil.java // public static String loadAndNormalizeXML(File xmlFile) throws ParserConfigurationException, SAXException, IOException, TransformerException { // DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); // DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); // Document doc = dBuilder.parse(xmlFile); // // removeRecursively(doc); // doc.normalizeDocument(); // // TransformerFactory tf = TransformerFactory.newInstance(); // Transformer transformer = tf.newTransformer(); // transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); // transformer.setOutputProperty(OutputKeys.INDENT, "no"); // StringWriter normalizedXml = new StringWriter(); // transformer.transform(new DOMSource(doc), new StreamResult(normalizedXml)); // return normalizedXml.toString(); // } // Path: src/de/neuland/firefly/extensionfinder/FireflyExtension.java import de.hybris.platform.core.PK; import de.neuland.firefly.migration.MigrationRepository; import de.neuland.firefly.model.FireflyExtensionModel; import de.neuland.firefly.model.FireflyExtensionStateModel; import de.neuland.firefly.model.FireflyMigrationModel; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.builder.ToStringBuilder; import org.xml.sax.SAXException; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerException; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import static de.neuland.firefly.constants.FireflyConstants.NO_HMC_XML_MD5; import static de.neuland.firefly.constants.FireflyConstants.NO_ITEMS_XML_MD5; import static de.neuland.firefly.utils.MD5Util.generateMD5; import static de.neuland.firefly.utils.XMLUtil.loadAndNormalizeXML; import static java.util.Arrays.asList; return ToStringBuilder.reflectionToString(this); } private boolean containsItemDefinitionHash(String itemsDefinitionHash, List<FireflyExtensionStateModel> states) { for (FireflyExtensionStateModel state : states) { if (StringUtils.equals(itemsDefinitionHash, state.getItemsDefinitionHash())) { return true; } } return false; } private boolean containsHmcDefinitionHash(String hmcDefinitionHash, List<FireflyExtensionStateModel> states) { for (FireflyExtensionStateModel state : states) { if (StringUtils.equals(hmcDefinitionHash, state.getHmcDefinitionHash())) { return true; } } return false; } private boolean equalsHash(FireflyExtensionStateModel lastState, String itemsDefinitionHash, String hmcDefinitionHash) { return lastState != null && StringUtils.equals(lastState.getItemsDefinitionHash(), itemsDefinitionHash) && StringUtils.equals(lastState.getHmcDefinitionHash(), hmcDefinitionHash); } private String getHashFromFile(File xml, String defaultHash) { if (xml.exists()) { try {
return generateMD5(loadAndNormalizeXML(xml));
neuland/firefly
testsrc/de/neuland/firefly/MigrationOnStartupListenerTest.java
// Path: src/de/neuland/firefly/web/ApplicationStartupEvent.java // public class ApplicationStartupEvent extends AbstractEvent { // @Override public String toString() { // return getClass().getSimpleName(); // } // }
import de.hybris.platform.servicelayer.cluster.ClusterService; import de.hybris.platform.servicelayer.tenant.TenantService; import de.neuland.firefly.web.ApplicationStartupEvent; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import static org.mockito.Mockito.verify;
package de.neuland.firefly; @RunWith(MockitoJUnitRunner.class) public class MigrationOnStartupListenerTest { @Mock private FireflyService fireflyService; @Test public void shouldStartAutomaticMigration() { // given MigrationOnStartupListener listener = new MigrationOnStartupListener( fireflyService, true); // when
// Path: src/de/neuland/firefly/web/ApplicationStartupEvent.java // public class ApplicationStartupEvent extends AbstractEvent { // @Override public String toString() { // return getClass().getSimpleName(); // } // } // Path: testsrc/de/neuland/firefly/MigrationOnStartupListenerTest.java import de.hybris.platform.servicelayer.cluster.ClusterService; import de.hybris.platform.servicelayer.tenant.TenantService; import de.neuland.firefly.web.ApplicationStartupEvent; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import static org.mockito.Mockito.verify; package de.neuland.firefly; @RunWith(MockitoJUnitRunner.class) public class MigrationOnStartupListenerTest { @Mock private FireflyService fireflyService; @Test public void shouldStartAutomaticMigration() { // given MigrationOnStartupListener listener = new MigrationOnStartupListener( fireflyService, true); // when
listener.onApplicationEvent(new ApplicationStartupEvent());
cxbiao/Android_Study_Demos
tubatu-viewpager-master/app/src/main/java/com/hhl/tubatu/MainActivity.java
// Path: tubatu-viewpager-master/app/src/main/java/com/hhl/tubatu/adapter/RecyclingPagerAdapter.java // public abstract class RecyclingPagerAdapter extends PagerAdapter { // static final int IGNORE_ITEM_VIEW_TYPE = AdapterView.ITEM_VIEW_TYPE_IGNORE; // // private final RecycleBin recycleBin; // // public RecyclingPagerAdapter() { // this(new RecycleBin()); // } // // RecyclingPagerAdapter(RecycleBin recycleBin) { // this.recycleBin = recycleBin; // recycleBin.setViewTypeCount(getViewTypeCount()); // } // // @Override // public void notifyDataSetChanged() { // recycleBin.scrapActiveViews(); // super.notifyDataSetChanged(); // } // // @Override // public final Object instantiateItem(ViewGroup container, int position) { // int viewType = getItemViewType(position); // View view = null; // if (viewType != IGNORE_ITEM_VIEW_TYPE) { // view = recycleBin.getScrapView(position, viewType); // } // view = getView(position, view, container); // container.addView(view); // return view; // } // // @Override // public final void destroyItem(ViewGroup container, int position, Object object) { // View view = (View) object; // container.removeView(view); // int viewType = getItemViewType(position); // if (viewType != IGNORE_ITEM_VIEW_TYPE) { // recycleBin.addScrapView(view, position, viewType); // } // } // // @Override // public final boolean isViewFromObject(View view, Object object) { // return view == object; // } // // /** // * <p> // * Returns the number of types of Views that will be created by // * {@link #getView}. Each type represents a set of views that can be // * converted in {@link #getView}. If the adapter always returns the same // * type of View for all items, this method should return 1. // * </p> // * <p> // * This method will only be called when when the adapter is set on the // * the {@link AdapterView}. // * </p> // * // * @return The number of types of Views that will be created by this adapter // */ // public int getViewTypeCount() { // return 1; // } // // /** // * Get the type of View that will be created by {@link #getView} for the specified item. // * // * @param position The position of the item within the adapter's data set whose view type we // * want. // * @return An integer representing the type of View. Two views should share the same type if one // * can be converted to the other in {@link #getView}. Note: Integers must be in the // * range 0 to {@link #getViewTypeCount} - 1. {@link #IGNORE_ITEM_VIEW_TYPE} can // * also be returned. // * @see #IGNORE_ITEM_VIEW_TYPE // */ // @SuppressWarnings("UnusedParameters") // Argument potentially used by subclasses. // public int getItemViewType(int position) { // return 0; // } // // /** // * Get a View that displays the data at the specified position in the data set. You can either // * create a View manually or inflate it from an XML layout file. When the View is inflated, the // * parent View (GridView, ListView...) will apply default layout parameters unless you use // * {@link android.view.LayoutInflater#inflate(int, ViewGroup, boolean)} // * to specify a root view and to prevent attachment to the root. // * // * @param position The position of the item within the adapter's data set of the item whose view // * we want. // * @param convertView The old view to reuse, if possible. Note: You should check that this view // * is non-null and of an appropriate type before using. If it is not possible to convert // * this view to display the correct data, this method can create a new view. // * Heterogeneous lists can specify their number of view types, so that this View is // * always of the right type (see {@link #getViewTypeCount()} and // * {@link #getItemViewType(int)}). // * @param container The parent that this view will eventually be attached to // * @return A View corresponding to the data at the specified position. // */ // public abstract View getView(int position, View convertView, ViewGroup container); // }
import android.content.Context; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import com.hhl.tubatu.adapter.RecyclingPagerAdapter; import java.util.ArrayList; import java.util.List;
findViewById(R.id.page_container).setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { return mViewPager.dispatchTouchEvent(event); } }); mPagerAdapter = new TubatuAdapter(this); mViewPager.setAdapter(mPagerAdapter); initData(); } private void initData() { List<Integer> list = new ArrayList<>(); list.add(R.drawable.style_xiandai); list.add(R.drawable.style_jianyue); list.add(R.drawable.style_oushi); list.add(R.drawable.style_zhongshi); list.add(R.drawable.style_meishi); list.add(R.drawable.style_dzh); list.add(R.drawable.style_dny); list.add(R.drawable.style_rishi); //设置OffscreenPageLimit mViewPager.setOffscreenPageLimit(list.size()); mPagerAdapter.addAll(list); }
// Path: tubatu-viewpager-master/app/src/main/java/com/hhl/tubatu/adapter/RecyclingPagerAdapter.java // public abstract class RecyclingPagerAdapter extends PagerAdapter { // static final int IGNORE_ITEM_VIEW_TYPE = AdapterView.ITEM_VIEW_TYPE_IGNORE; // // private final RecycleBin recycleBin; // // public RecyclingPagerAdapter() { // this(new RecycleBin()); // } // // RecyclingPagerAdapter(RecycleBin recycleBin) { // this.recycleBin = recycleBin; // recycleBin.setViewTypeCount(getViewTypeCount()); // } // // @Override // public void notifyDataSetChanged() { // recycleBin.scrapActiveViews(); // super.notifyDataSetChanged(); // } // // @Override // public final Object instantiateItem(ViewGroup container, int position) { // int viewType = getItemViewType(position); // View view = null; // if (viewType != IGNORE_ITEM_VIEW_TYPE) { // view = recycleBin.getScrapView(position, viewType); // } // view = getView(position, view, container); // container.addView(view); // return view; // } // // @Override // public final void destroyItem(ViewGroup container, int position, Object object) { // View view = (View) object; // container.removeView(view); // int viewType = getItemViewType(position); // if (viewType != IGNORE_ITEM_VIEW_TYPE) { // recycleBin.addScrapView(view, position, viewType); // } // } // // @Override // public final boolean isViewFromObject(View view, Object object) { // return view == object; // } // // /** // * <p> // * Returns the number of types of Views that will be created by // * {@link #getView}. Each type represents a set of views that can be // * converted in {@link #getView}. If the adapter always returns the same // * type of View for all items, this method should return 1. // * </p> // * <p> // * This method will only be called when when the adapter is set on the // * the {@link AdapterView}. // * </p> // * // * @return The number of types of Views that will be created by this adapter // */ // public int getViewTypeCount() { // return 1; // } // // /** // * Get the type of View that will be created by {@link #getView} for the specified item. // * // * @param position The position of the item within the adapter's data set whose view type we // * want. // * @return An integer representing the type of View. Two views should share the same type if one // * can be converted to the other in {@link #getView}. Note: Integers must be in the // * range 0 to {@link #getViewTypeCount} - 1. {@link #IGNORE_ITEM_VIEW_TYPE} can // * also be returned. // * @see #IGNORE_ITEM_VIEW_TYPE // */ // @SuppressWarnings("UnusedParameters") // Argument potentially used by subclasses. // public int getItemViewType(int position) { // return 0; // } // // /** // * Get a View that displays the data at the specified position in the data set. You can either // * create a View manually or inflate it from an XML layout file. When the View is inflated, the // * parent View (GridView, ListView...) will apply default layout parameters unless you use // * {@link android.view.LayoutInflater#inflate(int, ViewGroup, boolean)} // * to specify a root view and to prevent attachment to the root. // * // * @param position The position of the item within the adapter's data set of the item whose view // * we want. // * @param convertView The old view to reuse, if possible. Note: You should check that this view // * is non-null and of an appropriate type before using. If it is not possible to convert // * this view to display the correct data, this method can create a new view. // * Heterogeneous lists can specify their number of view types, so that this View is // * always of the right type (see {@link #getViewTypeCount()} and // * {@link #getItemViewType(int)}). // * @param container The parent that this view will eventually be attached to // * @return A View corresponding to the data at the specified position. // */ // public abstract View getView(int position, View convertView, ViewGroup container); // } // Path: tubatu-viewpager-master/app/src/main/java/com/hhl/tubatu/MainActivity.java import android.content.Context; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import com.hhl.tubatu.adapter.RecyclingPagerAdapter; import java.util.ArrayList; import java.util.List; findViewById(R.id.page_container).setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { return mViewPager.dispatchTouchEvent(event); } }); mPagerAdapter = new TubatuAdapter(this); mViewPager.setAdapter(mPagerAdapter); initData(); } private void initData() { List<Integer> list = new ArrayList<>(); list.add(R.drawable.style_xiandai); list.add(R.drawable.style_jianyue); list.add(R.drawable.style_oushi); list.add(R.drawable.style_zhongshi); list.add(R.drawable.style_meishi); list.add(R.drawable.style_dzh); list.add(R.drawable.style_dny); list.add(R.drawable.style_rishi); //设置OffscreenPageLimit mViewPager.setOffscreenPageLimit(list.size()); mPagerAdapter.addAll(list); }
public static class TubatuAdapter extends RecyclingPagerAdapter {
cxbiao/Android_Study_Demos
recyclerviewDemo/src/com/zhy/sample/demo_recyclerview/StaggeredGridLayoutActivity.java
// Path: recyclerviewDemo/src/com/zhy/sample/demo_recyclerview/StaggeredHomeAdapter.java // public interface OnItemClickLitener // { // void onItemClick(View view, int position); // // void onItemLongClick(View view, int position); // }
import java.util.ArrayList; import java.util.List; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.StaggeredGridLayoutManager; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Toast; import com.zhy.sample.demo_recyclerview.StaggeredHomeAdapter.OnItemClickLitener;
package com.zhy.sample.demo_recyclerview; public class StaggeredGridLayoutActivity extends AppCompatActivity { private RecyclerView mRecyclerView; private List<String> mDatas; private StaggeredHomeAdapter mStaggeredHomeAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_single_recyclerview); initData(); mRecyclerView = (RecyclerView) findViewById(R.id.id_recyclerview); mStaggeredHomeAdapter = new StaggeredHomeAdapter(this, mDatas); mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL)); mRecyclerView.setAdapter(mStaggeredHomeAdapter); // 设置item动画 mRecyclerView.setItemAnimator(new DefaultItemAnimator()); initEvent(); } private void initEvent() {
// Path: recyclerviewDemo/src/com/zhy/sample/demo_recyclerview/StaggeredHomeAdapter.java // public interface OnItemClickLitener // { // void onItemClick(View view, int position); // // void onItemLongClick(View view, int position); // } // Path: recyclerviewDemo/src/com/zhy/sample/demo_recyclerview/StaggeredGridLayoutActivity.java import java.util.ArrayList; import java.util.List; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.StaggeredGridLayoutManager; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Toast; import com.zhy.sample.demo_recyclerview.StaggeredHomeAdapter.OnItemClickLitener; package com.zhy.sample.demo_recyclerview; public class StaggeredGridLayoutActivity extends AppCompatActivity { private RecyclerView mRecyclerView; private List<String> mDatas; private StaggeredHomeAdapter mStaggeredHomeAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_single_recyclerview); initData(); mRecyclerView = (RecyclerView) findViewById(R.id.id_recyclerview); mStaggeredHomeAdapter = new StaggeredHomeAdapter(this, mDatas); mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL)); mRecyclerView.setAdapter(mStaggeredHomeAdapter); // 设置item动画 mRecyclerView.setItemAnimator(new DefaultItemAnimator()); initEvent(); } private void initEvent() {
mStaggeredHomeAdapter.setOnItemClickLitener(new OnItemClickLitener()
cxbiao/Android_Study_Demos
PagerSlidingTabStripDemo/src/com/astuetz/QuickContactFragment.java
// Path: PagerSlidingTabStripDemo/src/com/astuetz/PagerSlidingTabStrip.java // public interface IconTabProvider { // public int getPageIconResId(int position); // }
import android.graphics.Point; import android.os.Build; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.util.TypedValue; import android.view.Display; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.widget.TextView; import com.astuetz.PagerSlidingTabStrip.IconTabProvider; import com.bryan.pagerslidingtabstripdemo.R;
@SuppressWarnings("deprecation") @Override public void onStart() { super.onStart(); // change dialog width if (getDialog() != null) { int fullWidth = getDialog().getWindow().getAttributes().width; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) { Display display = getActivity().getWindowManager().getDefaultDisplay(); Point size = new Point(); display.getSize(size); fullWidth = size.x; } else { Display display = getActivity().getWindowManager().getDefaultDisplay(); fullWidth = display.getWidth(); } final int padding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 24, getResources() .getDisplayMetrics()); int w = fullWidth - padding; int h = getDialog().getWindow().getAttributes().height; getDialog().getWindow().setLayout(w, h); } }
// Path: PagerSlidingTabStripDemo/src/com/astuetz/PagerSlidingTabStrip.java // public interface IconTabProvider { // public int getPageIconResId(int position); // } // Path: PagerSlidingTabStripDemo/src/com/astuetz/QuickContactFragment.java import android.graphics.Point; import android.os.Build; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.util.TypedValue; import android.view.Display; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.widget.TextView; import com.astuetz.PagerSlidingTabStrip.IconTabProvider; import com.bryan.pagerslidingtabstripdemo.R; @SuppressWarnings("deprecation") @Override public void onStart() { super.onStart(); // change dialog width if (getDialog() != null) { int fullWidth = getDialog().getWindow().getAttributes().width; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) { Display display = getActivity().getWindowManager().getDefaultDisplay(); Point size = new Point(); display.getSize(size); fullWidth = size.x; } else { Display display = getActivity().getWindowManager().getDefaultDisplay(); fullWidth = display.getWidth(); } final int padding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 24, getResources() .getDisplayMetrics()); int w = fullWidth - padding; int h = getDialog().getWindow().getAttributes().height; getDialog().getWindow().setLayout(w, h); } }
public class ContactPagerAdapter extends PagerAdapter implements IconTabProvider {
cxbiao/Android_Study_Demos
PicChooser/src/main/java/com/bryan/picchooser/utils/ViewHolder.java
// Path: PicChooser/src/main/java/com/bryan/picchooser/utils/ImageLoader.java // public enum Type // { // FIFO, LIFO // }
import android.content.Context; import android.graphics.Bitmap; import android.util.SparseArray; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.bryan.picchooser.utils.ImageLoader.Type;
{ ImageView view = getView(viewId); view.setImageResource(drawableId); return this; } /** * 为ImageView设置图片 * * @param viewId * @param drawableId * @return */ public ViewHolder setImageBitmap(int viewId, Bitmap bm) { ImageView view = getView(viewId); view.setImageBitmap(bm); return this; } /** * 为ImageView设置图片 * * @param viewId * @param drawableId * @return */ public ViewHolder setImageByUrl(int viewId, String url) {
// Path: PicChooser/src/main/java/com/bryan/picchooser/utils/ImageLoader.java // public enum Type // { // FIFO, LIFO // } // Path: PicChooser/src/main/java/com/bryan/picchooser/utils/ViewHolder.java import android.content.Context; import android.graphics.Bitmap; import android.util.SparseArray; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.bryan.picchooser.utils.ImageLoader.Type; { ImageView view = getView(viewId); view.setImageResource(drawableId); return this; } /** * 为ImageView设置图片 * * @param viewId * @param drawableId * @return */ public ViewHolder setImageBitmap(int viewId, Bitmap bm) { ImageView view = getView(viewId); view.setImageBitmap(bm); return this; } /** * 为ImageView设置图片 * * @param viewId * @param drawableId * @return */ public ViewHolder setImageByUrl(int viewId, String url) {
ImageLoader.getInstance(3,Type.LIFO).loadImage(url, (ImageView) getView(viewId));
cxbiao/Android_Study_Demos
AndroidSwipeLayoutDemo/myswipedemo/src/main/java/bryan/com/myswipedemo/ListViewExample.java
// Path: AndroidSwipeLayoutDemo/myswipedemo/src/main/java/bryan/com/myswipedemo/adapter/ListViewAdapter.java // public class ListViewAdapter extends BaseSwipeAdapter { // // // private Context context; // // public ListViewAdapter(Context context){ // this.context=context; // } // // @Override // public int getSwipeLayoutResourceId(int position) { // //返回swipelayout的资源id // return R.id.swipelayout; // } // // @Override // public View generateView(int position, ViewGroup parent) { // return View.inflate(context,R.layout.listview_item,null); // } // // @Override // public void fillValues(final int position, View convertView) { // TextView textView= (TextView) convertView.findViewById(R.id.content); // textView.setText("这是内容" + position); // // final SwipeLayout swipeLayout= (SwipeLayout) convertView.findViewById(R.id.swipelayout); // swipeLayout.setDrag(SwipeLayout.DragEdge.Right,R.id.delete); // convertView.findViewById(R.id.delete).setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // Toast.makeText(context, "delete clicked", Toast.LENGTH_SHORT).show(); // } // }); // swipeLayout.getSurfaceView().setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // if(swipeLayout.getOpenStatus()==SwipeLayout.Status.Close){ // Toast.makeText(context, position+"clicked", Toast.LENGTH_SHORT).show(); // }else{ // swipeLayout.close(true); // } // // } // }); // // // // // } // // @Override // public int getCount() { // return 50; // } // // @Override // public Object getItem(int position) { // return null; // } // // @Override // public long getItemId(int position) { // return position; // } // }
import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.widget.AbsListView; import android.widget.AdapterView; import android.widget.ListView; import android.widget.Toast; import com.daimajia.swipe.util.Attributes; import bryan.com.myswipedemo.adapter.ListViewAdapter;
package bryan.com.myswipedemo; /** * Created by Administrator on 2015/8/3. */ public class ListViewExample extends Activity { ListView listView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.listview_demo); listView= (ListView) findViewById(R.id.listview);
// Path: AndroidSwipeLayoutDemo/myswipedemo/src/main/java/bryan/com/myswipedemo/adapter/ListViewAdapter.java // public class ListViewAdapter extends BaseSwipeAdapter { // // // private Context context; // // public ListViewAdapter(Context context){ // this.context=context; // } // // @Override // public int getSwipeLayoutResourceId(int position) { // //返回swipelayout的资源id // return R.id.swipelayout; // } // // @Override // public View generateView(int position, ViewGroup parent) { // return View.inflate(context,R.layout.listview_item,null); // } // // @Override // public void fillValues(final int position, View convertView) { // TextView textView= (TextView) convertView.findViewById(R.id.content); // textView.setText("这是内容" + position); // // final SwipeLayout swipeLayout= (SwipeLayout) convertView.findViewById(R.id.swipelayout); // swipeLayout.setDrag(SwipeLayout.DragEdge.Right,R.id.delete); // convertView.findViewById(R.id.delete).setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // Toast.makeText(context, "delete clicked", Toast.LENGTH_SHORT).show(); // } // }); // swipeLayout.getSurfaceView().setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // if(swipeLayout.getOpenStatus()==SwipeLayout.Status.Close){ // Toast.makeText(context, position+"clicked", Toast.LENGTH_SHORT).show(); // }else{ // swipeLayout.close(true); // } // // } // }); // // // // // } // // @Override // public int getCount() { // return 50; // } // // @Override // public Object getItem(int position) { // return null; // } // // @Override // public long getItemId(int position) { // return position; // } // } // Path: AndroidSwipeLayoutDemo/myswipedemo/src/main/java/bryan/com/myswipedemo/ListViewExample.java import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.widget.AbsListView; import android.widget.AdapterView; import android.widget.ListView; import android.widget.Toast; import com.daimajia.swipe.util.Attributes; import bryan.com.myswipedemo.adapter.ListViewAdapter; package bryan.com.myswipedemo; /** * Created by Administrator on 2015/8/3. */ public class ListViewExample extends Activity { ListView listView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.listview_demo); listView= (ListView) findViewById(R.id.listview);
ListViewAdapter adapter=new ListViewAdapter(this);
cxbiao/Android_Study_Demos
recyclerviewDemo/src/com/zhy/sample/demo_recyclerview/HomeActivity.java
// Path: recyclerviewDemo/src/com/zhy/sample/demo_recyclerview/HomeAdapter.java // public interface OnItemClickLitener // { // void onItemClick(View view, int position); // void onItemLongClick(View view , int position); // } // // Path: recyclerviewDemo/src/com/zhy/sample/refresh/RefreshActivity.java // public class RefreshActivity extends AppCompatActivity { // // TextView tv; // ScrollView scrollview; // ListView listView; // LinearLayout root; // private List<String> mDatas; // @Override // protected void onCreate(Bundle savedInstanceState) { // // TODO Auto-generated method stub // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_refresh); // // tv=(TextView) findViewById(R.id.tv); // scrollview=(ScrollView) findViewById(R.id.myScrollview); // listView=(ListView) findViewById(R.id.listview); // root=(LinearLayout) findViewById(R.id.root); // initData(); // // ArrayAdapter<String> adapter=new ArrayAdapter<String>(this, R.layout.item_home, R.id.id_num, mDatas); // listView.setAdapter(adapter); // } // // protected void initData() // { // mDatas = new ArrayList<String>(); // for (int i = 'A'; i < 'Z'; i++) // { // mDatas.add("" + (char) i); // } // } // // // // public void refresh(View v) { // // if(!ViewCompat.canScrollVertically(v, -1)){ // Toast.makeText(this, "拉到顶部了", 0).show(); // }else{ // Toast.makeText(this, "没拉到顶部了", 0).show(); // } // // } // // public void loadmore(View v) { // if(!ViewCompat.canScrollVertically(v, 1)){ // Toast.makeText(this, "拉到底部了", 0).show(); // }else{ // Toast.makeText(this, "没拉到底部了", 0).show(); // } // } // // // @Override // public boolean onCreateOptionsMenu(Menu menu) // { // getMenuInflater().inflate(R.menu.men_fresh, menu); // return super.onCreateOptionsMenu(menu); // } // // // @Override // public boolean onOptionsItemSelected(MenuItem item){ // switch (item.getItemId()) { // case R.id.id_action_refresh: // refresh(root); // break; // case R.id.id_action_more: // loadmore(root); // break; // default: // break; // } // return true; // } // }
import java.util.ArrayList; import java.util.List; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.StaggeredGridLayoutManager; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Toast; import com.zhy.sample.demo_recyclerview.HomeAdapter.OnItemClickLitener; import com.zhy.sample.refresh.RefreshActivity;
package com.zhy.sample.demo_recyclerview; public class HomeActivity extends AppCompatActivity { private RecyclerView mRecyclerView; private List<String> mDatas; private HomeAdapter mAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_single_recyclerview); initData(); mRecyclerView = (RecyclerView) findViewById(R.id.id_recyclerview); mAdapter = new HomeAdapter(this, mDatas); mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(4, StaggeredGridLayoutManager.VERTICAL)); mRecyclerView.setAdapter(mAdapter); mRecyclerView.addItemDecoration(new DividerGridItemDecoration(this)); // 设置item动画 mRecyclerView.setItemAnimator(new DefaultItemAnimator()); initEvent(); } private void initEvent() {
// Path: recyclerviewDemo/src/com/zhy/sample/demo_recyclerview/HomeAdapter.java // public interface OnItemClickLitener // { // void onItemClick(View view, int position); // void onItemLongClick(View view , int position); // } // // Path: recyclerviewDemo/src/com/zhy/sample/refresh/RefreshActivity.java // public class RefreshActivity extends AppCompatActivity { // // TextView tv; // ScrollView scrollview; // ListView listView; // LinearLayout root; // private List<String> mDatas; // @Override // protected void onCreate(Bundle savedInstanceState) { // // TODO Auto-generated method stub // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_refresh); // // tv=(TextView) findViewById(R.id.tv); // scrollview=(ScrollView) findViewById(R.id.myScrollview); // listView=(ListView) findViewById(R.id.listview); // root=(LinearLayout) findViewById(R.id.root); // initData(); // // ArrayAdapter<String> adapter=new ArrayAdapter<String>(this, R.layout.item_home, R.id.id_num, mDatas); // listView.setAdapter(adapter); // } // // protected void initData() // { // mDatas = new ArrayList<String>(); // for (int i = 'A'; i < 'Z'; i++) // { // mDatas.add("" + (char) i); // } // } // // // // public void refresh(View v) { // // if(!ViewCompat.canScrollVertically(v, -1)){ // Toast.makeText(this, "拉到顶部了", 0).show(); // }else{ // Toast.makeText(this, "没拉到顶部了", 0).show(); // } // // } // // public void loadmore(View v) { // if(!ViewCompat.canScrollVertically(v, 1)){ // Toast.makeText(this, "拉到底部了", 0).show(); // }else{ // Toast.makeText(this, "没拉到底部了", 0).show(); // } // } // // // @Override // public boolean onCreateOptionsMenu(Menu menu) // { // getMenuInflater().inflate(R.menu.men_fresh, menu); // return super.onCreateOptionsMenu(menu); // } // // // @Override // public boolean onOptionsItemSelected(MenuItem item){ // switch (item.getItemId()) { // case R.id.id_action_refresh: // refresh(root); // break; // case R.id.id_action_more: // loadmore(root); // break; // default: // break; // } // return true; // } // } // Path: recyclerviewDemo/src/com/zhy/sample/demo_recyclerview/HomeActivity.java import java.util.ArrayList; import java.util.List; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.StaggeredGridLayoutManager; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Toast; import com.zhy.sample.demo_recyclerview.HomeAdapter.OnItemClickLitener; import com.zhy.sample.refresh.RefreshActivity; package com.zhy.sample.demo_recyclerview; public class HomeActivity extends AppCompatActivity { private RecyclerView mRecyclerView; private List<String> mDatas; private HomeAdapter mAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_single_recyclerview); initData(); mRecyclerView = (RecyclerView) findViewById(R.id.id_recyclerview); mAdapter = new HomeAdapter(this, mDatas); mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(4, StaggeredGridLayoutManager.VERTICAL)); mRecyclerView.setAdapter(mAdapter); mRecyclerView.addItemDecoration(new DividerGridItemDecoration(this)); // 设置item动画 mRecyclerView.setItemAnimator(new DefaultItemAnimator()); initEvent(); } private void initEvent() {
mAdapter.setOnItemClickLitener(new OnItemClickLitener()
cxbiao/Android_Study_Demos
recyclerviewDemo/src/com/zhy/sample/demo_recyclerview/HomeActivity.java
// Path: recyclerviewDemo/src/com/zhy/sample/demo_recyclerview/HomeAdapter.java // public interface OnItemClickLitener // { // void onItemClick(View view, int position); // void onItemLongClick(View view , int position); // } // // Path: recyclerviewDemo/src/com/zhy/sample/refresh/RefreshActivity.java // public class RefreshActivity extends AppCompatActivity { // // TextView tv; // ScrollView scrollview; // ListView listView; // LinearLayout root; // private List<String> mDatas; // @Override // protected void onCreate(Bundle savedInstanceState) { // // TODO Auto-generated method stub // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_refresh); // // tv=(TextView) findViewById(R.id.tv); // scrollview=(ScrollView) findViewById(R.id.myScrollview); // listView=(ListView) findViewById(R.id.listview); // root=(LinearLayout) findViewById(R.id.root); // initData(); // // ArrayAdapter<String> adapter=new ArrayAdapter<String>(this, R.layout.item_home, R.id.id_num, mDatas); // listView.setAdapter(adapter); // } // // protected void initData() // { // mDatas = new ArrayList<String>(); // for (int i = 'A'; i < 'Z'; i++) // { // mDatas.add("" + (char) i); // } // } // // // // public void refresh(View v) { // // if(!ViewCompat.canScrollVertically(v, -1)){ // Toast.makeText(this, "拉到顶部了", 0).show(); // }else{ // Toast.makeText(this, "没拉到顶部了", 0).show(); // } // // } // // public void loadmore(View v) { // if(!ViewCompat.canScrollVertically(v, 1)){ // Toast.makeText(this, "拉到底部了", 0).show(); // }else{ // Toast.makeText(this, "没拉到底部了", 0).show(); // } // } // // // @Override // public boolean onCreateOptionsMenu(Menu menu) // { // getMenuInflater().inflate(R.menu.men_fresh, menu); // return super.onCreateOptionsMenu(menu); // } // // // @Override // public boolean onOptionsItemSelected(MenuItem item){ // switch (item.getItemId()) { // case R.id.id_action_refresh: // refresh(root); // break; // case R.id.id_action_more: // loadmore(root); // break; // default: // break; // } // return true; // } // }
import java.util.ArrayList; import java.util.List; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.StaggeredGridLayoutManager; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Toast; import com.zhy.sample.demo_recyclerview.HomeAdapter.OnItemClickLitener; import com.zhy.sample.refresh.RefreshActivity;
break; case R.id.id_action_delete: mAdapter.removeData(1); break; case R.id.id_action_gridview: mRecyclerView.setLayoutManager(new GridLayoutManager(this, 4)); break; case R.id.id_action_listview: mRecyclerView.setLayoutManager(new LinearLayoutManager(this)); break; case R.id.id_action_horizonlistview: mRecyclerView.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false)); break; case R.id.id_action_horizontalGridView: mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(4, StaggeredGridLayoutManager.HORIZONTAL)); break; case R.id.id_action_staggeredgridview:{ Intent intent = new Intent(this , StaggeredGridLayoutActivity.class); startActivity(intent); break; } case R.id.id_action_complex:{ Intent intent = new Intent(this , ComplexRecycleView.class); startActivity(intent); break; } case R.id.id_action_refesh:{
// Path: recyclerviewDemo/src/com/zhy/sample/demo_recyclerview/HomeAdapter.java // public interface OnItemClickLitener // { // void onItemClick(View view, int position); // void onItemLongClick(View view , int position); // } // // Path: recyclerviewDemo/src/com/zhy/sample/refresh/RefreshActivity.java // public class RefreshActivity extends AppCompatActivity { // // TextView tv; // ScrollView scrollview; // ListView listView; // LinearLayout root; // private List<String> mDatas; // @Override // protected void onCreate(Bundle savedInstanceState) { // // TODO Auto-generated method stub // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_refresh); // // tv=(TextView) findViewById(R.id.tv); // scrollview=(ScrollView) findViewById(R.id.myScrollview); // listView=(ListView) findViewById(R.id.listview); // root=(LinearLayout) findViewById(R.id.root); // initData(); // // ArrayAdapter<String> adapter=new ArrayAdapter<String>(this, R.layout.item_home, R.id.id_num, mDatas); // listView.setAdapter(adapter); // } // // protected void initData() // { // mDatas = new ArrayList<String>(); // for (int i = 'A'; i < 'Z'; i++) // { // mDatas.add("" + (char) i); // } // } // // // // public void refresh(View v) { // // if(!ViewCompat.canScrollVertically(v, -1)){ // Toast.makeText(this, "拉到顶部了", 0).show(); // }else{ // Toast.makeText(this, "没拉到顶部了", 0).show(); // } // // } // // public void loadmore(View v) { // if(!ViewCompat.canScrollVertically(v, 1)){ // Toast.makeText(this, "拉到底部了", 0).show(); // }else{ // Toast.makeText(this, "没拉到底部了", 0).show(); // } // } // // // @Override // public boolean onCreateOptionsMenu(Menu menu) // { // getMenuInflater().inflate(R.menu.men_fresh, menu); // return super.onCreateOptionsMenu(menu); // } // // // @Override // public boolean onOptionsItemSelected(MenuItem item){ // switch (item.getItemId()) { // case R.id.id_action_refresh: // refresh(root); // break; // case R.id.id_action_more: // loadmore(root); // break; // default: // break; // } // return true; // } // } // Path: recyclerviewDemo/src/com/zhy/sample/demo_recyclerview/HomeActivity.java import java.util.ArrayList; import java.util.List; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.StaggeredGridLayoutManager; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Toast; import com.zhy.sample.demo_recyclerview.HomeAdapter.OnItemClickLitener; import com.zhy.sample.refresh.RefreshActivity; break; case R.id.id_action_delete: mAdapter.removeData(1); break; case R.id.id_action_gridview: mRecyclerView.setLayoutManager(new GridLayoutManager(this, 4)); break; case R.id.id_action_listview: mRecyclerView.setLayoutManager(new LinearLayoutManager(this)); break; case R.id.id_action_horizonlistview: mRecyclerView.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false)); break; case R.id.id_action_horizontalGridView: mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(4, StaggeredGridLayoutManager.HORIZONTAL)); break; case R.id.id_action_staggeredgridview:{ Intent intent = new Intent(this , StaggeredGridLayoutActivity.class); startActivity(intent); break; } case R.id.id_action_complex:{ Intent intent = new Intent(this , ComplexRecycleView.class); startActivity(intent); break; } case R.id.id_action_refesh:{
Intent intent = new Intent(this , RefreshActivity.class);
cxbiao/Android_Study_Demos
PicChooser/src/main/java/com/bryan/picchooser/imageloader/ImageChooseActivity.java
// Path: PicChooser/src/main/java/com/bryan/picchooser/bean/ImageFloder.java // public class ImageFloder // { // /** // * 图片的文件夹路径 // */ // private String dir; // // /** // * 第一张图片的路径 // */ // private String firstImagePath; // // /** // * 文件夹的名称 // */ // private String name; // // /** // * 图片的数量 // */ // private int count; // // public String getDir() // { // return dir; // } // // public void setDir(String dir) // { // this.dir = dir; // int lastIndexOf = this.dir.lastIndexOf("/"); // this.name = this.dir.substring(lastIndexOf); // } // // public String getFirstImagePath() // { // return firstImagePath; // } // // public void setFirstImagePath(String firstImagePath) // { // this.firstImagePath = firstImagePath; // } // // public String getName() // { // return name; // } // public int getCount() // { // return count; // } // // public void setCount(int count) // { // this.count = count; // } // // // // }
import android.app.Activity; import android.app.ProgressDialog; import android.content.ContentResolver; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.provider.MediaStore; import android.util.DisplayMetrics; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup.LayoutParams; import android.view.WindowManager; import android.widget.GridView; import android.widget.PopupWindow.OnDismissListener; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.bryan.picchooser.R; import com.bryan.picchooser.bean.ImageFloder; import java.io.File; import java.io.FilenameFilter; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List;
package com.bryan.picchooser.imageloader; public class ImageChooseActivity extends Activity implements ListImageDirPopupWindow.OnImageDirSelected { private ProgressDialog mProgressDialog; /** * 存储文件夹中的图片数量 */ private int mPicsSize; /** * 图片数量最多的文件夹 */ private File mImgDir; /** * 所有的图片 */ private List<String> mImgs; private GridView mGirdView; private MyAdapter mAdapter; /** * 临时的辅助类,用于防止同一个文件夹的多次扫描 */ private HashSet<String> mDirPaths = new HashSet<String>(); /** * 扫描拿到所有的图片文件夹 */
// Path: PicChooser/src/main/java/com/bryan/picchooser/bean/ImageFloder.java // public class ImageFloder // { // /** // * 图片的文件夹路径 // */ // private String dir; // // /** // * 第一张图片的路径 // */ // private String firstImagePath; // // /** // * 文件夹的名称 // */ // private String name; // // /** // * 图片的数量 // */ // private int count; // // public String getDir() // { // return dir; // } // // public void setDir(String dir) // { // this.dir = dir; // int lastIndexOf = this.dir.lastIndexOf("/"); // this.name = this.dir.substring(lastIndexOf); // } // // public String getFirstImagePath() // { // return firstImagePath; // } // // public void setFirstImagePath(String firstImagePath) // { // this.firstImagePath = firstImagePath; // } // // public String getName() // { // return name; // } // public int getCount() // { // return count; // } // // public void setCount(int count) // { // this.count = count; // } // // // // } // Path: PicChooser/src/main/java/com/bryan/picchooser/imageloader/ImageChooseActivity.java import android.app.Activity; import android.app.ProgressDialog; import android.content.ContentResolver; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.provider.MediaStore; import android.util.DisplayMetrics; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup.LayoutParams; import android.view.WindowManager; import android.widget.GridView; import android.widget.PopupWindow.OnDismissListener; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.bryan.picchooser.R; import com.bryan.picchooser.bean.ImageFloder; import java.io.File; import java.io.FilenameFilter; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; package com.bryan.picchooser.imageloader; public class ImageChooseActivity extends Activity implements ListImageDirPopupWindow.OnImageDirSelected { private ProgressDialog mProgressDialog; /** * 存储文件夹中的图片数量 */ private int mPicsSize; /** * 图片数量最多的文件夹 */ private File mImgDir; /** * 所有的图片 */ private List<String> mImgs; private GridView mGirdView; private MyAdapter mAdapter; /** * 临时的辅助类,用于防止同一个文件夹的多次扫描 */ private HashSet<String> mDirPaths = new HashSet<String>(); /** * 扫描拿到所有的图片文件夹 */
private List<ImageFloder> mImageFloders = new ArrayList<ImageFloder>();
cxbiao/Android_Study_Demos
AndroidSwipeLayoutDemo/myswipedemo/src/main/java/bryan/com/myswipedemo/GridViewExample.java
// Path: AndroidSwipeLayoutDemo/myswipedemo/src/main/java/bryan/com/myswipedemo/adapter/GridViewAdapter.java // public class GridViewAdapter extends BaseSwipeAdapter { // // // private Context context; // // public GridViewAdapter(Context context){ // this.context=context; // } // // @Override // public int getSwipeLayoutResourceId(int position) { // //返回swipelayout的资源id // return R.id.swipelayout; // } // // @Override // public View generateView(int position, ViewGroup parent) { // return View.inflate(context,R.layout.gridview_item,null); // } // // @Override // public void fillValues(final int position, View convertView) { // TextView textView= (TextView) convertView.findViewById(R.id.content); // textView.setText("这是内容" + position); // // final SwipeLayout swipeLayout= (SwipeLayout) convertView.findViewById(R.id.swipelayout); // swipeLayout.setDrag(SwipeLayout.DragEdge.Right,R.id.delete); // convertView.findViewById(R.id.delete).setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // Toast.makeText(context, "delete clicked", Toast.LENGTH_SHORT).show(); // } // }); // swipeLayout.getSurfaceView().setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // if(swipeLayout.getOpenStatus()==SwipeLayout.Status.Close){ // Toast.makeText(context, position+"clicked", Toast.LENGTH_SHORT).show(); // }else{ // swipeLayout.close(true); // } // // // } // }); // // // // // } // // @Override // public int getCount() { // return 50; // } // // @Override // public Object getItem(int position) { // return null; // } // // @Override // public long getItemId(int position) { // return position; // } // }
import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.widget.AbsListView; import android.widget.AdapterView; import android.widget.GridView; import android.widget.Toast; import com.daimajia.swipe.util.Attributes; import bryan.com.myswipedemo.adapter.GridViewAdapter;
package bryan.com.myswipedemo; /** * Created by Administrator on 2015/8/3. */ public class GridViewExample extends Activity { GridView gridView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.gridview_demo); gridView= (GridView) findViewById(R.id.gridview);
// Path: AndroidSwipeLayoutDemo/myswipedemo/src/main/java/bryan/com/myswipedemo/adapter/GridViewAdapter.java // public class GridViewAdapter extends BaseSwipeAdapter { // // // private Context context; // // public GridViewAdapter(Context context){ // this.context=context; // } // // @Override // public int getSwipeLayoutResourceId(int position) { // //返回swipelayout的资源id // return R.id.swipelayout; // } // // @Override // public View generateView(int position, ViewGroup parent) { // return View.inflate(context,R.layout.gridview_item,null); // } // // @Override // public void fillValues(final int position, View convertView) { // TextView textView= (TextView) convertView.findViewById(R.id.content); // textView.setText("这是内容" + position); // // final SwipeLayout swipeLayout= (SwipeLayout) convertView.findViewById(R.id.swipelayout); // swipeLayout.setDrag(SwipeLayout.DragEdge.Right,R.id.delete); // convertView.findViewById(R.id.delete).setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // Toast.makeText(context, "delete clicked", Toast.LENGTH_SHORT).show(); // } // }); // swipeLayout.getSurfaceView().setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // if(swipeLayout.getOpenStatus()==SwipeLayout.Status.Close){ // Toast.makeText(context, position+"clicked", Toast.LENGTH_SHORT).show(); // }else{ // swipeLayout.close(true); // } // // // } // }); // // // // // } // // @Override // public int getCount() { // return 50; // } // // @Override // public Object getItem(int position) { // return null; // } // // @Override // public long getItemId(int position) { // return position; // } // } // Path: AndroidSwipeLayoutDemo/myswipedemo/src/main/java/bryan/com/myswipedemo/GridViewExample.java import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.widget.AbsListView; import android.widget.AdapterView; import android.widget.GridView; import android.widget.Toast; import com.daimajia.swipe.util.Attributes; import bryan.com.myswipedemo.adapter.GridViewAdapter; package bryan.com.myswipedemo; /** * Created by Administrator on 2015/8/3. */ public class GridViewExample extends Activity { GridView gridView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.gridview_demo); gridView= (GridView) findViewById(R.id.gridview);
GridViewAdapter adapter=new GridViewAdapter(this);
cxbiao/Android_Study_Demos
GreenDaoTest/app/src/main/java-gen/com/bryan/greendao/DaoMaster.java
// Path: GreenDaoTest/app/src/main/java-gen/com/bryan/greendao/NoteDao.java // public class NoteDao extends AbstractDao<Note, Long> { // // public static final String TABLENAME = "NOTE"; // // /** // * Properties of entity Note.<br/> // * Can be used for QueryBuilder and for referencing column names. // */ // public static class Properties { // public final static Property Id = new Property(0, Long.class, "id", true, "_id"); // public final static Property Text = new Property(1, String.class, "text", false, "TEXT"); // public final static Property Comment = new Property(2, String.class, "comment", false, "COMMENT"); // public final static Property Date = new Property(3, java.util.Date.class, "date", false, "DATE"); // }; // // // public NoteDao(DaoConfig config) { // super(config); // } // // public NoteDao(DaoConfig config, DaoSession daoSession) { // super(config, daoSession); // } // // /** Creates the underlying database table. */ // public static void createTable(SQLiteDatabase db, boolean ifNotExists) { // String constraint = ifNotExists? "IF NOT EXISTS ": ""; // db.execSQL("CREATE TABLE " + constraint + "\"NOTE\" (" + // // "\"_id\" INTEGER PRIMARY KEY ," + // 0: id // "\"TEXT\" TEXT NOT NULL ," + // 1: text // "\"COMMENT\" TEXT," + // 2: comment // "\"DATE\" INTEGER);"); // 3: date // } // // /** Drops the underlying database table. */ // public static void dropTable(SQLiteDatabase db, boolean ifExists) { // String sql = "DROP TABLE " + (ifExists ? "IF EXISTS " : "") + "\"NOTE\""; // db.execSQL(sql); // } // // /** @inheritdoc */ // @Override // protected void bindValues(SQLiteStatement stmt, Note entity) { // stmt.clearBindings(); // // Long id = entity.getId(); // if (id != null) { // stmt.bindLong(1, id); // } // stmt.bindString(2, entity.getText()); // // String comment = entity.getComment(); // if (comment != null) { // stmt.bindString(3, comment); // } // // java.util.Date date = entity.getDate(); // if (date != null) { // stmt.bindLong(4, date.getTime()); // } // } // // /** @inheritdoc */ // @Override // public Long readKey(Cursor cursor, int offset) { // return cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0); // } // // /** @inheritdoc */ // @Override // public Note readEntity(Cursor cursor, int offset) { // Note entity = new Note( // // cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0), // id // cursor.getString(offset + 1), // text // cursor.isNull(offset + 2) ? null : cursor.getString(offset + 2), // comment // cursor.isNull(offset + 3) ? null : new java.util.Date(cursor.getLong(offset + 3)) // date // ); // return entity; // } // // /** @inheritdoc */ // @Override // public void readEntity(Cursor cursor, Note entity, int offset) { // entity.setId(cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0)); // entity.setText(cursor.getString(offset + 1)); // entity.setComment(cursor.isNull(offset + 2) ? null : cursor.getString(offset + 2)); // entity.setDate(cursor.isNull(offset + 3) ? null : new java.util.Date(cursor.getLong(offset + 3))); // } // // /** @inheritdoc */ // @Override // protected Long updateKeyAfterInsert(Note entity, long rowId) { // entity.setId(rowId); // return rowId; // } // // /** @inheritdoc */ // @Override // public Long getKey(Note entity) { // if(entity != null) { // return entity.getId(); // } else { // return null; // } // } // // /** @inheritdoc */ // @Override // protected boolean isEntityUpdateable() { // return true; // } // // }
import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; import de.greenrobot.dao.AbstractDaoMaster; import de.greenrobot.dao.identityscope.IdentityScopeType; import com.bryan.greendao.NoteDao;
package com.bryan.greendao; // THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT. /** * Master of DAO (schema version 1): knows all DAOs. */ public class DaoMaster extends AbstractDaoMaster { public static final int SCHEMA_VERSION = 1; /** Creates underlying database table using DAOs. */ public static void createAllTables(SQLiteDatabase db, boolean ifNotExists) {
// Path: GreenDaoTest/app/src/main/java-gen/com/bryan/greendao/NoteDao.java // public class NoteDao extends AbstractDao<Note, Long> { // // public static final String TABLENAME = "NOTE"; // // /** // * Properties of entity Note.<br/> // * Can be used for QueryBuilder and for referencing column names. // */ // public static class Properties { // public final static Property Id = new Property(0, Long.class, "id", true, "_id"); // public final static Property Text = new Property(1, String.class, "text", false, "TEXT"); // public final static Property Comment = new Property(2, String.class, "comment", false, "COMMENT"); // public final static Property Date = new Property(3, java.util.Date.class, "date", false, "DATE"); // }; // // // public NoteDao(DaoConfig config) { // super(config); // } // // public NoteDao(DaoConfig config, DaoSession daoSession) { // super(config, daoSession); // } // // /** Creates the underlying database table. */ // public static void createTable(SQLiteDatabase db, boolean ifNotExists) { // String constraint = ifNotExists? "IF NOT EXISTS ": ""; // db.execSQL("CREATE TABLE " + constraint + "\"NOTE\" (" + // // "\"_id\" INTEGER PRIMARY KEY ," + // 0: id // "\"TEXT\" TEXT NOT NULL ," + // 1: text // "\"COMMENT\" TEXT," + // 2: comment // "\"DATE\" INTEGER);"); // 3: date // } // // /** Drops the underlying database table. */ // public static void dropTable(SQLiteDatabase db, boolean ifExists) { // String sql = "DROP TABLE " + (ifExists ? "IF EXISTS " : "") + "\"NOTE\""; // db.execSQL(sql); // } // // /** @inheritdoc */ // @Override // protected void bindValues(SQLiteStatement stmt, Note entity) { // stmt.clearBindings(); // // Long id = entity.getId(); // if (id != null) { // stmt.bindLong(1, id); // } // stmt.bindString(2, entity.getText()); // // String comment = entity.getComment(); // if (comment != null) { // stmt.bindString(3, comment); // } // // java.util.Date date = entity.getDate(); // if (date != null) { // stmt.bindLong(4, date.getTime()); // } // } // // /** @inheritdoc */ // @Override // public Long readKey(Cursor cursor, int offset) { // return cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0); // } // // /** @inheritdoc */ // @Override // public Note readEntity(Cursor cursor, int offset) { // Note entity = new Note( // // cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0), // id // cursor.getString(offset + 1), // text // cursor.isNull(offset + 2) ? null : cursor.getString(offset + 2), // comment // cursor.isNull(offset + 3) ? null : new java.util.Date(cursor.getLong(offset + 3)) // date // ); // return entity; // } // // /** @inheritdoc */ // @Override // public void readEntity(Cursor cursor, Note entity, int offset) { // entity.setId(cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0)); // entity.setText(cursor.getString(offset + 1)); // entity.setComment(cursor.isNull(offset + 2) ? null : cursor.getString(offset + 2)); // entity.setDate(cursor.isNull(offset + 3) ? null : new java.util.Date(cursor.getLong(offset + 3))); // } // // /** @inheritdoc */ // @Override // protected Long updateKeyAfterInsert(Note entity, long rowId) { // entity.setId(rowId); // return rowId; // } // // /** @inheritdoc */ // @Override // public Long getKey(Note entity) { // if(entity != null) { // return entity.getId(); // } else { // return null; // } // } // // /** @inheritdoc */ // @Override // protected boolean isEntityUpdateable() { // return true; // } // // } // Path: GreenDaoTest/app/src/main/java-gen/com/bryan/greendao/DaoMaster.java import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; import de.greenrobot.dao.AbstractDaoMaster; import de.greenrobot.dao.identityscope.IdentityScopeType; import com.bryan.greendao.NoteDao; package com.bryan.greendao; // THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT. /** * Master of DAO (schema version 1): knows all DAOs. */ public class DaoMaster extends AbstractDaoMaster { public static final int SCHEMA_VERSION = 1; /** Creates underlying database table using DAOs. */ public static void createAllTables(SQLiteDatabase db, boolean ifNotExists) {
NoteDao.createTable(db, ifNotExists);
cxbiao/Android_Study_Demos
MyViewPager/src/com/itheima/myscrollview28/MainActivity.java
// Path: MyViewPager/src/com/itheima/myscrollview28/MyScrollView.java // public interface MyPageChangedListener{ // void moveToDest(int currid); // }
import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.ImageView; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.RadioGroup.OnCheckedChangeListener; import com.itheima.myscrollview28.MyScrollView.MyPageChangedListener;
package com.itheima.myscrollview28; public class MainActivity extends Activity { private MyScrollView msv; //图片资源ID 数组 private int[] ids = new int[]{R.drawable.a1,R.drawable.a2,R.drawable.a3,R.drawable.a4,R.drawable.a5,R.drawable.a6}; private RadioGroup radioGroup; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); msv =(MyScrollView) findViewById(R.id.myscroll_view); radioGroup = (RadioGroup) findViewById(R.id.radioGroup); for (int i = 0; i < ids.length; i++) { ImageView image = new ImageView(this); image.setBackgroundResource(ids[i]); msv.addView(image); }
// Path: MyViewPager/src/com/itheima/myscrollview28/MyScrollView.java // public interface MyPageChangedListener{ // void moveToDest(int currid); // } // Path: MyViewPager/src/com/itheima/myscrollview28/MainActivity.java import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.ImageView; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.RadioGroup.OnCheckedChangeListener; import com.itheima.myscrollview28.MyScrollView.MyPageChangedListener; package com.itheima.myscrollview28; public class MainActivity extends Activity { private MyScrollView msv; //图片资源ID 数组 private int[] ids = new int[]{R.drawable.a1,R.drawable.a2,R.drawable.a3,R.drawable.a4,R.drawable.a5,R.drawable.a6}; private RadioGroup radioGroup; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); msv =(MyScrollView) findViewById(R.id.myscroll_view); radioGroup = (RadioGroup) findViewById(R.id.radioGroup); for (int i = 0; i < ids.length; i++) { ImageView image = new ImageView(this); image.setBackgroundResource(ids[i]); msv.addView(image); }
msv.setPageChangedListener(new MyPageChangedListener() {
cxbiao/Android_Study_Demos
AndroidSwipeLayoutDemo/myswipedemo/src/main/java/bryan/com/myswipedemo/RecyclerViewExample.java
// Path: AndroidSwipeLayoutDemo/myswipedemo/src/main/java/bryan/com/myswipedemo/adapter/RecyclerViewAdapter.java // public class RecyclerViewAdapter extends RecyclerSwipeAdapter<RecyclerViewAdapter.MyViewHolder> { // // // // private Context context; // private List<String> mData; // // public RecyclerViewAdapter(Context context,List<String> data){ // this.context=context; // this.mData=data; // } // // @Override // public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // // View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_item, parent, false); // return new MyViewHolder(view); // } // // @Override // public void onBindViewHolder(final MyViewHolder viewHolder, final int position) { // viewHolder.contentTv.setText(mData.get(position)); // viewHolder.delBtn.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // //获得真实的下标位置 // int index = viewHolder.getLayoutPosition(); // Toast.makeText(context, "position:" + index, Toast.LENGTH_SHORT).show(); // mItemManger.removeShownLayouts(viewHolder.swipeLayout); // mData.remove(index); // notifyItemRemoved(index); // mItemManger.closeAllItems(); // } // }); // // //设置了些监听器不会触发itemview的click事件 // viewHolder.swipeLayout.getSurfaceView().setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // int index = viewHolder.getLayoutPosition(); // if( viewHolder.swipeLayout.getOpenStatus()==SwipeLayout.Status.Close){ // Toast.makeText(context, index+"clicked", Toast.LENGTH_SHORT).show(); // }else{ // viewHolder.swipeLayout.close(true); // } // } // }); // // // // mItemManger.bind(viewHolder.itemView, position); // } // // @Override // public int getItemCount() { // return mData.size(); // } // // @Override // public int getSwipeLayoutResourceId(int position) { // return R.id.swipelayout; // } // // public static class MyViewHolder extends RecyclerView.ViewHolder{ // // public ImageView delBtn; // public TextView contentTv; // public SwipeLayout swipeLayout; // public MyViewHolder(View itemView) { // super(itemView); // delBtn= (ImageView) itemView.findViewById(R.id.delete); // contentTv= (TextView) itemView.findViewById(R.id.content); // swipeLayout= (SwipeLayout) itemView.findViewById(R.id.swipelayout); // // // } // } // }
import android.app.Activity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import com.daimajia.swipe.util.Attributes; import java.util.ArrayList; import java.util.List; import bryan.com.myswipedemo.adapter.RecyclerViewAdapter;
package bryan.com.myswipedemo; /** * Created by Administrator on 2015/8/4. */ public class RecyclerViewExample extends Activity { RecyclerView recyclerView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.recyclerview_demo); recyclerView= (RecyclerView) findViewById(R.id.recyclerView); recyclerView.setLayoutManager(new LinearLayoutManager(this)); List<String> data=new ArrayList<String>(); for(int i=0;i<50;i++){ data.add("主体内容:"+i); }
// Path: AndroidSwipeLayoutDemo/myswipedemo/src/main/java/bryan/com/myswipedemo/adapter/RecyclerViewAdapter.java // public class RecyclerViewAdapter extends RecyclerSwipeAdapter<RecyclerViewAdapter.MyViewHolder> { // // // // private Context context; // private List<String> mData; // // public RecyclerViewAdapter(Context context,List<String> data){ // this.context=context; // this.mData=data; // } // // @Override // public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // // View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_item, parent, false); // return new MyViewHolder(view); // } // // @Override // public void onBindViewHolder(final MyViewHolder viewHolder, final int position) { // viewHolder.contentTv.setText(mData.get(position)); // viewHolder.delBtn.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // //获得真实的下标位置 // int index = viewHolder.getLayoutPosition(); // Toast.makeText(context, "position:" + index, Toast.LENGTH_SHORT).show(); // mItemManger.removeShownLayouts(viewHolder.swipeLayout); // mData.remove(index); // notifyItemRemoved(index); // mItemManger.closeAllItems(); // } // }); // // //设置了些监听器不会触发itemview的click事件 // viewHolder.swipeLayout.getSurfaceView().setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // int index = viewHolder.getLayoutPosition(); // if( viewHolder.swipeLayout.getOpenStatus()==SwipeLayout.Status.Close){ // Toast.makeText(context, index+"clicked", Toast.LENGTH_SHORT).show(); // }else{ // viewHolder.swipeLayout.close(true); // } // } // }); // // // // mItemManger.bind(viewHolder.itemView, position); // } // // @Override // public int getItemCount() { // return mData.size(); // } // // @Override // public int getSwipeLayoutResourceId(int position) { // return R.id.swipelayout; // } // // public static class MyViewHolder extends RecyclerView.ViewHolder{ // // public ImageView delBtn; // public TextView contentTv; // public SwipeLayout swipeLayout; // public MyViewHolder(View itemView) { // super(itemView); // delBtn= (ImageView) itemView.findViewById(R.id.delete); // contentTv= (TextView) itemView.findViewById(R.id.content); // swipeLayout= (SwipeLayout) itemView.findViewById(R.id.swipelayout); // // // } // } // } // Path: AndroidSwipeLayoutDemo/myswipedemo/src/main/java/bryan/com/myswipedemo/RecyclerViewExample.java import android.app.Activity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import com.daimajia.swipe.util.Attributes; import java.util.ArrayList; import java.util.List; import bryan.com.myswipedemo.adapter.RecyclerViewAdapter; package bryan.com.myswipedemo; /** * Created by Administrator on 2015/8/4. */ public class RecyclerViewExample extends Activity { RecyclerView recyclerView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.recyclerview_demo); recyclerView= (RecyclerView) findViewById(R.id.recyclerView); recyclerView.setLayoutManager(new LinearLayoutManager(this)); List<String> data=new ArrayList<String>(); for(int i=0;i<50;i++){ data.add("主体内容:"+i); }
RecyclerViewAdapter adapter=new RecyclerViewAdapter(this,data);
yhemanth/hadoop-training-samples
src/main/java/com/dsinpractice/samples/hadoop/mapred/merge/MergeJob.java
// Path: src/main/java/com/dsinpractice/samples/hadoop/mapred/generic/IdentityMapper.java // public class IdentityMapper extends Mapper<Object, Object, Object, Object> { // @Override // protected void map(Object key, Object value, Context context) throws IOException, InterruptedException { // context.write(key, value); // } // } // // Path: src/main/java/com/dsinpractice/samples/hadoop/mapred/generic/ValueOnlyReducer.java // public class ValueOnlyReducer extends Reducer<Object, Object, Object, Object> { // @Override // public void reduce(Object key, Iterable<Object> values, Context context) throws IOException, InterruptedException { // for (Object value : values) { // context.write(value, NullWritable.get()); // } // } // }
import com.dsinpractice.samples.hadoop.mapred.generic.IdentityMapper; import com.dsinpractice.samples.hadoop.mapred.generic.ValueOnlyReducer; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.fs.Path; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner;
package com.dsinpractice.samples.hadoop.mapred.merge; public class MergeJob extends Configured implements Tool { @Override public int run(String[] args) throws Exception { Job job = new Job(getConf()); job.setJarByClass(MergeJob.class);
// Path: src/main/java/com/dsinpractice/samples/hadoop/mapred/generic/IdentityMapper.java // public class IdentityMapper extends Mapper<Object, Object, Object, Object> { // @Override // protected void map(Object key, Object value, Context context) throws IOException, InterruptedException { // context.write(key, value); // } // } // // Path: src/main/java/com/dsinpractice/samples/hadoop/mapred/generic/ValueOnlyReducer.java // public class ValueOnlyReducer extends Reducer<Object, Object, Object, Object> { // @Override // public void reduce(Object key, Iterable<Object> values, Context context) throws IOException, InterruptedException { // for (Object value : values) { // context.write(value, NullWritable.get()); // } // } // } // Path: src/main/java/com/dsinpractice/samples/hadoop/mapred/merge/MergeJob.java import com.dsinpractice.samples.hadoop.mapred.generic.IdentityMapper; import com.dsinpractice.samples.hadoop.mapred.generic.ValueOnlyReducer; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.fs.Path; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; package com.dsinpractice.samples.hadoop.mapred.merge; public class MergeJob extends Configured implements Tool { @Override public int run(String[] args) throws Exception { Job job = new Job(getConf()); job.setJarByClass(MergeJob.class);
job.setMapperClass(IdentityMapper.class);
yhemanth/hadoop-training-samples
src/main/java/com/dsinpractice/samples/hadoop/mapred/merge/MergeJob.java
// Path: src/main/java/com/dsinpractice/samples/hadoop/mapred/generic/IdentityMapper.java // public class IdentityMapper extends Mapper<Object, Object, Object, Object> { // @Override // protected void map(Object key, Object value, Context context) throws IOException, InterruptedException { // context.write(key, value); // } // } // // Path: src/main/java/com/dsinpractice/samples/hadoop/mapred/generic/ValueOnlyReducer.java // public class ValueOnlyReducer extends Reducer<Object, Object, Object, Object> { // @Override // public void reduce(Object key, Iterable<Object> values, Context context) throws IOException, InterruptedException { // for (Object value : values) { // context.write(value, NullWritable.get()); // } // } // }
import com.dsinpractice.samples.hadoop.mapred.generic.IdentityMapper; import com.dsinpractice.samples.hadoop.mapred.generic.ValueOnlyReducer; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.fs.Path; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner;
package com.dsinpractice.samples.hadoop.mapred.merge; public class MergeJob extends Configured implements Tool { @Override public int run(String[] args) throws Exception { Job job = new Job(getConf()); job.setJarByClass(MergeJob.class); job.setMapperClass(IdentityMapper.class);
// Path: src/main/java/com/dsinpractice/samples/hadoop/mapred/generic/IdentityMapper.java // public class IdentityMapper extends Mapper<Object, Object, Object, Object> { // @Override // protected void map(Object key, Object value, Context context) throws IOException, InterruptedException { // context.write(key, value); // } // } // // Path: src/main/java/com/dsinpractice/samples/hadoop/mapred/generic/ValueOnlyReducer.java // public class ValueOnlyReducer extends Reducer<Object, Object, Object, Object> { // @Override // public void reduce(Object key, Iterable<Object> values, Context context) throws IOException, InterruptedException { // for (Object value : values) { // context.write(value, NullWritable.get()); // } // } // } // Path: src/main/java/com/dsinpractice/samples/hadoop/mapred/merge/MergeJob.java import com.dsinpractice.samples.hadoop.mapred.generic.IdentityMapper; import com.dsinpractice.samples.hadoop.mapred.generic.ValueOnlyReducer; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.fs.Path; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; package com.dsinpractice.samples.hadoop.mapred.merge; public class MergeJob extends Configured implements Tool { @Override public int run(String[] args) throws Exception { Job job = new Job(getConf()); job.setJarByClass(MergeJob.class); job.setMapperClass(IdentityMapper.class);
job.setReducerClass(ValueOnlyReducer.class);
yhemanth/hadoop-training-samples
src/main/java/com/dsinpractice/samples/hadoop/mapred/logparsing/LogParsingJob.java
// Path: src/main/java/com/dsinpractice/samples/hadoop/domain/HttpRequest.java // public class HttpRequest implements WritableComparable { // private String httpMethod; // private String url; // // public HttpRequest(String httpMethod, String url) { // this.httpMethod = httpMethod; // this.url = url; // } // // public HttpRequest() { // // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // HttpRequest that = (HttpRequest) o; // // if (!httpMethod.equals(that.httpMethod)) return false; // if (!url.equals(that.url)) return false; // // return true; // } // // @Override // public int hashCode() { // int result = httpMethod.hashCode(); // result = 31 * result + url.hashCode(); // return result; // } // // @Override // public void write(DataOutput dataOutput) throws IOException { // dataOutput.writeUTF(httpMethod); // dataOutput.writeUTF(url); // } // // @Override // public void readFields(DataInput dataInput) throws IOException { // httpMethod = dataInput.readUTF(); // url = dataInput.readUTF(); // } // // @Override // public String toString() { // return String.format("%s,%s", httpMethod,url); // } // // @Override // public int compareTo(Object o) { // if (equals(o)) return 0; // if ((o==null) || (o.getClass() != getClass())) return 1; // HttpRequest otherRequest = (HttpRequest) o; // if (url.equals(otherRequest.url)) { // return httpMethod.compareTo(otherRequest.httpMethod); // } else { // return url.compareTo(otherRequest.url); // } // } // } // // Path: src/main/java/com/dsinpractice/samples/hadoop/domain/LogEntry.java // public class LogEntry implements Writable { // // private String date; // private String time; // private HttpRequest request; // // public String getDate() { // return date; // } // // public String getTime() { // return time; // } // // public HttpRequest getRequest() { // return request; // } // // public LogEntry() { // // } // // public LogEntry(String date, String time, HttpRequest request) { // this.date = date; // this.time = time; // this.request = request; // } // // @Override // public void write(DataOutput dataOutput) throws IOException { // dataOutput.writeUTF(date); // dataOutput.writeUTF(time); // request.write(dataOutput); // } // // @Override // public void readFields(DataInput dataInput) throws IOException { // date = dataInput.readUTF(); // time = dataInput.readUTF(); // request = new HttpRequest(); // request.readFields(dataInput); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // LogEntry logEntry = (LogEntry) o; // // if (!date.equals(logEntry.date)) return false; // if (!request.equals(logEntry.request)) return false; // if (!time.equals(logEntry.time)) return false; // // return true; // } // // @Override // public int hashCode() { // int result = date.hashCode(); // result = 31 * result + time.hashCode(); // result = 31 * result + request.hashCode(); // return result; // } // // @Override // public String toString() { // return String.format("%s,%s,%s", date, time, request.toString()); // } // // }
import com.dsinpractice.samples.hadoop.domain.HttpRequest; import com.dsinpractice.samples.hadoop.domain.LogEntry; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner;
package com.dsinpractice.samples.hadoop.mapred.logparsing; public class LogParsingJob extends Configured implements Tool { @Override public int run(String[] args) throws Exception { Configuration conf = getConf(); Job logParsingJob = new Job(conf, "Log Parsing Job"); logParsingJob.setJarByClass(LogParsingJob.class); logParsingJob.setMapperClass(LogParsingMapper.class); FileInputFormat.setInputPaths(logParsingJob, args[0]);
// Path: src/main/java/com/dsinpractice/samples/hadoop/domain/HttpRequest.java // public class HttpRequest implements WritableComparable { // private String httpMethod; // private String url; // // public HttpRequest(String httpMethod, String url) { // this.httpMethod = httpMethod; // this.url = url; // } // // public HttpRequest() { // // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // HttpRequest that = (HttpRequest) o; // // if (!httpMethod.equals(that.httpMethod)) return false; // if (!url.equals(that.url)) return false; // // return true; // } // // @Override // public int hashCode() { // int result = httpMethod.hashCode(); // result = 31 * result + url.hashCode(); // return result; // } // // @Override // public void write(DataOutput dataOutput) throws IOException { // dataOutput.writeUTF(httpMethod); // dataOutput.writeUTF(url); // } // // @Override // public void readFields(DataInput dataInput) throws IOException { // httpMethod = dataInput.readUTF(); // url = dataInput.readUTF(); // } // // @Override // public String toString() { // return String.format("%s,%s", httpMethod,url); // } // // @Override // public int compareTo(Object o) { // if (equals(o)) return 0; // if ((o==null) || (o.getClass() != getClass())) return 1; // HttpRequest otherRequest = (HttpRequest) o; // if (url.equals(otherRequest.url)) { // return httpMethod.compareTo(otherRequest.httpMethod); // } else { // return url.compareTo(otherRequest.url); // } // } // } // // Path: src/main/java/com/dsinpractice/samples/hadoop/domain/LogEntry.java // public class LogEntry implements Writable { // // private String date; // private String time; // private HttpRequest request; // // public String getDate() { // return date; // } // // public String getTime() { // return time; // } // // public HttpRequest getRequest() { // return request; // } // // public LogEntry() { // // } // // public LogEntry(String date, String time, HttpRequest request) { // this.date = date; // this.time = time; // this.request = request; // } // // @Override // public void write(DataOutput dataOutput) throws IOException { // dataOutput.writeUTF(date); // dataOutput.writeUTF(time); // request.write(dataOutput); // } // // @Override // public void readFields(DataInput dataInput) throws IOException { // date = dataInput.readUTF(); // time = dataInput.readUTF(); // request = new HttpRequest(); // request.readFields(dataInput); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // LogEntry logEntry = (LogEntry) o; // // if (!date.equals(logEntry.date)) return false; // if (!request.equals(logEntry.request)) return false; // if (!time.equals(logEntry.time)) return false; // // return true; // } // // @Override // public int hashCode() { // int result = date.hashCode(); // result = 31 * result + time.hashCode(); // result = 31 * result + request.hashCode(); // return result; // } // // @Override // public String toString() { // return String.format("%s,%s,%s", date, time, request.toString()); // } // // } // Path: src/main/java/com/dsinpractice/samples/hadoop/mapred/logparsing/LogParsingJob.java import com.dsinpractice.samples.hadoop.domain.HttpRequest; import com.dsinpractice.samples.hadoop.domain.LogEntry; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; package com.dsinpractice.samples.hadoop.mapred.logparsing; public class LogParsingJob extends Configured implements Tool { @Override public int run(String[] args) throws Exception { Configuration conf = getConf(); Job logParsingJob = new Job(conf, "Log Parsing Job"); logParsingJob.setJarByClass(LogParsingJob.class); logParsingJob.setMapperClass(LogParsingMapper.class); FileInputFormat.setInputPaths(logParsingJob, args[0]);
logParsingJob.setMapOutputKeyClass(HttpRequest.class);
yhemanth/hadoop-training-samples
src/main/java/com/dsinpractice/samples/hadoop/mapred/logparsing/LogParsingJob.java
// Path: src/main/java/com/dsinpractice/samples/hadoop/domain/HttpRequest.java // public class HttpRequest implements WritableComparable { // private String httpMethod; // private String url; // // public HttpRequest(String httpMethod, String url) { // this.httpMethod = httpMethod; // this.url = url; // } // // public HttpRequest() { // // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // HttpRequest that = (HttpRequest) o; // // if (!httpMethod.equals(that.httpMethod)) return false; // if (!url.equals(that.url)) return false; // // return true; // } // // @Override // public int hashCode() { // int result = httpMethod.hashCode(); // result = 31 * result + url.hashCode(); // return result; // } // // @Override // public void write(DataOutput dataOutput) throws IOException { // dataOutput.writeUTF(httpMethod); // dataOutput.writeUTF(url); // } // // @Override // public void readFields(DataInput dataInput) throws IOException { // httpMethod = dataInput.readUTF(); // url = dataInput.readUTF(); // } // // @Override // public String toString() { // return String.format("%s,%s", httpMethod,url); // } // // @Override // public int compareTo(Object o) { // if (equals(o)) return 0; // if ((o==null) || (o.getClass() != getClass())) return 1; // HttpRequest otherRequest = (HttpRequest) o; // if (url.equals(otherRequest.url)) { // return httpMethod.compareTo(otherRequest.httpMethod); // } else { // return url.compareTo(otherRequest.url); // } // } // } // // Path: src/main/java/com/dsinpractice/samples/hadoop/domain/LogEntry.java // public class LogEntry implements Writable { // // private String date; // private String time; // private HttpRequest request; // // public String getDate() { // return date; // } // // public String getTime() { // return time; // } // // public HttpRequest getRequest() { // return request; // } // // public LogEntry() { // // } // // public LogEntry(String date, String time, HttpRequest request) { // this.date = date; // this.time = time; // this.request = request; // } // // @Override // public void write(DataOutput dataOutput) throws IOException { // dataOutput.writeUTF(date); // dataOutput.writeUTF(time); // request.write(dataOutput); // } // // @Override // public void readFields(DataInput dataInput) throws IOException { // date = dataInput.readUTF(); // time = dataInput.readUTF(); // request = new HttpRequest(); // request.readFields(dataInput); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // LogEntry logEntry = (LogEntry) o; // // if (!date.equals(logEntry.date)) return false; // if (!request.equals(logEntry.request)) return false; // if (!time.equals(logEntry.time)) return false; // // return true; // } // // @Override // public int hashCode() { // int result = date.hashCode(); // result = 31 * result + time.hashCode(); // result = 31 * result + request.hashCode(); // return result; // } // // @Override // public String toString() { // return String.format("%s,%s,%s", date, time, request.toString()); // } // // }
import com.dsinpractice.samples.hadoop.domain.HttpRequest; import com.dsinpractice.samples.hadoop.domain.LogEntry; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner;
package com.dsinpractice.samples.hadoop.mapred.logparsing; public class LogParsingJob extends Configured implements Tool { @Override public int run(String[] args) throws Exception { Configuration conf = getConf(); Job logParsingJob = new Job(conf, "Log Parsing Job"); logParsingJob.setJarByClass(LogParsingJob.class); logParsingJob.setMapperClass(LogParsingMapper.class); FileInputFormat.setInputPaths(logParsingJob, args[0]); logParsingJob.setMapOutputKeyClass(HttpRequest.class);
// Path: src/main/java/com/dsinpractice/samples/hadoop/domain/HttpRequest.java // public class HttpRequest implements WritableComparable { // private String httpMethod; // private String url; // // public HttpRequest(String httpMethod, String url) { // this.httpMethod = httpMethod; // this.url = url; // } // // public HttpRequest() { // // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // HttpRequest that = (HttpRequest) o; // // if (!httpMethod.equals(that.httpMethod)) return false; // if (!url.equals(that.url)) return false; // // return true; // } // // @Override // public int hashCode() { // int result = httpMethod.hashCode(); // result = 31 * result + url.hashCode(); // return result; // } // // @Override // public void write(DataOutput dataOutput) throws IOException { // dataOutput.writeUTF(httpMethod); // dataOutput.writeUTF(url); // } // // @Override // public void readFields(DataInput dataInput) throws IOException { // httpMethod = dataInput.readUTF(); // url = dataInput.readUTF(); // } // // @Override // public String toString() { // return String.format("%s,%s", httpMethod,url); // } // // @Override // public int compareTo(Object o) { // if (equals(o)) return 0; // if ((o==null) || (o.getClass() != getClass())) return 1; // HttpRequest otherRequest = (HttpRequest) o; // if (url.equals(otherRequest.url)) { // return httpMethod.compareTo(otherRequest.httpMethod); // } else { // return url.compareTo(otherRequest.url); // } // } // } // // Path: src/main/java/com/dsinpractice/samples/hadoop/domain/LogEntry.java // public class LogEntry implements Writable { // // private String date; // private String time; // private HttpRequest request; // // public String getDate() { // return date; // } // // public String getTime() { // return time; // } // // public HttpRequest getRequest() { // return request; // } // // public LogEntry() { // // } // // public LogEntry(String date, String time, HttpRequest request) { // this.date = date; // this.time = time; // this.request = request; // } // // @Override // public void write(DataOutput dataOutput) throws IOException { // dataOutput.writeUTF(date); // dataOutput.writeUTF(time); // request.write(dataOutput); // } // // @Override // public void readFields(DataInput dataInput) throws IOException { // date = dataInput.readUTF(); // time = dataInput.readUTF(); // request = new HttpRequest(); // request.readFields(dataInput); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // LogEntry logEntry = (LogEntry) o; // // if (!date.equals(logEntry.date)) return false; // if (!request.equals(logEntry.request)) return false; // if (!time.equals(logEntry.time)) return false; // // return true; // } // // @Override // public int hashCode() { // int result = date.hashCode(); // result = 31 * result + time.hashCode(); // result = 31 * result + request.hashCode(); // return result; // } // // @Override // public String toString() { // return String.format("%s,%s,%s", date, time, request.toString()); // } // // } // Path: src/main/java/com/dsinpractice/samples/hadoop/mapred/logparsing/LogParsingJob.java import com.dsinpractice.samples.hadoop.domain.HttpRequest; import com.dsinpractice.samples.hadoop.domain.LogEntry; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; package com.dsinpractice.samples.hadoop.mapred.logparsing; public class LogParsingJob extends Configured implements Tool { @Override public int run(String[] args) throws Exception { Configuration conf = getConf(); Job logParsingJob = new Job(conf, "Log Parsing Job"); logParsingJob.setJarByClass(LogParsingJob.class); logParsingJob.setMapperClass(LogParsingMapper.class); FileInputFormat.setInputPaths(logParsingJob, args[0]); logParsingJob.setMapOutputKeyClass(HttpRequest.class);
logParsingJob.setMapOutputValueClass(LogEntry.class);
yhemanth/hadoop-training-samples
src/test/java/com/dsinpractice/samples/hadoop/mapred/logparsing/LogParsingMapperTest.java
// Path: src/main/java/com/dsinpractice/samples/hadoop/domain/HttpRequest.java // public class HttpRequest implements WritableComparable { // private String httpMethod; // private String url; // // public HttpRequest(String httpMethod, String url) { // this.httpMethod = httpMethod; // this.url = url; // } // // public HttpRequest() { // // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // HttpRequest that = (HttpRequest) o; // // if (!httpMethod.equals(that.httpMethod)) return false; // if (!url.equals(that.url)) return false; // // return true; // } // // @Override // public int hashCode() { // int result = httpMethod.hashCode(); // result = 31 * result + url.hashCode(); // return result; // } // // @Override // public void write(DataOutput dataOutput) throws IOException { // dataOutput.writeUTF(httpMethod); // dataOutput.writeUTF(url); // } // // @Override // public void readFields(DataInput dataInput) throws IOException { // httpMethod = dataInput.readUTF(); // url = dataInput.readUTF(); // } // // @Override // public String toString() { // return String.format("%s,%s", httpMethod,url); // } // // @Override // public int compareTo(Object o) { // if (equals(o)) return 0; // if ((o==null) || (o.getClass() != getClass())) return 1; // HttpRequest otherRequest = (HttpRequest) o; // if (url.equals(otherRequest.url)) { // return httpMethod.compareTo(otherRequest.httpMethod); // } else { // return url.compareTo(otherRequest.url); // } // } // } // // Path: src/main/java/com/dsinpractice/samples/hadoop/domain/LogEntry.java // public class LogEntry implements Writable { // // private String date; // private String time; // private HttpRequest request; // // public String getDate() { // return date; // } // // public String getTime() { // return time; // } // // public HttpRequest getRequest() { // return request; // } // // public LogEntry() { // // } // // public LogEntry(String date, String time, HttpRequest request) { // this.date = date; // this.time = time; // this.request = request; // } // // @Override // public void write(DataOutput dataOutput) throws IOException { // dataOutput.writeUTF(date); // dataOutput.writeUTF(time); // request.write(dataOutput); // } // // @Override // public void readFields(DataInput dataInput) throws IOException { // date = dataInput.readUTF(); // time = dataInput.readUTF(); // request = new HttpRequest(); // request.readFields(dataInput); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // LogEntry logEntry = (LogEntry) o; // // if (!date.equals(logEntry.date)) return false; // if (!request.equals(logEntry.request)) return false; // if (!time.equals(logEntry.time)) return false; // // return true; // } // // @Override // public int hashCode() { // int result = date.hashCode(); // result = 31 * result + time.hashCode(); // result = 31 * result + request.hashCode(); // return result; // } // // @Override // public String toString() { // return String.format("%s,%s,%s", date, time, request.toString()); // } // // }
import com.dsinpractice.samples.hadoop.domain.HttpRequest; import com.dsinpractice.samples.hadoop.domain.LogEntry; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mrunit.mapreduce.MapDriver; import org.junit.Test;
package com.dsinpractice.samples.hadoop.mapred.logparsing; public class LogParsingMapperTest { @Test public void should_parse_log_line_into_map_record() { LogParsingMapper logParsingMapper = new LogParsingMapper();
// Path: src/main/java/com/dsinpractice/samples/hadoop/domain/HttpRequest.java // public class HttpRequest implements WritableComparable { // private String httpMethod; // private String url; // // public HttpRequest(String httpMethod, String url) { // this.httpMethod = httpMethod; // this.url = url; // } // // public HttpRequest() { // // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // HttpRequest that = (HttpRequest) o; // // if (!httpMethod.equals(that.httpMethod)) return false; // if (!url.equals(that.url)) return false; // // return true; // } // // @Override // public int hashCode() { // int result = httpMethod.hashCode(); // result = 31 * result + url.hashCode(); // return result; // } // // @Override // public void write(DataOutput dataOutput) throws IOException { // dataOutput.writeUTF(httpMethod); // dataOutput.writeUTF(url); // } // // @Override // public void readFields(DataInput dataInput) throws IOException { // httpMethod = dataInput.readUTF(); // url = dataInput.readUTF(); // } // // @Override // public String toString() { // return String.format("%s,%s", httpMethod,url); // } // // @Override // public int compareTo(Object o) { // if (equals(o)) return 0; // if ((o==null) || (o.getClass() != getClass())) return 1; // HttpRequest otherRequest = (HttpRequest) o; // if (url.equals(otherRequest.url)) { // return httpMethod.compareTo(otherRequest.httpMethod); // } else { // return url.compareTo(otherRequest.url); // } // } // } // // Path: src/main/java/com/dsinpractice/samples/hadoop/domain/LogEntry.java // public class LogEntry implements Writable { // // private String date; // private String time; // private HttpRequest request; // // public String getDate() { // return date; // } // // public String getTime() { // return time; // } // // public HttpRequest getRequest() { // return request; // } // // public LogEntry() { // // } // // public LogEntry(String date, String time, HttpRequest request) { // this.date = date; // this.time = time; // this.request = request; // } // // @Override // public void write(DataOutput dataOutput) throws IOException { // dataOutput.writeUTF(date); // dataOutput.writeUTF(time); // request.write(dataOutput); // } // // @Override // public void readFields(DataInput dataInput) throws IOException { // date = dataInput.readUTF(); // time = dataInput.readUTF(); // request = new HttpRequest(); // request.readFields(dataInput); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // LogEntry logEntry = (LogEntry) o; // // if (!date.equals(logEntry.date)) return false; // if (!request.equals(logEntry.request)) return false; // if (!time.equals(logEntry.time)) return false; // // return true; // } // // @Override // public int hashCode() { // int result = date.hashCode(); // result = 31 * result + time.hashCode(); // result = 31 * result + request.hashCode(); // return result; // } // // @Override // public String toString() { // return String.format("%s,%s,%s", date, time, request.toString()); // } // // } // Path: src/test/java/com/dsinpractice/samples/hadoop/mapred/logparsing/LogParsingMapperTest.java import com.dsinpractice.samples.hadoop.domain.HttpRequest; import com.dsinpractice.samples.hadoop.domain.LogEntry; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mrunit.mapreduce.MapDriver; import org.junit.Test; package com.dsinpractice.samples.hadoop.mapred.logparsing; public class LogParsingMapperTest { @Test public void should_parse_log_line_into_map_record() { LogParsingMapper logParsingMapper = new LogParsingMapper();
MapDriver<Object, Text, HttpRequest, LogEntry> mapDriver
yhemanth/hadoop-training-samples
src/test/java/com/dsinpractice/samples/hadoop/mapred/logparsing/LogParsingMapperTest.java
// Path: src/main/java/com/dsinpractice/samples/hadoop/domain/HttpRequest.java // public class HttpRequest implements WritableComparable { // private String httpMethod; // private String url; // // public HttpRequest(String httpMethod, String url) { // this.httpMethod = httpMethod; // this.url = url; // } // // public HttpRequest() { // // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // HttpRequest that = (HttpRequest) o; // // if (!httpMethod.equals(that.httpMethod)) return false; // if (!url.equals(that.url)) return false; // // return true; // } // // @Override // public int hashCode() { // int result = httpMethod.hashCode(); // result = 31 * result + url.hashCode(); // return result; // } // // @Override // public void write(DataOutput dataOutput) throws IOException { // dataOutput.writeUTF(httpMethod); // dataOutput.writeUTF(url); // } // // @Override // public void readFields(DataInput dataInput) throws IOException { // httpMethod = dataInput.readUTF(); // url = dataInput.readUTF(); // } // // @Override // public String toString() { // return String.format("%s,%s", httpMethod,url); // } // // @Override // public int compareTo(Object o) { // if (equals(o)) return 0; // if ((o==null) || (o.getClass() != getClass())) return 1; // HttpRequest otherRequest = (HttpRequest) o; // if (url.equals(otherRequest.url)) { // return httpMethod.compareTo(otherRequest.httpMethod); // } else { // return url.compareTo(otherRequest.url); // } // } // } // // Path: src/main/java/com/dsinpractice/samples/hadoop/domain/LogEntry.java // public class LogEntry implements Writable { // // private String date; // private String time; // private HttpRequest request; // // public String getDate() { // return date; // } // // public String getTime() { // return time; // } // // public HttpRequest getRequest() { // return request; // } // // public LogEntry() { // // } // // public LogEntry(String date, String time, HttpRequest request) { // this.date = date; // this.time = time; // this.request = request; // } // // @Override // public void write(DataOutput dataOutput) throws IOException { // dataOutput.writeUTF(date); // dataOutput.writeUTF(time); // request.write(dataOutput); // } // // @Override // public void readFields(DataInput dataInput) throws IOException { // date = dataInput.readUTF(); // time = dataInput.readUTF(); // request = new HttpRequest(); // request.readFields(dataInput); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // LogEntry logEntry = (LogEntry) o; // // if (!date.equals(logEntry.date)) return false; // if (!request.equals(logEntry.request)) return false; // if (!time.equals(logEntry.time)) return false; // // return true; // } // // @Override // public int hashCode() { // int result = date.hashCode(); // result = 31 * result + time.hashCode(); // result = 31 * result + request.hashCode(); // return result; // } // // @Override // public String toString() { // return String.format("%s,%s,%s", date, time, request.toString()); // } // // }
import com.dsinpractice.samples.hadoop.domain.HttpRequest; import com.dsinpractice.samples.hadoop.domain.LogEntry; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mrunit.mapreduce.MapDriver; import org.junit.Test;
package com.dsinpractice.samples.hadoop.mapred.logparsing; public class LogParsingMapperTest { @Test public void should_parse_log_line_into_map_record() { LogParsingMapper logParsingMapper = new LogParsingMapper();
// Path: src/main/java/com/dsinpractice/samples/hadoop/domain/HttpRequest.java // public class HttpRequest implements WritableComparable { // private String httpMethod; // private String url; // // public HttpRequest(String httpMethod, String url) { // this.httpMethod = httpMethod; // this.url = url; // } // // public HttpRequest() { // // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // HttpRequest that = (HttpRequest) o; // // if (!httpMethod.equals(that.httpMethod)) return false; // if (!url.equals(that.url)) return false; // // return true; // } // // @Override // public int hashCode() { // int result = httpMethod.hashCode(); // result = 31 * result + url.hashCode(); // return result; // } // // @Override // public void write(DataOutput dataOutput) throws IOException { // dataOutput.writeUTF(httpMethod); // dataOutput.writeUTF(url); // } // // @Override // public void readFields(DataInput dataInput) throws IOException { // httpMethod = dataInput.readUTF(); // url = dataInput.readUTF(); // } // // @Override // public String toString() { // return String.format("%s,%s", httpMethod,url); // } // // @Override // public int compareTo(Object o) { // if (equals(o)) return 0; // if ((o==null) || (o.getClass() != getClass())) return 1; // HttpRequest otherRequest = (HttpRequest) o; // if (url.equals(otherRequest.url)) { // return httpMethod.compareTo(otherRequest.httpMethod); // } else { // return url.compareTo(otherRequest.url); // } // } // } // // Path: src/main/java/com/dsinpractice/samples/hadoop/domain/LogEntry.java // public class LogEntry implements Writable { // // private String date; // private String time; // private HttpRequest request; // // public String getDate() { // return date; // } // // public String getTime() { // return time; // } // // public HttpRequest getRequest() { // return request; // } // // public LogEntry() { // // } // // public LogEntry(String date, String time, HttpRequest request) { // this.date = date; // this.time = time; // this.request = request; // } // // @Override // public void write(DataOutput dataOutput) throws IOException { // dataOutput.writeUTF(date); // dataOutput.writeUTF(time); // request.write(dataOutput); // } // // @Override // public void readFields(DataInput dataInput) throws IOException { // date = dataInput.readUTF(); // time = dataInput.readUTF(); // request = new HttpRequest(); // request.readFields(dataInput); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // LogEntry logEntry = (LogEntry) o; // // if (!date.equals(logEntry.date)) return false; // if (!request.equals(logEntry.request)) return false; // if (!time.equals(logEntry.time)) return false; // // return true; // } // // @Override // public int hashCode() { // int result = date.hashCode(); // result = 31 * result + time.hashCode(); // result = 31 * result + request.hashCode(); // return result; // } // // @Override // public String toString() { // return String.format("%s,%s,%s", date, time, request.toString()); // } // // } // Path: src/test/java/com/dsinpractice/samples/hadoop/mapred/logparsing/LogParsingMapperTest.java import com.dsinpractice.samples.hadoop.domain.HttpRequest; import com.dsinpractice.samples.hadoop.domain.LogEntry; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mrunit.mapreduce.MapDriver; import org.junit.Test; package com.dsinpractice.samples.hadoop.mapred.logparsing; public class LogParsingMapperTest { @Test public void should_parse_log_line_into_map_record() { LogParsingMapper logParsingMapper = new LogParsingMapper();
MapDriver<Object, Text, HttpRequest, LogEntry> mapDriver
yhemanth/hadoop-training-samples
src/test/java/com/dsinpractice/samples/hadoop/mapred/logparsing/LogParsingReducerTest.java
// Path: src/main/java/com/dsinpractice/samples/hadoop/domain/HttpRequest.java // public class HttpRequest implements WritableComparable { // private String httpMethod; // private String url; // // public HttpRequest(String httpMethod, String url) { // this.httpMethod = httpMethod; // this.url = url; // } // // public HttpRequest() { // // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // HttpRequest that = (HttpRequest) o; // // if (!httpMethod.equals(that.httpMethod)) return false; // if (!url.equals(that.url)) return false; // // return true; // } // // @Override // public int hashCode() { // int result = httpMethod.hashCode(); // result = 31 * result + url.hashCode(); // return result; // } // // @Override // public void write(DataOutput dataOutput) throws IOException { // dataOutput.writeUTF(httpMethod); // dataOutput.writeUTF(url); // } // // @Override // public void readFields(DataInput dataInput) throws IOException { // httpMethod = dataInput.readUTF(); // url = dataInput.readUTF(); // } // // @Override // public String toString() { // return String.format("%s,%s", httpMethod,url); // } // // @Override // public int compareTo(Object o) { // if (equals(o)) return 0; // if ((o==null) || (o.getClass() != getClass())) return 1; // HttpRequest otherRequest = (HttpRequest) o; // if (url.equals(otherRequest.url)) { // return httpMethod.compareTo(otherRequest.httpMethod); // } else { // return url.compareTo(otherRequest.url); // } // } // } // // Path: src/main/java/com/dsinpractice/samples/hadoop/domain/LogEntry.java // public class LogEntry implements Writable { // // private String date; // private String time; // private HttpRequest request; // // public String getDate() { // return date; // } // // public String getTime() { // return time; // } // // public HttpRequest getRequest() { // return request; // } // // public LogEntry() { // // } // // public LogEntry(String date, String time, HttpRequest request) { // this.date = date; // this.time = time; // this.request = request; // } // // @Override // public void write(DataOutput dataOutput) throws IOException { // dataOutput.writeUTF(date); // dataOutput.writeUTF(time); // request.write(dataOutput); // } // // @Override // public void readFields(DataInput dataInput) throws IOException { // date = dataInput.readUTF(); // time = dataInput.readUTF(); // request = new HttpRequest(); // request.readFields(dataInput); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // LogEntry logEntry = (LogEntry) o; // // if (!date.equals(logEntry.date)) return false; // if (!request.equals(logEntry.request)) return false; // if (!time.equals(logEntry.time)) return false; // // return true; // } // // @Override // public int hashCode() { // int result = date.hashCode(); // result = 31 * result + time.hashCode(); // result = 31 * result + request.hashCode(); // return result; // } // // @Override // public String toString() { // return String.format("%s,%s,%s", date, time, request.toString()); // } // // }
import com.dsinpractice.samples.hadoop.domain.HttpRequest; import com.dsinpractice.samples.hadoop.domain.LogEntry; import org.apache.hadoop.io.Text; import org.apache.hadoop.mrunit.mapreduce.ReduceDriver; import org.junit.Test; import java.util.ArrayList; import java.util.List;
package com.dsinpractice.samples.hadoop.mapred.logparsing; public class LogParsingReducerTest { @Test public void should_collect_request_times() { LogParsingReducer logParsingReducer = new LogParsingReducer();
// Path: src/main/java/com/dsinpractice/samples/hadoop/domain/HttpRequest.java // public class HttpRequest implements WritableComparable { // private String httpMethod; // private String url; // // public HttpRequest(String httpMethod, String url) { // this.httpMethod = httpMethod; // this.url = url; // } // // public HttpRequest() { // // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // HttpRequest that = (HttpRequest) o; // // if (!httpMethod.equals(that.httpMethod)) return false; // if (!url.equals(that.url)) return false; // // return true; // } // // @Override // public int hashCode() { // int result = httpMethod.hashCode(); // result = 31 * result + url.hashCode(); // return result; // } // // @Override // public void write(DataOutput dataOutput) throws IOException { // dataOutput.writeUTF(httpMethod); // dataOutput.writeUTF(url); // } // // @Override // public void readFields(DataInput dataInput) throws IOException { // httpMethod = dataInput.readUTF(); // url = dataInput.readUTF(); // } // // @Override // public String toString() { // return String.format("%s,%s", httpMethod,url); // } // // @Override // public int compareTo(Object o) { // if (equals(o)) return 0; // if ((o==null) || (o.getClass() != getClass())) return 1; // HttpRequest otherRequest = (HttpRequest) o; // if (url.equals(otherRequest.url)) { // return httpMethod.compareTo(otherRequest.httpMethod); // } else { // return url.compareTo(otherRequest.url); // } // } // } // // Path: src/main/java/com/dsinpractice/samples/hadoop/domain/LogEntry.java // public class LogEntry implements Writable { // // private String date; // private String time; // private HttpRequest request; // // public String getDate() { // return date; // } // // public String getTime() { // return time; // } // // public HttpRequest getRequest() { // return request; // } // // public LogEntry() { // // } // // public LogEntry(String date, String time, HttpRequest request) { // this.date = date; // this.time = time; // this.request = request; // } // // @Override // public void write(DataOutput dataOutput) throws IOException { // dataOutput.writeUTF(date); // dataOutput.writeUTF(time); // request.write(dataOutput); // } // // @Override // public void readFields(DataInput dataInput) throws IOException { // date = dataInput.readUTF(); // time = dataInput.readUTF(); // request = new HttpRequest(); // request.readFields(dataInput); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // LogEntry logEntry = (LogEntry) o; // // if (!date.equals(logEntry.date)) return false; // if (!request.equals(logEntry.request)) return false; // if (!time.equals(logEntry.time)) return false; // // return true; // } // // @Override // public int hashCode() { // int result = date.hashCode(); // result = 31 * result + time.hashCode(); // result = 31 * result + request.hashCode(); // return result; // } // // @Override // public String toString() { // return String.format("%s,%s,%s", date, time, request.toString()); // } // // } // Path: src/test/java/com/dsinpractice/samples/hadoop/mapred/logparsing/LogParsingReducerTest.java import com.dsinpractice.samples.hadoop.domain.HttpRequest; import com.dsinpractice.samples.hadoop.domain.LogEntry; import org.apache.hadoop.io.Text; import org.apache.hadoop.mrunit.mapreduce.ReduceDriver; import org.junit.Test; import java.util.ArrayList; import java.util.List; package com.dsinpractice.samples.hadoop.mapred.logparsing; public class LogParsingReducerTest { @Test public void should_collect_request_times() { LogParsingReducer logParsingReducer = new LogParsingReducer();
ReduceDriver<HttpRequest, LogEntry, HttpRequest, Text> logParsingReduceDriver