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
opentracing-contrib/java-spring-cloud
instrument-starters/opentracing-spring-cloud-rxjava-starter/src/test/java/io/opentracing/contrib/spring/cloud/rxjava/RxJavaTracingAutoConfigurationTest.java
// Path: instrument-starters/opentracing-spring-cloud-rxjava-starter/src/test/java/io/opentracing/contrib/spring/cloud/rxjava/RxJavaTracingAutoConfigurationTest.java // @Configuration // @EnableAutoConfiguration // public static class MockTracingConfiguration { // @Bean // public MockTracer tracer() { // return new MockTracer(); // } // } // // Path: instrument-starters/opentracing-spring-cloud-rxjava-starter/src/test/java/io/opentracing/contrib/spring/cloud/rxjava/RxJavaTracingAutoConfigurationTest.java // @RestController // public static class TestController { // // @Autowired // private MockTracer mockTracer; // // @RequestMapping(method = RequestMethod.GET, value = "/single") // public Single<Integer> single() { // return Observable.range(1, 10) // .subscribeOn(Schedulers.io()) // .observeOn(Schedulers.computation()) // .map(x -> { // // without enabled RxJava instrumentation active span will be null // assertNotNull(mockTracer.activeSpan()); // mockTracer.activeSpan().setTag("rx", "rx"); // return x * 2; // }).take(1).toSingle(); // } // }
import static org.awaitility.Awaitility.await; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import io.opentracing.contrib.spring.cloud.rxjava.RxJavaTracingAutoConfigurationTest.MockTracingConfiguration; import io.opentracing.contrib.spring.cloud.rxjava.RxJavaTracingAutoConfigurationTest.TestController; import io.opentracing.mock.MockSpan; import io.opentracing.mock.MockTracer; import java.util.List; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.ResponseEntity; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import rx.Observable; import rx.Single; import rx.schedulers.Schedulers;
/** * Copyright 2017-2018 The OpenTracing Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package io.opentracing.contrib.spring.cloud.rxjava; @SpringBootTest( webEnvironment = WebEnvironment.RANDOM_PORT,
// Path: instrument-starters/opentracing-spring-cloud-rxjava-starter/src/test/java/io/opentracing/contrib/spring/cloud/rxjava/RxJavaTracingAutoConfigurationTest.java // @Configuration // @EnableAutoConfiguration // public static class MockTracingConfiguration { // @Bean // public MockTracer tracer() { // return new MockTracer(); // } // } // // Path: instrument-starters/opentracing-spring-cloud-rxjava-starter/src/test/java/io/opentracing/contrib/spring/cloud/rxjava/RxJavaTracingAutoConfigurationTest.java // @RestController // public static class TestController { // // @Autowired // private MockTracer mockTracer; // // @RequestMapping(method = RequestMethod.GET, value = "/single") // public Single<Integer> single() { // return Observable.range(1, 10) // .subscribeOn(Schedulers.io()) // .observeOn(Schedulers.computation()) // .map(x -> { // // without enabled RxJava instrumentation active span will be null // assertNotNull(mockTracer.activeSpan()); // mockTracer.activeSpan().setTag("rx", "rx"); // return x * 2; // }).take(1).toSingle(); // } // } // Path: instrument-starters/opentracing-spring-cloud-rxjava-starter/src/test/java/io/opentracing/contrib/spring/cloud/rxjava/RxJavaTracingAutoConfigurationTest.java import static org.awaitility.Awaitility.await; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import io.opentracing.contrib.spring.cloud.rxjava.RxJavaTracingAutoConfigurationTest.MockTracingConfiguration; import io.opentracing.contrib.spring.cloud.rxjava.RxJavaTracingAutoConfigurationTest.TestController; import io.opentracing.mock.MockSpan; import io.opentracing.mock.MockTracer; import java.util.List; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.ResponseEntity; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import rx.Observable; import rx.Single; import rx.schedulers.Schedulers; /** * Copyright 2017-2018 The OpenTracing Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package io.opentracing.contrib.spring.cloud.rxjava; @SpringBootTest( webEnvironment = WebEnvironment.RANDOM_PORT,
classes = {MockTracingConfiguration.class, TestController.class},
opentracing-contrib/java-spring-cloud
instrument-starters/opentracing-spring-cloud-core/src/main/java/io/opentracing/contrib/spring/cloud/async/TraceAsyncAspect.java
// Path: instrument-starters/opentracing-spring-cloud-core/src/main/java/io/opentracing/contrib/spring/cloud/ExtensionTags.java // public class ExtensionTags { // // private ExtensionTags() { // } // // /** // * Tag for {@link Class#getSimpleName()} // */ // public static final StringTag CLASS_TAG = new StringTag("class"); // // /** // * Tag for method name // */ // public static final StringTag METHOD_TAG = new StringTag("method"); // } // // Path: instrument-starters/opentracing-spring-cloud-core/src/main/java/io/opentracing/contrib/spring/cloud/SpanUtils.java // public class SpanUtils { // // private SpanUtils() { // } // // /** // * Add appropriate error tags and logs to a span when an exception occurs // * // * @param span the span "monitoring" the code which threw the exception // * @param ex captured exception // */ // public static void captureException(Span span, Exception ex) { // Map<String, Object> exceptionLogs = new LinkedHashMap<>(2); // exceptionLogs.put("event", Tags.ERROR.getKey()); // exceptionLogs.put("error.object", ex); // span.log(exceptionLogs); // Tags.ERROR.set(span, true); // } // }
import io.opentracing.Scope; import io.opentracing.Span; import io.opentracing.Tracer; import io.opentracing.contrib.spring.cloud.ExtensionTags; import io.opentracing.contrib.spring.cloud.SpanUtils; import io.opentracing.tag.Tags; import java.lang.reflect.Method; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.reflect.MethodSignature; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.ReflectionUtils;
/** * Copyright 2017-2019 The OpenTracing Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package io.opentracing.contrib.spring.cloud.async; /** * @author kameshsampath */ @Aspect public class TraceAsyncAspect { static final String TAG_COMPONENT = "async"; @Autowired private Tracer tracer; public TraceAsyncAspect(Tracer tracer) { this.tracer = tracer; } @Around("execution (@org.springframework.scheduling.annotation.Async * *.*(..))") public Object traceBackgroundThread(final ProceedingJoinPoint pjp) throws Throwable { /** * We create a span because parent span might be missing. E.g. method is invoked */ Span span = this.tracer.buildSpan(operationName(pjp)) .withTag(Tags.COMPONENT.getKey(), TAG_COMPONENT)
// Path: instrument-starters/opentracing-spring-cloud-core/src/main/java/io/opentracing/contrib/spring/cloud/ExtensionTags.java // public class ExtensionTags { // // private ExtensionTags() { // } // // /** // * Tag for {@link Class#getSimpleName()} // */ // public static final StringTag CLASS_TAG = new StringTag("class"); // // /** // * Tag for method name // */ // public static final StringTag METHOD_TAG = new StringTag("method"); // } // // Path: instrument-starters/opentracing-spring-cloud-core/src/main/java/io/opentracing/contrib/spring/cloud/SpanUtils.java // public class SpanUtils { // // private SpanUtils() { // } // // /** // * Add appropriate error tags and logs to a span when an exception occurs // * // * @param span the span "monitoring" the code which threw the exception // * @param ex captured exception // */ // public static void captureException(Span span, Exception ex) { // Map<String, Object> exceptionLogs = new LinkedHashMap<>(2); // exceptionLogs.put("event", Tags.ERROR.getKey()); // exceptionLogs.put("error.object", ex); // span.log(exceptionLogs); // Tags.ERROR.set(span, true); // } // } // Path: instrument-starters/opentracing-spring-cloud-core/src/main/java/io/opentracing/contrib/spring/cloud/async/TraceAsyncAspect.java import io.opentracing.Scope; import io.opentracing.Span; import io.opentracing.Tracer; import io.opentracing.contrib.spring.cloud.ExtensionTags; import io.opentracing.contrib.spring.cloud.SpanUtils; import io.opentracing.tag.Tags; import java.lang.reflect.Method; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.reflect.MethodSignature; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.ReflectionUtils; /** * Copyright 2017-2019 The OpenTracing Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package io.opentracing.contrib.spring.cloud.async; /** * @author kameshsampath */ @Aspect public class TraceAsyncAspect { static final String TAG_COMPONENT = "async"; @Autowired private Tracer tracer; public TraceAsyncAspect(Tracer tracer) { this.tracer = tracer; } @Around("execution (@org.springframework.scheduling.annotation.Async * *.*(..))") public Object traceBackgroundThread(final ProceedingJoinPoint pjp) throws Throwable { /** * We create a span because parent span might be missing. E.g. method is invoked */ Span span = this.tracer.buildSpan(operationName(pjp)) .withTag(Tags.COMPONENT.getKey(), TAG_COMPONENT)
.withTag(ExtensionTags.CLASS_TAG.getKey(), pjp.getTarget().getClass().getSimpleName())
opentracing-contrib/java-spring-cloud
instrument-starters/opentracing-spring-cloud-core/src/main/java/io/opentracing/contrib/spring/cloud/async/TraceAsyncAspect.java
// Path: instrument-starters/opentracing-spring-cloud-core/src/main/java/io/opentracing/contrib/spring/cloud/ExtensionTags.java // public class ExtensionTags { // // private ExtensionTags() { // } // // /** // * Tag for {@link Class#getSimpleName()} // */ // public static final StringTag CLASS_TAG = new StringTag("class"); // // /** // * Tag for method name // */ // public static final StringTag METHOD_TAG = new StringTag("method"); // } // // Path: instrument-starters/opentracing-spring-cloud-core/src/main/java/io/opentracing/contrib/spring/cloud/SpanUtils.java // public class SpanUtils { // // private SpanUtils() { // } // // /** // * Add appropriate error tags and logs to a span when an exception occurs // * // * @param span the span "monitoring" the code which threw the exception // * @param ex captured exception // */ // public static void captureException(Span span, Exception ex) { // Map<String, Object> exceptionLogs = new LinkedHashMap<>(2); // exceptionLogs.put("event", Tags.ERROR.getKey()); // exceptionLogs.put("error.object", ex); // span.log(exceptionLogs); // Tags.ERROR.set(span, true); // } // }
import io.opentracing.Scope; import io.opentracing.Span; import io.opentracing.Tracer; import io.opentracing.contrib.spring.cloud.ExtensionTags; import io.opentracing.contrib.spring.cloud.SpanUtils; import io.opentracing.tag.Tags; import java.lang.reflect.Method; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.reflect.MethodSignature; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.ReflectionUtils;
/** * Copyright 2017-2019 The OpenTracing Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package io.opentracing.contrib.spring.cloud.async; /** * @author kameshsampath */ @Aspect public class TraceAsyncAspect { static final String TAG_COMPONENT = "async"; @Autowired private Tracer tracer; public TraceAsyncAspect(Tracer tracer) { this.tracer = tracer; } @Around("execution (@org.springframework.scheduling.annotation.Async * *.*(..))") public Object traceBackgroundThread(final ProceedingJoinPoint pjp) throws Throwable { /** * We create a span because parent span might be missing. E.g. method is invoked */ Span span = this.tracer.buildSpan(operationName(pjp)) .withTag(Tags.COMPONENT.getKey(), TAG_COMPONENT) .withTag(ExtensionTags.CLASS_TAG.getKey(), pjp.getTarget().getClass().getSimpleName()) .withTag(ExtensionTags.METHOD_TAG.getKey(), pjp.getSignature().getName()) .start(); try (Scope scope = this.tracer.scopeManager().activate(span)) { return pjp.proceed(); } catch (Exception ex) {
// Path: instrument-starters/opentracing-spring-cloud-core/src/main/java/io/opentracing/contrib/spring/cloud/ExtensionTags.java // public class ExtensionTags { // // private ExtensionTags() { // } // // /** // * Tag for {@link Class#getSimpleName()} // */ // public static final StringTag CLASS_TAG = new StringTag("class"); // // /** // * Tag for method name // */ // public static final StringTag METHOD_TAG = new StringTag("method"); // } // // Path: instrument-starters/opentracing-spring-cloud-core/src/main/java/io/opentracing/contrib/spring/cloud/SpanUtils.java // public class SpanUtils { // // private SpanUtils() { // } // // /** // * Add appropriate error tags and logs to a span when an exception occurs // * // * @param span the span "monitoring" the code which threw the exception // * @param ex captured exception // */ // public static void captureException(Span span, Exception ex) { // Map<String, Object> exceptionLogs = new LinkedHashMap<>(2); // exceptionLogs.put("event", Tags.ERROR.getKey()); // exceptionLogs.put("error.object", ex); // span.log(exceptionLogs); // Tags.ERROR.set(span, true); // } // } // Path: instrument-starters/opentracing-spring-cloud-core/src/main/java/io/opentracing/contrib/spring/cloud/async/TraceAsyncAspect.java import io.opentracing.Scope; import io.opentracing.Span; import io.opentracing.Tracer; import io.opentracing.contrib.spring.cloud.ExtensionTags; import io.opentracing.contrib.spring.cloud.SpanUtils; import io.opentracing.tag.Tags; import java.lang.reflect.Method; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.reflect.MethodSignature; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.ReflectionUtils; /** * Copyright 2017-2019 The OpenTracing Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package io.opentracing.contrib.spring.cloud.async; /** * @author kameshsampath */ @Aspect public class TraceAsyncAspect { static final String TAG_COMPONENT = "async"; @Autowired private Tracer tracer; public TraceAsyncAspect(Tracer tracer) { this.tracer = tracer; } @Around("execution (@org.springframework.scheduling.annotation.Async * *.*(..))") public Object traceBackgroundThread(final ProceedingJoinPoint pjp) throws Throwable { /** * We create a span because parent span might be missing. E.g. method is invoked */ Span span = this.tracer.buildSpan(operationName(pjp)) .withTag(Tags.COMPONENT.getKey(), TAG_COMPONENT) .withTag(ExtensionTags.CLASS_TAG.getKey(), pjp.getTarget().getClass().getSimpleName()) .withTag(ExtensionTags.METHOD_TAG.getKey(), pjp.getSignature().getName()) .start(); try (Scope scope = this.tracer.scopeManager().activate(span)) { return pjp.proceed(); } catch (Exception ex) {
SpanUtils.captureException(span, ex);
opentracing-contrib/java-spring-cloud
instrument-starters/opentracing-spring-cloud-feign-starter/src/test/java/io/opentracing/contrib/spring/cloud/feign/FeignManualWithSpanDecoratorsTest.java
// Path: instrument-starters/opentracing-spring-cloud-feign-starter/src/test/java/io/opentracing/contrib/spring/cloud/feign/TestUtils.java // static void verifyWithSpanDecorators(MockTracer mockTracer) { // await().until(() -> mockTracer.finishedSpans().size() == 1); // List<MockSpan> mockSpans = mockTracer.finishedSpans(); // assertEquals(1, mockSpans.size()); // Map<String, Object> tags = mockSpans.get(0).tags(); // assertEquals(Tags.SPAN_KIND_CLIENT, tags.get(Tags.SPAN_KIND.getKey())); // assertEquals(MyFeignSpanDecorator.TAG_VALUE, tags.get(MyFeignSpanDecorator.TAG_NAME)); // assertEquals(AnotherFeignSpanDecorator.TAG_VALUE, tags.get(AnotherFeignSpanDecorator.TAG_NAME)); // } // // Path: instrument-starters/opentracing-spring-cloud-feign-starter/src/test/java/io/opentracing/contrib/spring/cloud/feign/FeignManualTest.java // @Configuration // static class ManualFeignConfiguration { // // @Autowired // public ManualFeignConfiguration(Client client) { // feignInterface = Feign.builder().client(client) // .target(FeignInterface.class, "http://localService"); // } // } // // Path: instrument-starters/opentracing-spring-cloud-feign-starter/src/test/java/io/opentracing/contrib/spring/cloud/feign/FeignTest.java // @Configuration // @EnableFeignClients // @RibbonClients(@RibbonClient(name = "localService", configuration = RibbonConfiguration.class)) // static class FeignRibbonLocalConfiguration { // // }
import static io.opentracing.contrib.spring.cloud.feign.TestUtils.verifyWithSpanDecorators; import io.opentracing.contrib.spring.cloud.feign.FeignManualTest.ManualFeignConfiguration; import io.opentracing.contrib.spring.cloud.feign.FeignTest.FeignRibbonLocalConfiguration; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/** * Copyright 2017-2019 The OpenTracing Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package io.opentracing.contrib.spring.cloud.feign; /** * @author Emerson Oliveira * @author Gilles Robert */ @SpringBootTest( webEnvironment = WebEnvironment.RANDOM_PORT, classes = {MockTracingConfiguration.class, TestController.class,
// Path: instrument-starters/opentracing-spring-cloud-feign-starter/src/test/java/io/opentracing/contrib/spring/cloud/feign/TestUtils.java // static void verifyWithSpanDecorators(MockTracer mockTracer) { // await().until(() -> mockTracer.finishedSpans().size() == 1); // List<MockSpan> mockSpans = mockTracer.finishedSpans(); // assertEquals(1, mockSpans.size()); // Map<String, Object> tags = mockSpans.get(0).tags(); // assertEquals(Tags.SPAN_KIND_CLIENT, tags.get(Tags.SPAN_KIND.getKey())); // assertEquals(MyFeignSpanDecorator.TAG_VALUE, tags.get(MyFeignSpanDecorator.TAG_NAME)); // assertEquals(AnotherFeignSpanDecorator.TAG_VALUE, tags.get(AnotherFeignSpanDecorator.TAG_NAME)); // } // // Path: instrument-starters/opentracing-spring-cloud-feign-starter/src/test/java/io/opentracing/contrib/spring/cloud/feign/FeignManualTest.java // @Configuration // static class ManualFeignConfiguration { // // @Autowired // public ManualFeignConfiguration(Client client) { // feignInterface = Feign.builder().client(client) // .target(FeignInterface.class, "http://localService"); // } // } // // Path: instrument-starters/opentracing-spring-cloud-feign-starter/src/test/java/io/opentracing/contrib/spring/cloud/feign/FeignTest.java // @Configuration // @EnableFeignClients // @RibbonClients(@RibbonClient(name = "localService", configuration = RibbonConfiguration.class)) // static class FeignRibbonLocalConfiguration { // // } // Path: instrument-starters/opentracing-spring-cloud-feign-starter/src/test/java/io/opentracing/contrib/spring/cloud/feign/FeignManualWithSpanDecoratorsTest.java import static io.opentracing.contrib.spring.cloud.feign.TestUtils.verifyWithSpanDecorators; import io.opentracing.contrib.spring.cloud.feign.FeignManualTest.ManualFeignConfiguration; import io.opentracing.contrib.spring.cloud.feign.FeignTest.FeignRibbonLocalConfiguration; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** * Copyright 2017-2019 The OpenTracing Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package io.opentracing.contrib.spring.cloud.feign; /** * @author Emerson Oliveira * @author Gilles Robert */ @SpringBootTest( webEnvironment = WebEnvironment.RANDOM_PORT, classes = {MockTracingConfiguration.class, TestController.class,
ManualFeignConfiguration.class, FeignRibbonLocalConfiguration.class,
opentracing-contrib/java-spring-cloud
instrument-starters/opentracing-spring-cloud-feign-starter/src/test/java/io/opentracing/contrib/spring/cloud/feign/FeignManualWithSpanDecoratorsTest.java
// Path: instrument-starters/opentracing-spring-cloud-feign-starter/src/test/java/io/opentracing/contrib/spring/cloud/feign/TestUtils.java // static void verifyWithSpanDecorators(MockTracer mockTracer) { // await().until(() -> mockTracer.finishedSpans().size() == 1); // List<MockSpan> mockSpans = mockTracer.finishedSpans(); // assertEquals(1, mockSpans.size()); // Map<String, Object> tags = mockSpans.get(0).tags(); // assertEquals(Tags.SPAN_KIND_CLIENT, tags.get(Tags.SPAN_KIND.getKey())); // assertEquals(MyFeignSpanDecorator.TAG_VALUE, tags.get(MyFeignSpanDecorator.TAG_NAME)); // assertEquals(AnotherFeignSpanDecorator.TAG_VALUE, tags.get(AnotherFeignSpanDecorator.TAG_NAME)); // } // // Path: instrument-starters/opentracing-spring-cloud-feign-starter/src/test/java/io/opentracing/contrib/spring/cloud/feign/FeignManualTest.java // @Configuration // static class ManualFeignConfiguration { // // @Autowired // public ManualFeignConfiguration(Client client) { // feignInterface = Feign.builder().client(client) // .target(FeignInterface.class, "http://localService"); // } // } // // Path: instrument-starters/opentracing-spring-cloud-feign-starter/src/test/java/io/opentracing/contrib/spring/cloud/feign/FeignTest.java // @Configuration // @EnableFeignClients // @RibbonClients(@RibbonClient(name = "localService", configuration = RibbonConfiguration.class)) // static class FeignRibbonLocalConfiguration { // // }
import static io.opentracing.contrib.spring.cloud.feign.TestUtils.verifyWithSpanDecorators; import io.opentracing.contrib.spring.cloud.feign.FeignManualTest.ManualFeignConfiguration; import io.opentracing.contrib.spring.cloud.feign.FeignTest.FeignRibbonLocalConfiguration; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/** * Copyright 2017-2019 The OpenTracing Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package io.opentracing.contrib.spring.cloud.feign; /** * @author Emerson Oliveira * @author Gilles Robert */ @SpringBootTest( webEnvironment = WebEnvironment.RANDOM_PORT, classes = {MockTracingConfiguration.class, TestController.class,
// Path: instrument-starters/opentracing-spring-cloud-feign-starter/src/test/java/io/opentracing/contrib/spring/cloud/feign/TestUtils.java // static void verifyWithSpanDecorators(MockTracer mockTracer) { // await().until(() -> mockTracer.finishedSpans().size() == 1); // List<MockSpan> mockSpans = mockTracer.finishedSpans(); // assertEquals(1, mockSpans.size()); // Map<String, Object> tags = mockSpans.get(0).tags(); // assertEquals(Tags.SPAN_KIND_CLIENT, tags.get(Tags.SPAN_KIND.getKey())); // assertEquals(MyFeignSpanDecorator.TAG_VALUE, tags.get(MyFeignSpanDecorator.TAG_NAME)); // assertEquals(AnotherFeignSpanDecorator.TAG_VALUE, tags.get(AnotherFeignSpanDecorator.TAG_NAME)); // } // // Path: instrument-starters/opentracing-spring-cloud-feign-starter/src/test/java/io/opentracing/contrib/spring/cloud/feign/FeignManualTest.java // @Configuration // static class ManualFeignConfiguration { // // @Autowired // public ManualFeignConfiguration(Client client) { // feignInterface = Feign.builder().client(client) // .target(FeignInterface.class, "http://localService"); // } // } // // Path: instrument-starters/opentracing-spring-cloud-feign-starter/src/test/java/io/opentracing/contrib/spring/cloud/feign/FeignTest.java // @Configuration // @EnableFeignClients // @RibbonClients(@RibbonClient(name = "localService", configuration = RibbonConfiguration.class)) // static class FeignRibbonLocalConfiguration { // // } // Path: instrument-starters/opentracing-spring-cloud-feign-starter/src/test/java/io/opentracing/contrib/spring/cloud/feign/FeignManualWithSpanDecoratorsTest.java import static io.opentracing.contrib.spring.cloud.feign.TestUtils.verifyWithSpanDecorators; import io.opentracing.contrib.spring.cloud.feign.FeignManualTest.ManualFeignConfiguration; import io.opentracing.contrib.spring.cloud.feign.FeignTest.FeignRibbonLocalConfiguration; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** * Copyright 2017-2019 The OpenTracing Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package io.opentracing.contrib.spring.cloud.feign; /** * @author Emerson Oliveira * @author Gilles Robert */ @SpringBootTest( webEnvironment = WebEnvironment.RANDOM_PORT, classes = {MockTracingConfiguration.class, TestController.class,
ManualFeignConfiguration.class, FeignRibbonLocalConfiguration.class,
opentracing-contrib/java-spring-cloud
instrument-starters/opentracing-spring-cloud-feign-starter/src/test/java/io/opentracing/contrib/spring/cloud/feign/FeignManualWithSpanDecoratorsTest.java
// Path: instrument-starters/opentracing-spring-cloud-feign-starter/src/test/java/io/opentracing/contrib/spring/cloud/feign/TestUtils.java // static void verifyWithSpanDecorators(MockTracer mockTracer) { // await().until(() -> mockTracer.finishedSpans().size() == 1); // List<MockSpan> mockSpans = mockTracer.finishedSpans(); // assertEquals(1, mockSpans.size()); // Map<String, Object> tags = mockSpans.get(0).tags(); // assertEquals(Tags.SPAN_KIND_CLIENT, tags.get(Tags.SPAN_KIND.getKey())); // assertEquals(MyFeignSpanDecorator.TAG_VALUE, tags.get(MyFeignSpanDecorator.TAG_NAME)); // assertEquals(AnotherFeignSpanDecorator.TAG_VALUE, tags.get(AnotherFeignSpanDecorator.TAG_NAME)); // } // // Path: instrument-starters/opentracing-spring-cloud-feign-starter/src/test/java/io/opentracing/contrib/spring/cloud/feign/FeignManualTest.java // @Configuration // static class ManualFeignConfiguration { // // @Autowired // public ManualFeignConfiguration(Client client) { // feignInterface = Feign.builder().client(client) // .target(FeignInterface.class, "http://localService"); // } // } // // Path: instrument-starters/opentracing-spring-cloud-feign-starter/src/test/java/io/opentracing/contrib/spring/cloud/feign/FeignTest.java // @Configuration // @EnableFeignClients // @RibbonClients(@RibbonClient(name = "localService", configuration = RibbonConfiguration.class)) // static class FeignRibbonLocalConfiguration { // // }
import static io.opentracing.contrib.spring.cloud.feign.TestUtils.verifyWithSpanDecorators; import io.opentracing.contrib.spring.cloud.feign.FeignManualTest.ManualFeignConfiguration; import io.opentracing.contrib.spring.cloud.feign.FeignTest.FeignRibbonLocalConfiguration; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/** * Copyright 2017-2019 The OpenTracing Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package io.opentracing.contrib.spring.cloud.feign; /** * @author Emerson Oliveira * @author Gilles Robert */ @SpringBootTest( webEnvironment = WebEnvironment.RANDOM_PORT, classes = {MockTracingConfiguration.class, TestController.class, ManualFeignConfiguration.class, FeignRibbonLocalConfiguration.class, FeignSpanDecoratorConfiguration.class}, properties = {"opentracing.spring.web.skipPattern=/notTraced"}) @RunWith(SpringJUnit4ClassRunner.class) public class FeignManualWithSpanDecoratorsTest extends FeignManualTest { @Override @Test public void testTracedRequestDefinedUrl() { feignInterface.hello();
// Path: instrument-starters/opentracing-spring-cloud-feign-starter/src/test/java/io/opentracing/contrib/spring/cloud/feign/TestUtils.java // static void verifyWithSpanDecorators(MockTracer mockTracer) { // await().until(() -> mockTracer.finishedSpans().size() == 1); // List<MockSpan> mockSpans = mockTracer.finishedSpans(); // assertEquals(1, mockSpans.size()); // Map<String, Object> tags = mockSpans.get(0).tags(); // assertEquals(Tags.SPAN_KIND_CLIENT, tags.get(Tags.SPAN_KIND.getKey())); // assertEquals(MyFeignSpanDecorator.TAG_VALUE, tags.get(MyFeignSpanDecorator.TAG_NAME)); // assertEquals(AnotherFeignSpanDecorator.TAG_VALUE, tags.get(AnotherFeignSpanDecorator.TAG_NAME)); // } // // Path: instrument-starters/opentracing-spring-cloud-feign-starter/src/test/java/io/opentracing/contrib/spring/cloud/feign/FeignManualTest.java // @Configuration // static class ManualFeignConfiguration { // // @Autowired // public ManualFeignConfiguration(Client client) { // feignInterface = Feign.builder().client(client) // .target(FeignInterface.class, "http://localService"); // } // } // // Path: instrument-starters/opentracing-spring-cloud-feign-starter/src/test/java/io/opentracing/contrib/spring/cloud/feign/FeignTest.java // @Configuration // @EnableFeignClients // @RibbonClients(@RibbonClient(name = "localService", configuration = RibbonConfiguration.class)) // static class FeignRibbonLocalConfiguration { // // } // Path: instrument-starters/opentracing-spring-cloud-feign-starter/src/test/java/io/opentracing/contrib/spring/cloud/feign/FeignManualWithSpanDecoratorsTest.java import static io.opentracing.contrib.spring.cloud.feign.TestUtils.verifyWithSpanDecorators; import io.opentracing.contrib.spring.cloud.feign.FeignManualTest.ManualFeignConfiguration; import io.opentracing.contrib.spring.cloud.feign.FeignTest.FeignRibbonLocalConfiguration; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** * Copyright 2017-2019 The OpenTracing Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package io.opentracing.contrib.spring.cloud.feign; /** * @author Emerson Oliveira * @author Gilles Robert */ @SpringBootTest( webEnvironment = WebEnvironment.RANDOM_PORT, classes = {MockTracingConfiguration.class, TestController.class, ManualFeignConfiguration.class, FeignRibbonLocalConfiguration.class, FeignSpanDecoratorConfiguration.class}, properties = {"opentracing.spring.web.skipPattern=/notTraced"}) @RunWith(SpringJUnit4ClassRunner.class) public class FeignManualWithSpanDecoratorsTest extends FeignManualTest { @Override @Test public void testTracedRequestDefinedUrl() { feignInterface.hello();
verifyWithSpanDecorators(mockTracer);
opentracing-contrib/java-spring-cloud
instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/async/AsyncAnnotationTest.java
// Path: instrument-starters/opentracing-spring-cloud-core/src/main/java/io/opentracing/contrib/spring/cloud/ExtensionTags.java // public class ExtensionTags { // // private ExtensionTags() { // } // // /** // * Tag for {@link Class#getSimpleName()} // */ // public static final StringTag CLASS_TAG = new StringTag("class"); // // /** // * Tag for method name // */ // public static final StringTag METHOD_TAG = new StringTag("method"); // } // // Path: instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/MockTracingConfiguration.java // @Configuration // @EnableAutoConfiguration // public class MockTracingConfiguration { // // @Bean // public MockTracer mockTracer() { // GlobalTracerTestUtil.resetGlobalTracer(); // return new MockTracer(); // } // // @Bean // public RestTemplate restTemplate(RestTemplateBuilder restTemplateBuilder) { // return restTemplateBuilder.build(); // } // // @Bean // public AsyncRestTemplate asyncRestTemplate() { // return new AsyncRestTemplate(); // } // // public static TestRestTemplate createNotTracedRestTemplate(int port) { // return new TestRestTemplate(new RestTemplateBuilder().rootUri("http://localhost:" + port)); // } // } // // Path: instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/TestUtils.java // public class TestUtils { // // /** // * Check if all spans have same traceId. // * // * @param spans the spans to check // */ // public static void assertSameTraceId(Collection<MockSpan> spans) { // if (!spans.isEmpty()) { // final long traceId = spans.iterator().next().context().traceId(); // for (MockSpan span : spans) { // Assert.assertEquals(traceId, span.context().traceId()); // } // } // } // }
import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import io.opentracing.Scope; import io.opentracing.Span; import io.opentracing.contrib.spring.cloud.ExtensionTags; import io.opentracing.contrib.spring.cloud.MockTracingConfiguration; import io.opentracing.contrib.spring.cloud.TestUtils; import io.opentracing.mock.MockSpan; import io.opentracing.mock.MockTracer; import io.opentracing.tag.Tags; import java.util.List; import java.util.concurrent.Future; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.Bean; import org.springframework.scheduling.annotation.Async; import org.springframework.scheduling.annotation.AsyncResult; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
} } @Autowired private MockTracer mockTracer; @Autowired private AsyncService asyncService; @Before public void before() { mockTracer.reset(); } @Test public void testAsyncTraceAndSpans() throws Exception { Span span = mockTracer.buildSpan("outer").start(); try (Scope scope = mockTracer.activateSpan(span)) { Future<String> fut = asyncService.fooAsync(); await().until(() -> fut.isDone()); assertThat(fut.get()).isNotNull(); } finally { span.finish(); } await().until(() -> mockTracer.finishedSpans().size() == 3); List<MockSpan> mockSpans = mockTracer.finishedSpans(); // parent span from test, span modelling @Async, span inside @Async assertEquals(3, mockSpans.size());
// Path: instrument-starters/opentracing-spring-cloud-core/src/main/java/io/opentracing/contrib/spring/cloud/ExtensionTags.java // public class ExtensionTags { // // private ExtensionTags() { // } // // /** // * Tag for {@link Class#getSimpleName()} // */ // public static final StringTag CLASS_TAG = new StringTag("class"); // // /** // * Tag for method name // */ // public static final StringTag METHOD_TAG = new StringTag("method"); // } // // Path: instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/MockTracingConfiguration.java // @Configuration // @EnableAutoConfiguration // public class MockTracingConfiguration { // // @Bean // public MockTracer mockTracer() { // GlobalTracerTestUtil.resetGlobalTracer(); // return new MockTracer(); // } // // @Bean // public RestTemplate restTemplate(RestTemplateBuilder restTemplateBuilder) { // return restTemplateBuilder.build(); // } // // @Bean // public AsyncRestTemplate asyncRestTemplate() { // return new AsyncRestTemplate(); // } // // public static TestRestTemplate createNotTracedRestTemplate(int port) { // return new TestRestTemplate(new RestTemplateBuilder().rootUri("http://localhost:" + port)); // } // } // // Path: instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/TestUtils.java // public class TestUtils { // // /** // * Check if all spans have same traceId. // * // * @param spans the spans to check // */ // public static void assertSameTraceId(Collection<MockSpan> spans) { // if (!spans.isEmpty()) { // final long traceId = spans.iterator().next().context().traceId(); // for (MockSpan span : spans) { // Assert.assertEquals(traceId, span.context().traceId()); // } // } // } // } // Path: instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/async/AsyncAnnotationTest.java import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import io.opentracing.Scope; import io.opentracing.Span; import io.opentracing.contrib.spring.cloud.ExtensionTags; import io.opentracing.contrib.spring.cloud.MockTracingConfiguration; import io.opentracing.contrib.spring.cloud.TestUtils; import io.opentracing.mock.MockSpan; import io.opentracing.mock.MockTracer; import io.opentracing.tag.Tags; import java.util.List; import java.util.concurrent.Future; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.Bean; import org.springframework.scheduling.annotation.Async; import org.springframework.scheduling.annotation.AsyncResult; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; } } @Autowired private MockTracer mockTracer; @Autowired private AsyncService asyncService; @Before public void before() { mockTracer.reset(); } @Test public void testAsyncTraceAndSpans() throws Exception { Span span = mockTracer.buildSpan("outer").start(); try (Scope scope = mockTracer.activateSpan(span)) { Future<String> fut = asyncService.fooAsync(); await().until(() -> fut.isDone()); assertThat(fut.get()).isNotNull(); } finally { span.finish(); } await().until(() -> mockTracer.finishedSpans().size() == 3); List<MockSpan> mockSpans = mockTracer.finishedSpans(); // parent span from test, span modelling @Async, span inside @Async assertEquals(3, mockSpans.size());
TestUtils.assertSameTraceId(mockSpans);
opentracing-contrib/java-spring-cloud
instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/async/AsyncAnnotationTest.java
// Path: instrument-starters/opentracing-spring-cloud-core/src/main/java/io/opentracing/contrib/spring/cloud/ExtensionTags.java // public class ExtensionTags { // // private ExtensionTags() { // } // // /** // * Tag for {@link Class#getSimpleName()} // */ // public static final StringTag CLASS_TAG = new StringTag("class"); // // /** // * Tag for method name // */ // public static final StringTag METHOD_TAG = new StringTag("method"); // } // // Path: instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/MockTracingConfiguration.java // @Configuration // @EnableAutoConfiguration // public class MockTracingConfiguration { // // @Bean // public MockTracer mockTracer() { // GlobalTracerTestUtil.resetGlobalTracer(); // return new MockTracer(); // } // // @Bean // public RestTemplate restTemplate(RestTemplateBuilder restTemplateBuilder) { // return restTemplateBuilder.build(); // } // // @Bean // public AsyncRestTemplate asyncRestTemplate() { // return new AsyncRestTemplate(); // } // // public static TestRestTemplate createNotTracedRestTemplate(int port) { // return new TestRestTemplate(new RestTemplateBuilder().rootUri("http://localhost:" + port)); // } // } // // Path: instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/TestUtils.java // public class TestUtils { // // /** // * Check if all spans have same traceId. // * // * @param spans the spans to check // */ // public static void assertSameTraceId(Collection<MockSpan> spans) { // if (!spans.isEmpty()) { // final long traceId = spans.iterator().next().context().traceId(); // for (MockSpan span : spans) { // Assert.assertEquals(traceId, span.context().traceId()); // } // } // } // }
import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import io.opentracing.Scope; import io.opentracing.Span; import io.opentracing.contrib.spring.cloud.ExtensionTags; import io.opentracing.contrib.spring.cloud.MockTracingConfiguration; import io.opentracing.contrib.spring.cloud.TestUtils; import io.opentracing.mock.MockSpan; import io.opentracing.mock.MockTracer; import io.opentracing.tag.Tags; import java.util.List; import java.util.concurrent.Future; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.Bean; import org.springframework.scheduling.annotation.Async; import org.springframework.scheduling.annotation.AsyncResult; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
try (Scope scope = mockTracer.activateSpan(span)) { Future<String> fut = asyncService.fooAsync(); await().until(() -> fut.isDone()); assertThat(fut.get()).isNotNull(); } finally { span.finish(); } await().until(() -> mockTracer.finishedSpans().size() == 3); List<MockSpan> mockSpans = mockTracer.finishedSpans(); // parent span from test, span modelling @Async, span inside @Async assertEquals(3, mockSpans.size()); TestUtils.assertSameTraceId(mockSpans); MockSpan outerSpan = mockSpans.get(2); MockSpan fooAsyncSpan = mockSpans.get(1); MockSpan fooInnerSpan = mockSpans.get(0); assertEquals( "Expected the async method span to be a child of the outer span", outerSpan.context().spanId(), fooAsyncSpan.parentId()); assertEquals( "Expected the inner span to be a child of the async method span", fooAsyncSpan.context().spanId(), fooInnerSpan.parentId()); MockSpan asyncSpan = mockSpans.get(1); assertEquals(3, asyncSpan.tags().size()); assertEquals(TraceAsyncAspect.TAG_COMPONENT, asyncSpan.tags().get(Tags.COMPONENT.getKey()));
// Path: instrument-starters/opentracing-spring-cloud-core/src/main/java/io/opentracing/contrib/spring/cloud/ExtensionTags.java // public class ExtensionTags { // // private ExtensionTags() { // } // // /** // * Tag for {@link Class#getSimpleName()} // */ // public static final StringTag CLASS_TAG = new StringTag("class"); // // /** // * Tag for method name // */ // public static final StringTag METHOD_TAG = new StringTag("method"); // } // // Path: instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/MockTracingConfiguration.java // @Configuration // @EnableAutoConfiguration // public class MockTracingConfiguration { // // @Bean // public MockTracer mockTracer() { // GlobalTracerTestUtil.resetGlobalTracer(); // return new MockTracer(); // } // // @Bean // public RestTemplate restTemplate(RestTemplateBuilder restTemplateBuilder) { // return restTemplateBuilder.build(); // } // // @Bean // public AsyncRestTemplate asyncRestTemplate() { // return new AsyncRestTemplate(); // } // // public static TestRestTemplate createNotTracedRestTemplate(int port) { // return new TestRestTemplate(new RestTemplateBuilder().rootUri("http://localhost:" + port)); // } // } // // Path: instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/TestUtils.java // public class TestUtils { // // /** // * Check if all spans have same traceId. // * // * @param spans the spans to check // */ // public static void assertSameTraceId(Collection<MockSpan> spans) { // if (!spans.isEmpty()) { // final long traceId = spans.iterator().next().context().traceId(); // for (MockSpan span : spans) { // Assert.assertEquals(traceId, span.context().traceId()); // } // } // } // } // Path: instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/async/AsyncAnnotationTest.java import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import io.opentracing.Scope; import io.opentracing.Span; import io.opentracing.contrib.spring.cloud.ExtensionTags; import io.opentracing.contrib.spring.cloud.MockTracingConfiguration; import io.opentracing.contrib.spring.cloud.TestUtils; import io.opentracing.mock.MockSpan; import io.opentracing.mock.MockTracer; import io.opentracing.tag.Tags; import java.util.List; import java.util.concurrent.Future; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.Bean; import org.springframework.scheduling.annotation.Async; import org.springframework.scheduling.annotation.AsyncResult; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; try (Scope scope = mockTracer.activateSpan(span)) { Future<String> fut = asyncService.fooAsync(); await().until(() -> fut.isDone()); assertThat(fut.get()).isNotNull(); } finally { span.finish(); } await().until(() -> mockTracer.finishedSpans().size() == 3); List<MockSpan> mockSpans = mockTracer.finishedSpans(); // parent span from test, span modelling @Async, span inside @Async assertEquals(3, mockSpans.size()); TestUtils.assertSameTraceId(mockSpans); MockSpan outerSpan = mockSpans.get(2); MockSpan fooAsyncSpan = mockSpans.get(1); MockSpan fooInnerSpan = mockSpans.get(0); assertEquals( "Expected the async method span to be a child of the outer span", outerSpan.context().spanId(), fooAsyncSpan.parentId()); assertEquals( "Expected the inner span to be a child of the async method span", fooAsyncSpan.context().spanId(), fooInnerSpan.parentId()); MockSpan asyncSpan = mockSpans.get(1); assertEquals(3, asyncSpan.tags().size()); assertEquals(TraceAsyncAspect.TAG_COMPONENT, asyncSpan.tags().get(Tags.COMPONENT.getKey()));
assertEquals("fooAsync", asyncSpan.tags().get(ExtensionTags.METHOD_TAG.getKey()));
opentracing-contrib/java-spring-cloud
instrument-starters/opentracing-spring-cloud-core/src/main/java/io/opentracing/contrib/spring/cloud/async/CustomAsyncConfigurerAutoConfiguration.java
// Path: instrument-starters/opentracing-spring-cloud-core/src/main/java/io/opentracing/contrib/spring/cloud/async/instrument/TracedAsyncConfigurer.java // public class TracedAsyncConfigurer extends AsyncConfigurerSupport { // // private final Tracer tracer; // private final AsyncConfigurer delegate; // // public TracedAsyncConfigurer(Tracer tracer, AsyncConfigurer delegate) { // this.tracer = tracer; // this.delegate = delegate; // } // // @Override // public Executor getAsyncExecutor() { // return new TracedExecutor(this.delegate.getAsyncExecutor(), this.tracer); // } // // @Override // public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { // return delegate.getAsyncUncaughtExceptionHandler(); // } // }
import io.opentracing.Tracer; import io.opentracing.contrib.spring.cloud.async.instrument.TracedAsyncConfigurer; import io.opentracing.contrib.spring.tracer.configuration.TracerAutoConfiguration; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactoryAware; import org.springframework.beans.factory.config.BeanPostProcessor; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.AutoConfigureBefore; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Configuration; import org.springframework.core.PriorityOrdered; import org.springframework.scheduling.annotation.AsyncConfigurer;
/** * Copyright 2017-2019 The OpenTracing Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package io.opentracing.contrib.spring.cloud.async; /** * This auto-configuration wraps available {@link AsyncConfigurer} in a {@link * TracedAsyncConfigurer} * * @author Pavol Loffay * @author Tadaya Tsuyukubo */ @Configuration @ConditionalOnBean(AsyncConfigurer.class) //TODO when Scheduling is added we need to do @AutoConfigurationAfter on it @AutoConfigureBefore(DefaultAsyncAutoConfiguration.class) @AutoConfigureAfter(TracerAutoConfiguration.class) @ConditionalOnProperty(name = "opentracing.spring.cloud.async.enabled", havingValue = "true", matchIfMissing = true) public class CustomAsyncConfigurerAutoConfiguration implements BeanPostProcessor, PriorityOrdered, BeanFactoryAware { private BeanFactory beanFactory; @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { return bean; } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
// Path: instrument-starters/opentracing-spring-cloud-core/src/main/java/io/opentracing/contrib/spring/cloud/async/instrument/TracedAsyncConfigurer.java // public class TracedAsyncConfigurer extends AsyncConfigurerSupport { // // private final Tracer tracer; // private final AsyncConfigurer delegate; // // public TracedAsyncConfigurer(Tracer tracer, AsyncConfigurer delegate) { // this.tracer = tracer; // this.delegate = delegate; // } // // @Override // public Executor getAsyncExecutor() { // return new TracedExecutor(this.delegate.getAsyncExecutor(), this.tracer); // } // // @Override // public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { // return delegate.getAsyncUncaughtExceptionHandler(); // } // } // Path: instrument-starters/opentracing-spring-cloud-core/src/main/java/io/opentracing/contrib/spring/cloud/async/CustomAsyncConfigurerAutoConfiguration.java import io.opentracing.Tracer; import io.opentracing.contrib.spring.cloud.async.instrument.TracedAsyncConfigurer; import io.opentracing.contrib.spring.tracer.configuration.TracerAutoConfiguration; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactoryAware; import org.springframework.beans.factory.config.BeanPostProcessor; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.AutoConfigureBefore; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Configuration; import org.springframework.core.PriorityOrdered; import org.springframework.scheduling.annotation.AsyncConfigurer; /** * Copyright 2017-2019 The OpenTracing Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package io.opentracing.contrib.spring.cloud.async; /** * This auto-configuration wraps available {@link AsyncConfigurer} in a {@link * TracedAsyncConfigurer} * * @author Pavol Loffay * @author Tadaya Tsuyukubo */ @Configuration @ConditionalOnBean(AsyncConfigurer.class) //TODO when Scheduling is added we need to do @AutoConfigurationAfter on it @AutoConfigureBefore(DefaultAsyncAutoConfiguration.class) @AutoConfigureAfter(TracerAutoConfiguration.class) @ConditionalOnProperty(name = "opentracing.spring.cloud.async.enabled", havingValue = "true", matchIfMissing = true) public class CustomAsyncConfigurerAutoConfiguration implements BeanPostProcessor, PriorityOrdered, BeanFactoryAware { private BeanFactory beanFactory; @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { return bean; } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof AsyncConfigurer && !(bean instanceof TracedAsyncConfigurer)) {
opentracing-contrib/java-spring-cloud
instrument-starters/opentracing-spring-cloud-core/src/main/java/io/opentracing/contrib/spring/cloud/scheduled/ScheduledAutoConfiguration.java
// Path: instrument-starters/opentracing-spring-cloud-core/src/main/java/io/opentracing/contrib/spring/cloud/aop/MethodInterceptorSpanDecorator.java // public interface MethodInterceptorSpanDecorator { // // /** // * Decorate span before invocation is done, e.g. before // * {@link ProceedingJoinPoint#proceed()} // * is called // * // * @param ProceedingJoinPoint pjp // * @param Object result // * @param span span // */ // void onPreProceed(ProceedingJoinPoint pjp, Span span); // // /** // * Decorate span after invocation is done, e.g. after // * {@link ProceedingJoinPoint#proceed()} // * is called // * // * @param ProceedingJoinPoint pjp // * @param Object result // * @param span span // */ // void onPostProceed(ProceedingJoinPoint pjp, Object result, Span span); // // /** // * Decorate span when exception is thrown during the invocation, e.g. during // * {@link ProceedingJoinPoint#proceed()} // * is processing. // * // * @param ProceedingJoinPoint pjp // * @param ex exception // * @param span span // */ // void onError(ProceedingJoinPoint pjp, Exception ex, Span span); // // /** // * This decorator adds set of standard tags to the span. // */ // class StandardTags implements MethodInterceptorSpanDecorator { // // @Override // public void onPreProceed(ProceedingJoinPoint pjp, Span span) { // ExtensionTags.CLASS_TAG.set(span, pjp.getTarget().getClass().getSimpleName()); // ExtensionTags.METHOD_TAG.set(span, ((MethodSignature) pjp.getSignature()).getName()); // } // // @Override // public void onPostProceed(ProceedingJoinPoint pjp, Object result, Span span) { // } // // @Override // public void onError(ProceedingJoinPoint pjp, Exception ex, Span span) { // SpanUtils.captureException(span, ex); // } // } // }
import io.opentracing.Tracer; import io.opentracing.contrib.spring.cloud.aop.MethodInterceptorSpanDecorator; import io.opentracing.contrib.spring.tracer.configuration.TracerAutoConfiguration; import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.ObjectProvider; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.annotation.AnnotationAwareOrderComparator; import org.springframework.util.CollectionUtils;
/** * Copyright 2017-2018 The OpenTracing Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package io.opentracing.contrib.spring.cloud.scheduled; /** * @author Pavol Loffay */ @Configuration @ConditionalOnBean(Tracer.class) @AutoConfigureAfter(TracerAutoConfiguration.class) @ConditionalOnProperty(name = "opentracing.spring.cloud.scheduled.enabled", havingValue = "true", matchIfMissing = true) @EnableConfigurationProperties(ScheduledTracingProperties.class) public class ScheduledAutoConfiguration {
// Path: instrument-starters/opentracing-spring-cloud-core/src/main/java/io/opentracing/contrib/spring/cloud/aop/MethodInterceptorSpanDecorator.java // public interface MethodInterceptorSpanDecorator { // // /** // * Decorate span before invocation is done, e.g. before // * {@link ProceedingJoinPoint#proceed()} // * is called // * // * @param ProceedingJoinPoint pjp // * @param Object result // * @param span span // */ // void onPreProceed(ProceedingJoinPoint pjp, Span span); // // /** // * Decorate span after invocation is done, e.g. after // * {@link ProceedingJoinPoint#proceed()} // * is called // * // * @param ProceedingJoinPoint pjp // * @param Object result // * @param span span // */ // void onPostProceed(ProceedingJoinPoint pjp, Object result, Span span); // // /** // * Decorate span when exception is thrown during the invocation, e.g. during // * {@link ProceedingJoinPoint#proceed()} // * is processing. // * // * @param ProceedingJoinPoint pjp // * @param ex exception // * @param span span // */ // void onError(ProceedingJoinPoint pjp, Exception ex, Span span); // // /** // * This decorator adds set of standard tags to the span. // */ // class StandardTags implements MethodInterceptorSpanDecorator { // // @Override // public void onPreProceed(ProceedingJoinPoint pjp, Span span) { // ExtensionTags.CLASS_TAG.set(span, pjp.getTarget().getClass().getSimpleName()); // ExtensionTags.METHOD_TAG.set(span, ((MethodSignature) pjp.getSignature()).getName()); // } // // @Override // public void onPostProceed(ProceedingJoinPoint pjp, Object result, Span span) { // } // // @Override // public void onError(ProceedingJoinPoint pjp, Exception ex, Span span) { // SpanUtils.captureException(span, ex); // } // } // } // Path: instrument-starters/opentracing-spring-cloud-core/src/main/java/io/opentracing/contrib/spring/cloud/scheduled/ScheduledAutoConfiguration.java import io.opentracing.Tracer; import io.opentracing.contrib.spring.cloud.aop.MethodInterceptorSpanDecorator; import io.opentracing.contrib.spring.tracer.configuration.TracerAutoConfiguration; import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.ObjectProvider; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.annotation.AnnotationAwareOrderComparator; import org.springframework.util.CollectionUtils; /** * Copyright 2017-2018 The OpenTracing Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package io.opentracing.contrib.spring.cloud.scheduled; /** * @author Pavol Loffay */ @Configuration @ConditionalOnBean(Tracer.class) @AutoConfigureAfter(TracerAutoConfiguration.class) @ConditionalOnProperty(name = "opentracing.spring.cloud.scheduled.enabled", havingValue = "true", matchIfMissing = true) @EnableConfigurationProperties(ScheduledTracingProperties.class) public class ScheduledAutoConfiguration {
private final ObjectProvider<List<MethodInterceptorSpanDecorator>> methodInterceptorSpanDecorators;
opentracing-contrib/java-spring-cloud
instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/traced/TracedAspectTest.java
// Path: instrument-starters/opentracing-spring-cloud-core/src/main/java/io/opentracing/contrib/spring/cloud/aop/MethodInterceptorSpanDecorator.java // public interface MethodInterceptorSpanDecorator { // // /** // * Decorate span before invocation is done, e.g. before // * {@link ProceedingJoinPoint#proceed()} // * is called // * // * @param ProceedingJoinPoint pjp // * @param Object result // * @param span span // */ // void onPreProceed(ProceedingJoinPoint pjp, Span span); // // /** // * Decorate span after invocation is done, e.g. after // * {@link ProceedingJoinPoint#proceed()} // * is called // * // * @param ProceedingJoinPoint pjp // * @param Object result // * @param span span // */ // void onPostProceed(ProceedingJoinPoint pjp, Object result, Span span); // // /** // * Decorate span when exception is thrown during the invocation, e.g. during // * {@link ProceedingJoinPoint#proceed()} // * is processing. // * // * @param ProceedingJoinPoint pjp // * @param ex exception // * @param span span // */ // void onError(ProceedingJoinPoint pjp, Exception ex, Span span); // // /** // * This decorator adds set of standard tags to the span. // */ // class StandardTags implements MethodInterceptorSpanDecorator { // // @Override // public void onPreProceed(ProceedingJoinPoint pjp, Span span) { // ExtensionTags.CLASS_TAG.set(span, pjp.getTarget().getClass().getSimpleName()); // ExtensionTags.METHOD_TAG.set(span, ((MethodSignature) pjp.getSignature()).getName()); // } // // @Override // public void onPostProceed(ProceedingJoinPoint pjp, Object result, Span span) { // } // // @Override // public void onError(ProceedingJoinPoint pjp, Exception ex, Span span) { // SpanUtils.captureException(span, ex); // } // } // }
import static org.mockito.Mockito.when; import io.opentracing.Span; import io.opentracing.Tracer; import io.opentracing.contrib.spring.cloud.aop.MethodInterceptorSpanDecorator; import io.opentracing.contrib.spring.cloud.aop.Traced; import java.util.List; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.reflect.MethodSignature; import org.assertj.core.api.WithAssertions; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner;
/** * Copyright 2017-2018 The OpenTracing Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package io.opentracing.contrib.spring.cloud.traced; @RunWith(MockitoJUnitRunner.class) public class TracedAspectTest implements WithAssertions { @Mock private Span span; @Mock private Tracer tracer; @Mock
// Path: instrument-starters/opentracing-spring-cloud-core/src/main/java/io/opentracing/contrib/spring/cloud/aop/MethodInterceptorSpanDecorator.java // public interface MethodInterceptorSpanDecorator { // // /** // * Decorate span before invocation is done, e.g. before // * {@link ProceedingJoinPoint#proceed()} // * is called // * // * @param ProceedingJoinPoint pjp // * @param Object result // * @param span span // */ // void onPreProceed(ProceedingJoinPoint pjp, Span span); // // /** // * Decorate span after invocation is done, e.g. after // * {@link ProceedingJoinPoint#proceed()} // * is called // * // * @param ProceedingJoinPoint pjp // * @param Object result // * @param span span // */ // void onPostProceed(ProceedingJoinPoint pjp, Object result, Span span); // // /** // * Decorate span when exception is thrown during the invocation, e.g. during // * {@link ProceedingJoinPoint#proceed()} // * is processing. // * // * @param ProceedingJoinPoint pjp // * @param ex exception // * @param span span // */ // void onError(ProceedingJoinPoint pjp, Exception ex, Span span); // // /** // * This decorator adds set of standard tags to the span. // */ // class StandardTags implements MethodInterceptorSpanDecorator { // // @Override // public void onPreProceed(ProceedingJoinPoint pjp, Span span) { // ExtensionTags.CLASS_TAG.set(span, pjp.getTarget().getClass().getSimpleName()); // ExtensionTags.METHOD_TAG.set(span, ((MethodSignature) pjp.getSignature()).getName()); // } // // @Override // public void onPostProceed(ProceedingJoinPoint pjp, Object result, Span span) { // } // // @Override // public void onError(ProceedingJoinPoint pjp, Exception ex, Span span) { // SpanUtils.captureException(span, ex); // } // } // } // Path: instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/traced/TracedAspectTest.java import static org.mockito.Mockito.when; import io.opentracing.Span; import io.opentracing.Tracer; import io.opentracing.contrib.spring.cloud.aop.MethodInterceptorSpanDecorator; import io.opentracing.contrib.spring.cloud.aop.Traced; import java.util.List; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.reflect.MethodSignature; import org.assertj.core.api.WithAssertions; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; /** * Copyright 2017-2018 The OpenTracing Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package io.opentracing.contrib.spring.cloud.traced; @RunWith(MockitoJUnitRunner.class) public class TracedAspectTest implements WithAssertions { @Mock private Span span; @Mock private Tracer tracer; @Mock
private List<MethodInterceptorSpanDecorator> decorators;
opentracing-contrib/java-spring-cloud
instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/async/WebAsyncTaskTest.java
// Path: instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/MockTracingConfiguration.java // @Configuration // @EnableAutoConfiguration // public class MockTracingConfiguration { // // @Bean // public MockTracer mockTracer() { // GlobalTracerTestUtil.resetGlobalTracer(); // return new MockTracer(); // } // // @Bean // public RestTemplate restTemplate(RestTemplateBuilder restTemplateBuilder) { // return restTemplateBuilder.build(); // } // // @Bean // public AsyncRestTemplate asyncRestTemplate() { // return new AsyncRestTemplate(); // } // // public static TestRestTemplate createNotTracedRestTemplate(int port) { // return new TestRestTemplate(new RestTemplateBuilder().rootUri("http://localhost:" + port)); // } // } // // Path: instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/TestUtils.java // public class TestUtils { // // /** // * Check if all spans have same traceId. // * // * @param spans the spans to check // */ // public static void assertSameTraceId(Collection<MockSpan> spans) { // if (!spans.isEmpty()) { // final long traceId = spans.iterator().next().context().traceId(); // for (MockSpan span : spans) { // Assert.assertEquals(traceId, span.context().traceId()); // } // } // } // }
import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; import static org.junit.Assert.assertEquals; import io.opentracing.contrib.spring.cloud.MockTracingConfiguration; import io.opentracing.contrib.spring.cloud.TestUtils; import io.opentracing.mock.MockSpan; import io.opentracing.mock.MockTracer; import java.util.List; import java.util.concurrent.Callable; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.web.server.LocalServerPort; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.context.request.async.WebAsyncTask;
} @RequestMapping("/callable") public Callable<String> callable() { return () -> { mockTracer.buildSpan("foo").start().finish(); return "callable"; }; } } @Autowired private MockTracer mockTracer; @LocalServerPort private int port; @Before public void before() { mockTracer.reset(); } @Test public void testWebAsyncTaskTraceAndSpans() throws Exception { String response = MockTracingConfiguration.createNotTracedRestTemplate(port).getForObject("/webAsyncTask", String.class); assertThat(response).isNotNull(); await().until(() -> mockTracer.finishedSpans().size() == 2); List<MockSpan> mockSpans = mockTracer.finishedSpans(); assertEquals(2, mockSpans.size());
// Path: instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/MockTracingConfiguration.java // @Configuration // @EnableAutoConfiguration // public class MockTracingConfiguration { // // @Bean // public MockTracer mockTracer() { // GlobalTracerTestUtil.resetGlobalTracer(); // return new MockTracer(); // } // // @Bean // public RestTemplate restTemplate(RestTemplateBuilder restTemplateBuilder) { // return restTemplateBuilder.build(); // } // // @Bean // public AsyncRestTemplate asyncRestTemplate() { // return new AsyncRestTemplate(); // } // // public static TestRestTemplate createNotTracedRestTemplate(int port) { // return new TestRestTemplate(new RestTemplateBuilder().rootUri("http://localhost:" + port)); // } // } // // Path: instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/TestUtils.java // public class TestUtils { // // /** // * Check if all spans have same traceId. // * // * @param spans the spans to check // */ // public static void assertSameTraceId(Collection<MockSpan> spans) { // if (!spans.isEmpty()) { // final long traceId = spans.iterator().next().context().traceId(); // for (MockSpan span : spans) { // Assert.assertEquals(traceId, span.context().traceId()); // } // } // } // } // Path: instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/async/WebAsyncTaskTest.java import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; import static org.junit.Assert.assertEquals; import io.opentracing.contrib.spring.cloud.MockTracingConfiguration; import io.opentracing.contrib.spring.cloud.TestUtils; import io.opentracing.mock.MockSpan; import io.opentracing.mock.MockTracer; import java.util.List; import java.util.concurrent.Callable; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.web.server.LocalServerPort; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.context.request.async.WebAsyncTask; } @RequestMapping("/callable") public Callable<String> callable() { return () -> { mockTracer.buildSpan("foo").start().finish(); return "callable"; }; } } @Autowired private MockTracer mockTracer; @LocalServerPort private int port; @Before public void before() { mockTracer.reset(); } @Test public void testWebAsyncTaskTraceAndSpans() throws Exception { String response = MockTracingConfiguration.createNotTracedRestTemplate(port).getForObject("/webAsyncTask", String.class); assertThat(response).isNotNull(); await().until(() -> mockTracer.finishedSpans().size() == 2); List<MockSpan> mockSpans = mockTracer.finishedSpans(); assertEquals(2, mockSpans.size());
TestUtils.assertSameTraceId(mockSpans);
opentracing-contrib/java-spring-cloud
instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/async/CustomAsyncConfigurerAutoConfigurationTest.java
// Path: instrument-starters/opentracing-spring-cloud-core/src/main/java/io/opentracing/contrib/spring/cloud/async/instrument/TracedAsyncConfigurer.java // public class TracedAsyncConfigurer extends AsyncConfigurerSupport { // // private final Tracer tracer; // private final AsyncConfigurer delegate; // // public TracedAsyncConfigurer(Tracer tracer, AsyncConfigurer delegate) { // this.tracer = tracer; // this.delegate = delegate; // } // // @Override // public Executor getAsyncExecutor() { // return new TracedExecutor(this.delegate.getAsyncExecutor(), this.tracer); // } // // @Override // public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { // return delegate.getAsyncUncaughtExceptionHandler(); // } // }
import static org.assertj.core.api.BDDAssertions.then; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import io.opentracing.Tracer; import io.opentracing.contrib.spring.cloud.async.instrument.TracedAsyncConfigurer; import io.opentracing.mock.MockTracer; import org.junit.Test; import org.springframework.beans.factory.BeanFactory; import org.springframework.scheduling.annotation.AsyncConfigurer;
/** * Copyright 2017-2019 The OpenTracing Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package io.opentracing.contrib.spring.cloud.async; /** * @author kameshs */ public class CustomAsyncConfigurerAutoConfigurationTest { @Test public void should_return_bean_when_its_not_async_configurer() { CustomAsyncConfigurerAutoConfiguration configuration = new CustomAsyncConfigurerAutoConfiguration(); Object bean = configuration.postProcessAfterInitialization(new Object(), "someBean");
// Path: instrument-starters/opentracing-spring-cloud-core/src/main/java/io/opentracing/contrib/spring/cloud/async/instrument/TracedAsyncConfigurer.java // public class TracedAsyncConfigurer extends AsyncConfigurerSupport { // // private final Tracer tracer; // private final AsyncConfigurer delegate; // // public TracedAsyncConfigurer(Tracer tracer, AsyncConfigurer delegate) { // this.tracer = tracer; // this.delegate = delegate; // } // // @Override // public Executor getAsyncExecutor() { // return new TracedExecutor(this.delegate.getAsyncExecutor(), this.tracer); // } // // @Override // public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { // return delegate.getAsyncUncaughtExceptionHandler(); // } // } // Path: instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/async/CustomAsyncConfigurerAutoConfigurationTest.java import static org.assertj.core.api.BDDAssertions.then; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import io.opentracing.Tracer; import io.opentracing.contrib.spring.cloud.async.instrument.TracedAsyncConfigurer; import io.opentracing.mock.MockTracer; import org.junit.Test; import org.springframework.beans.factory.BeanFactory; import org.springframework.scheduling.annotation.AsyncConfigurer; /** * Copyright 2017-2019 The OpenTracing Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package io.opentracing.contrib.spring.cloud.async; /** * @author kameshs */ public class CustomAsyncConfigurerAutoConfigurationTest { @Test public void should_return_bean_when_its_not_async_configurer() { CustomAsyncConfigurerAutoConfiguration configuration = new CustomAsyncConfigurerAutoConfiguration(); Object bean = configuration.postProcessAfterInitialization(new Object(), "someBean");
then(bean).isNotInstanceOf(TracedAsyncConfigurer.class);
opentracing-contrib/java-spring-cloud
instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/scheduled/ScheduledTest.java
// Path: instrument-starters/opentracing-spring-cloud-core/src/main/java/io/opentracing/contrib/spring/cloud/ExtensionTags.java // public class ExtensionTags { // // private ExtensionTags() { // } // // /** // * Tag for {@link Class#getSimpleName()} // */ // public static final StringTag CLASS_TAG = new StringTag("class"); // // /** // * Tag for method name // */ // public static final StringTag METHOD_TAG = new StringTag("method"); // } // // Path: instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/MockTracingConfiguration.java // @Configuration // @EnableAutoConfiguration // public class MockTracingConfiguration { // // @Bean // public MockTracer mockTracer() { // GlobalTracerTestUtil.resetGlobalTracer(); // return new MockTracer(); // } // // @Bean // public RestTemplate restTemplate(RestTemplateBuilder restTemplateBuilder) { // return restTemplateBuilder.build(); // } // // @Bean // public AsyncRestTemplate asyncRestTemplate() { // return new AsyncRestTemplate(); // } // // public static TestRestTemplate createNotTracedRestTemplate(int port) { // return new TestRestTemplate(new RestTemplateBuilder().rootUri("http://localhost:" + port)); // } // } // // Path: instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/TestUtils.java // public class TestUtils { // // /** // * Check if all spans have same traceId. // * // * @param spans the spans to check // */ // public static void assertSameTraceId(Collection<MockSpan> spans) { // if (!spans.isEmpty()) { // final long traceId = spans.iterator().next().context().traceId(); // for (MockSpan span : spans) { // Assert.assertEquals(traceId, span.context().traceId()); // } // } // } // } // // Path: instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/scheduled/ScheduledTest.java // @EnableScheduling // static class Configuration { // // } // // Path: instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/scheduled/ScheduledTest.java // @Component // @EnableScheduling // static class ScheduledComponent { // // @Autowired // private Tracer tracer; // @Autowired // private ScheduledAnnotationBeanPostProcessor scheduledAnnotationBeanPostProcessor; // @Autowired // private BeanFactory beanFactory; // // @Scheduled(fixedDelay = 1) // public void scheduledFoo() { // // disable upcoming scheduling // scheduledAnnotationBeanPostProcessor // .postProcessBeforeDestruction(beanFactory.getBean(ScheduledComponent.class), null); // tracer.buildSpan("child").start().finish(); // } // }
import static org.awaitility.Awaitility.await; import static org.junit.Assert.assertEquals; import io.opentracing.Tracer; import io.opentracing.contrib.spring.cloud.ExtensionTags; import io.opentracing.contrib.spring.cloud.MockTracingConfiguration; import io.opentracing.contrib.spring.cloud.TestUtils; import io.opentracing.contrib.spring.cloud.scheduled.ScheduledTest.Configuration; import io.opentracing.contrib.spring.cloud.scheduled.ScheduledTest.ScheduledComponent; import io.opentracing.mock.MockSpan; import io.opentracing.mock.MockTracer; import io.opentracing.tag.Tags; import java.util.List; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor; import org.springframework.stereotype.Component; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/** * Copyright 2017-2018 The OpenTracing Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package io.opentracing.contrib.spring.cloud.scheduled; /** * @author Pavol Loffay */ @SpringBootTest( webEnvironment = WebEnvironment.RANDOM_PORT, classes = {
// Path: instrument-starters/opentracing-spring-cloud-core/src/main/java/io/opentracing/contrib/spring/cloud/ExtensionTags.java // public class ExtensionTags { // // private ExtensionTags() { // } // // /** // * Tag for {@link Class#getSimpleName()} // */ // public static final StringTag CLASS_TAG = new StringTag("class"); // // /** // * Tag for method name // */ // public static final StringTag METHOD_TAG = new StringTag("method"); // } // // Path: instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/MockTracingConfiguration.java // @Configuration // @EnableAutoConfiguration // public class MockTracingConfiguration { // // @Bean // public MockTracer mockTracer() { // GlobalTracerTestUtil.resetGlobalTracer(); // return new MockTracer(); // } // // @Bean // public RestTemplate restTemplate(RestTemplateBuilder restTemplateBuilder) { // return restTemplateBuilder.build(); // } // // @Bean // public AsyncRestTemplate asyncRestTemplate() { // return new AsyncRestTemplate(); // } // // public static TestRestTemplate createNotTracedRestTemplate(int port) { // return new TestRestTemplate(new RestTemplateBuilder().rootUri("http://localhost:" + port)); // } // } // // Path: instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/TestUtils.java // public class TestUtils { // // /** // * Check if all spans have same traceId. // * // * @param spans the spans to check // */ // public static void assertSameTraceId(Collection<MockSpan> spans) { // if (!spans.isEmpty()) { // final long traceId = spans.iterator().next().context().traceId(); // for (MockSpan span : spans) { // Assert.assertEquals(traceId, span.context().traceId()); // } // } // } // } // // Path: instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/scheduled/ScheduledTest.java // @EnableScheduling // static class Configuration { // // } // // Path: instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/scheduled/ScheduledTest.java // @Component // @EnableScheduling // static class ScheduledComponent { // // @Autowired // private Tracer tracer; // @Autowired // private ScheduledAnnotationBeanPostProcessor scheduledAnnotationBeanPostProcessor; // @Autowired // private BeanFactory beanFactory; // // @Scheduled(fixedDelay = 1) // public void scheduledFoo() { // // disable upcoming scheduling // scheduledAnnotationBeanPostProcessor // .postProcessBeforeDestruction(beanFactory.getBean(ScheduledComponent.class), null); // tracer.buildSpan("child").start().finish(); // } // } // Path: instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/scheduled/ScheduledTest.java import static org.awaitility.Awaitility.await; import static org.junit.Assert.assertEquals; import io.opentracing.Tracer; import io.opentracing.contrib.spring.cloud.ExtensionTags; import io.opentracing.contrib.spring.cloud.MockTracingConfiguration; import io.opentracing.contrib.spring.cloud.TestUtils; import io.opentracing.contrib.spring.cloud.scheduled.ScheduledTest.Configuration; import io.opentracing.contrib.spring.cloud.scheduled.ScheduledTest.ScheduledComponent; import io.opentracing.mock.MockSpan; import io.opentracing.mock.MockTracer; import io.opentracing.tag.Tags; import java.util.List; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor; import org.springframework.stereotype.Component; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** * Copyright 2017-2018 The OpenTracing Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package io.opentracing.contrib.spring.cloud.scheduled; /** * @author Pavol Loffay */ @SpringBootTest( webEnvironment = WebEnvironment.RANDOM_PORT, classes = {
MockTracingConfiguration.class,
opentracing-contrib/java-spring-cloud
instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/scheduled/ScheduledTest.java
// Path: instrument-starters/opentracing-spring-cloud-core/src/main/java/io/opentracing/contrib/spring/cloud/ExtensionTags.java // public class ExtensionTags { // // private ExtensionTags() { // } // // /** // * Tag for {@link Class#getSimpleName()} // */ // public static final StringTag CLASS_TAG = new StringTag("class"); // // /** // * Tag for method name // */ // public static final StringTag METHOD_TAG = new StringTag("method"); // } // // Path: instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/MockTracingConfiguration.java // @Configuration // @EnableAutoConfiguration // public class MockTracingConfiguration { // // @Bean // public MockTracer mockTracer() { // GlobalTracerTestUtil.resetGlobalTracer(); // return new MockTracer(); // } // // @Bean // public RestTemplate restTemplate(RestTemplateBuilder restTemplateBuilder) { // return restTemplateBuilder.build(); // } // // @Bean // public AsyncRestTemplate asyncRestTemplate() { // return new AsyncRestTemplate(); // } // // public static TestRestTemplate createNotTracedRestTemplate(int port) { // return new TestRestTemplate(new RestTemplateBuilder().rootUri("http://localhost:" + port)); // } // } // // Path: instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/TestUtils.java // public class TestUtils { // // /** // * Check if all spans have same traceId. // * // * @param spans the spans to check // */ // public static void assertSameTraceId(Collection<MockSpan> spans) { // if (!spans.isEmpty()) { // final long traceId = spans.iterator().next().context().traceId(); // for (MockSpan span : spans) { // Assert.assertEquals(traceId, span.context().traceId()); // } // } // } // } // // Path: instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/scheduled/ScheduledTest.java // @EnableScheduling // static class Configuration { // // } // // Path: instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/scheduled/ScheduledTest.java // @Component // @EnableScheduling // static class ScheduledComponent { // // @Autowired // private Tracer tracer; // @Autowired // private ScheduledAnnotationBeanPostProcessor scheduledAnnotationBeanPostProcessor; // @Autowired // private BeanFactory beanFactory; // // @Scheduled(fixedDelay = 1) // public void scheduledFoo() { // // disable upcoming scheduling // scheduledAnnotationBeanPostProcessor // .postProcessBeforeDestruction(beanFactory.getBean(ScheduledComponent.class), null); // tracer.buildSpan("child").start().finish(); // } // }
import static org.awaitility.Awaitility.await; import static org.junit.Assert.assertEquals; import io.opentracing.Tracer; import io.opentracing.contrib.spring.cloud.ExtensionTags; import io.opentracing.contrib.spring.cloud.MockTracingConfiguration; import io.opentracing.contrib.spring.cloud.TestUtils; import io.opentracing.contrib.spring.cloud.scheduled.ScheduledTest.Configuration; import io.opentracing.contrib.spring.cloud.scheduled.ScheduledTest.ScheduledComponent; import io.opentracing.mock.MockSpan; import io.opentracing.mock.MockTracer; import io.opentracing.tag.Tags; import java.util.List; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor; import org.springframework.stereotype.Component; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/** * Copyright 2017-2018 The OpenTracing Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package io.opentracing.contrib.spring.cloud.scheduled; /** * @author Pavol Loffay */ @SpringBootTest( webEnvironment = WebEnvironment.RANDOM_PORT, classes = { MockTracingConfiguration.class,
// Path: instrument-starters/opentracing-spring-cloud-core/src/main/java/io/opentracing/contrib/spring/cloud/ExtensionTags.java // public class ExtensionTags { // // private ExtensionTags() { // } // // /** // * Tag for {@link Class#getSimpleName()} // */ // public static final StringTag CLASS_TAG = new StringTag("class"); // // /** // * Tag for method name // */ // public static final StringTag METHOD_TAG = new StringTag("method"); // } // // Path: instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/MockTracingConfiguration.java // @Configuration // @EnableAutoConfiguration // public class MockTracingConfiguration { // // @Bean // public MockTracer mockTracer() { // GlobalTracerTestUtil.resetGlobalTracer(); // return new MockTracer(); // } // // @Bean // public RestTemplate restTemplate(RestTemplateBuilder restTemplateBuilder) { // return restTemplateBuilder.build(); // } // // @Bean // public AsyncRestTemplate asyncRestTemplate() { // return new AsyncRestTemplate(); // } // // public static TestRestTemplate createNotTracedRestTemplate(int port) { // return new TestRestTemplate(new RestTemplateBuilder().rootUri("http://localhost:" + port)); // } // } // // Path: instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/TestUtils.java // public class TestUtils { // // /** // * Check if all spans have same traceId. // * // * @param spans the spans to check // */ // public static void assertSameTraceId(Collection<MockSpan> spans) { // if (!spans.isEmpty()) { // final long traceId = spans.iterator().next().context().traceId(); // for (MockSpan span : spans) { // Assert.assertEquals(traceId, span.context().traceId()); // } // } // } // } // // Path: instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/scheduled/ScheduledTest.java // @EnableScheduling // static class Configuration { // // } // // Path: instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/scheduled/ScheduledTest.java // @Component // @EnableScheduling // static class ScheduledComponent { // // @Autowired // private Tracer tracer; // @Autowired // private ScheduledAnnotationBeanPostProcessor scheduledAnnotationBeanPostProcessor; // @Autowired // private BeanFactory beanFactory; // // @Scheduled(fixedDelay = 1) // public void scheduledFoo() { // // disable upcoming scheduling // scheduledAnnotationBeanPostProcessor // .postProcessBeforeDestruction(beanFactory.getBean(ScheduledComponent.class), null); // tracer.buildSpan("child").start().finish(); // } // } // Path: instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/scheduled/ScheduledTest.java import static org.awaitility.Awaitility.await; import static org.junit.Assert.assertEquals; import io.opentracing.Tracer; import io.opentracing.contrib.spring.cloud.ExtensionTags; import io.opentracing.contrib.spring.cloud.MockTracingConfiguration; import io.opentracing.contrib.spring.cloud.TestUtils; import io.opentracing.contrib.spring.cloud.scheduled.ScheduledTest.Configuration; import io.opentracing.contrib.spring.cloud.scheduled.ScheduledTest.ScheduledComponent; import io.opentracing.mock.MockSpan; import io.opentracing.mock.MockTracer; import io.opentracing.tag.Tags; import java.util.List; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor; import org.springframework.stereotype.Component; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** * Copyright 2017-2018 The OpenTracing Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package io.opentracing.contrib.spring.cloud.scheduled; /** * @author Pavol Loffay */ @SpringBootTest( webEnvironment = WebEnvironment.RANDOM_PORT, classes = { MockTracingConfiguration.class,
Configuration.class,
opentracing-contrib/java-spring-cloud
instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/scheduled/ScheduledTest.java
// Path: instrument-starters/opentracing-spring-cloud-core/src/main/java/io/opentracing/contrib/spring/cloud/ExtensionTags.java // public class ExtensionTags { // // private ExtensionTags() { // } // // /** // * Tag for {@link Class#getSimpleName()} // */ // public static final StringTag CLASS_TAG = new StringTag("class"); // // /** // * Tag for method name // */ // public static final StringTag METHOD_TAG = new StringTag("method"); // } // // Path: instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/MockTracingConfiguration.java // @Configuration // @EnableAutoConfiguration // public class MockTracingConfiguration { // // @Bean // public MockTracer mockTracer() { // GlobalTracerTestUtil.resetGlobalTracer(); // return new MockTracer(); // } // // @Bean // public RestTemplate restTemplate(RestTemplateBuilder restTemplateBuilder) { // return restTemplateBuilder.build(); // } // // @Bean // public AsyncRestTemplate asyncRestTemplate() { // return new AsyncRestTemplate(); // } // // public static TestRestTemplate createNotTracedRestTemplate(int port) { // return new TestRestTemplate(new RestTemplateBuilder().rootUri("http://localhost:" + port)); // } // } // // Path: instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/TestUtils.java // public class TestUtils { // // /** // * Check if all spans have same traceId. // * // * @param spans the spans to check // */ // public static void assertSameTraceId(Collection<MockSpan> spans) { // if (!spans.isEmpty()) { // final long traceId = spans.iterator().next().context().traceId(); // for (MockSpan span : spans) { // Assert.assertEquals(traceId, span.context().traceId()); // } // } // } // } // // Path: instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/scheduled/ScheduledTest.java // @EnableScheduling // static class Configuration { // // } // // Path: instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/scheduled/ScheduledTest.java // @Component // @EnableScheduling // static class ScheduledComponent { // // @Autowired // private Tracer tracer; // @Autowired // private ScheduledAnnotationBeanPostProcessor scheduledAnnotationBeanPostProcessor; // @Autowired // private BeanFactory beanFactory; // // @Scheduled(fixedDelay = 1) // public void scheduledFoo() { // // disable upcoming scheduling // scheduledAnnotationBeanPostProcessor // .postProcessBeforeDestruction(beanFactory.getBean(ScheduledComponent.class), null); // tracer.buildSpan("child").start().finish(); // } // }
import static org.awaitility.Awaitility.await; import static org.junit.Assert.assertEquals; import io.opentracing.Tracer; import io.opentracing.contrib.spring.cloud.ExtensionTags; import io.opentracing.contrib.spring.cloud.MockTracingConfiguration; import io.opentracing.contrib.spring.cloud.TestUtils; import io.opentracing.contrib.spring.cloud.scheduled.ScheduledTest.Configuration; import io.opentracing.contrib.spring.cloud.scheduled.ScheduledTest.ScheduledComponent; import io.opentracing.mock.MockSpan; import io.opentracing.mock.MockTracer; import io.opentracing.tag.Tags; import java.util.List; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor; import org.springframework.stereotype.Component; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/** * Copyright 2017-2018 The OpenTracing Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package io.opentracing.contrib.spring.cloud.scheduled; /** * @author Pavol Loffay */ @SpringBootTest( webEnvironment = WebEnvironment.RANDOM_PORT, classes = { MockTracingConfiguration.class, Configuration.class,
// Path: instrument-starters/opentracing-spring-cloud-core/src/main/java/io/opentracing/contrib/spring/cloud/ExtensionTags.java // public class ExtensionTags { // // private ExtensionTags() { // } // // /** // * Tag for {@link Class#getSimpleName()} // */ // public static final StringTag CLASS_TAG = new StringTag("class"); // // /** // * Tag for method name // */ // public static final StringTag METHOD_TAG = new StringTag("method"); // } // // Path: instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/MockTracingConfiguration.java // @Configuration // @EnableAutoConfiguration // public class MockTracingConfiguration { // // @Bean // public MockTracer mockTracer() { // GlobalTracerTestUtil.resetGlobalTracer(); // return new MockTracer(); // } // // @Bean // public RestTemplate restTemplate(RestTemplateBuilder restTemplateBuilder) { // return restTemplateBuilder.build(); // } // // @Bean // public AsyncRestTemplate asyncRestTemplate() { // return new AsyncRestTemplate(); // } // // public static TestRestTemplate createNotTracedRestTemplate(int port) { // return new TestRestTemplate(new RestTemplateBuilder().rootUri("http://localhost:" + port)); // } // } // // Path: instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/TestUtils.java // public class TestUtils { // // /** // * Check if all spans have same traceId. // * // * @param spans the spans to check // */ // public static void assertSameTraceId(Collection<MockSpan> spans) { // if (!spans.isEmpty()) { // final long traceId = spans.iterator().next().context().traceId(); // for (MockSpan span : spans) { // Assert.assertEquals(traceId, span.context().traceId()); // } // } // } // } // // Path: instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/scheduled/ScheduledTest.java // @EnableScheduling // static class Configuration { // // } // // Path: instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/scheduled/ScheduledTest.java // @Component // @EnableScheduling // static class ScheduledComponent { // // @Autowired // private Tracer tracer; // @Autowired // private ScheduledAnnotationBeanPostProcessor scheduledAnnotationBeanPostProcessor; // @Autowired // private BeanFactory beanFactory; // // @Scheduled(fixedDelay = 1) // public void scheduledFoo() { // // disable upcoming scheduling // scheduledAnnotationBeanPostProcessor // .postProcessBeforeDestruction(beanFactory.getBean(ScheduledComponent.class), null); // tracer.buildSpan("child").start().finish(); // } // } // Path: instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/scheduled/ScheduledTest.java import static org.awaitility.Awaitility.await; import static org.junit.Assert.assertEquals; import io.opentracing.Tracer; import io.opentracing.contrib.spring.cloud.ExtensionTags; import io.opentracing.contrib.spring.cloud.MockTracingConfiguration; import io.opentracing.contrib.spring.cloud.TestUtils; import io.opentracing.contrib.spring.cloud.scheduled.ScheduledTest.Configuration; import io.opentracing.contrib.spring.cloud.scheduled.ScheduledTest.ScheduledComponent; import io.opentracing.mock.MockSpan; import io.opentracing.mock.MockTracer; import io.opentracing.tag.Tags; import java.util.List; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor; import org.springframework.stereotype.Component; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** * Copyright 2017-2018 The OpenTracing Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package io.opentracing.contrib.spring.cloud.scheduled; /** * @author Pavol Loffay */ @SpringBootTest( webEnvironment = WebEnvironment.RANDOM_PORT, classes = { MockTracingConfiguration.class, Configuration.class,
ScheduledComponent.class
opentracing-contrib/java-spring-cloud
instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/scheduled/ScheduledTest.java
// Path: instrument-starters/opentracing-spring-cloud-core/src/main/java/io/opentracing/contrib/spring/cloud/ExtensionTags.java // public class ExtensionTags { // // private ExtensionTags() { // } // // /** // * Tag for {@link Class#getSimpleName()} // */ // public static final StringTag CLASS_TAG = new StringTag("class"); // // /** // * Tag for method name // */ // public static final StringTag METHOD_TAG = new StringTag("method"); // } // // Path: instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/MockTracingConfiguration.java // @Configuration // @EnableAutoConfiguration // public class MockTracingConfiguration { // // @Bean // public MockTracer mockTracer() { // GlobalTracerTestUtil.resetGlobalTracer(); // return new MockTracer(); // } // // @Bean // public RestTemplate restTemplate(RestTemplateBuilder restTemplateBuilder) { // return restTemplateBuilder.build(); // } // // @Bean // public AsyncRestTemplate asyncRestTemplate() { // return new AsyncRestTemplate(); // } // // public static TestRestTemplate createNotTracedRestTemplate(int port) { // return new TestRestTemplate(new RestTemplateBuilder().rootUri("http://localhost:" + port)); // } // } // // Path: instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/TestUtils.java // public class TestUtils { // // /** // * Check if all spans have same traceId. // * // * @param spans the spans to check // */ // public static void assertSameTraceId(Collection<MockSpan> spans) { // if (!spans.isEmpty()) { // final long traceId = spans.iterator().next().context().traceId(); // for (MockSpan span : spans) { // Assert.assertEquals(traceId, span.context().traceId()); // } // } // } // } // // Path: instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/scheduled/ScheduledTest.java // @EnableScheduling // static class Configuration { // // } // // Path: instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/scheduled/ScheduledTest.java // @Component // @EnableScheduling // static class ScheduledComponent { // // @Autowired // private Tracer tracer; // @Autowired // private ScheduledAnnotationBeanPostProcessor scheduledAnnotationBeanPostProcessor; // @Autowired // private BeanFactory beanFactory; // // @Scheduled(fixedDelay = 1) // public void scheduledFoo() { // // disable upcoming scheduling // scheduledAnnotationBeanPostProcessor // .postProcessBeforeDestruction(beanFactory.getBean(ScheduledComponent.class), null); // tracer.buildSpan("child").start().finish(); // } // }
import static org.awaitility.Awaitility.await; import static org.junit.Assert.assertEquals; import io.opentracing.Tracer; import io.opentracing.contrib.spring.cloud.ExtensionTags; import io.opentracing.contrib.spring.cloud.MockTracingConfiguration; import io.opentracing.contrib.spring.cloud.TestUtils; import io.opentracing.contrib.spring.cloud.scheduled.ScheduledTest.Configuration; import io.opentracing.contrib.spring.cloud.scheduled.ScheduledTest.ScheduledComponent; import io.opentracing.mock.MockSpan; import io.opentracing.mock.MockTracer; import io.opentracing.tag.Tags; import java.util.List; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor; import org.springframework.stereotype.Component; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
private Tracer tracer; @Autowired private ScheduledAnnotationBeanPostProcessor scheduledAnnotationBeanPostProcessor; @Autowired private BeanFactory beanFactory; @Scheduled(fixedDelay = 1) public void scheduledFoo() { // disable upcoming scheduling scheduledAnnotationBeanPostProcessor .postProcessBeforeDestruction(beanFactory.getBean(ScheduledComponent.class), null); tracer.buildSpan("child").start().finish(); } } @Autowired private MockTracer tracer; @After public void after() { tracer.reset(); } @Test public void testScheduled() throws InterruptedException { await().until(() -> tracer.finishedSpans().size() == 2); // 1. span created for @Scheduled // 2. span created inside scheduled method List<MockSpan> mockSpans = tracer.finishedSpans(); assertEquals(2, mockSpans.size());
// Path: instrument-starters/opentracing-spring-cloud-core/src/main/java/io/opentracing/contrib/spring/cloud/ExtensionTags.java // public class ExtensionTags { // // private ExtensionTags() { // } // // /** // * Tag for {@link Class#getSimpleName()} // */ // public static final StringTag CLASS_TAG = new StringTag("class"); // // /** // * Tag for method name // */ // public static final StringTag METHOD_TAG = new StringTag("method"); // } // // Path: instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/MockTracingConfiguration.java // @Configuration // @EnableAutoConfiguration // public class MockTracingConfiguration { // // @Bean // public MockTracer mockTracer() { // GlobalTracerTestUtil.resetGlobalTracer(); // return new MockTracer(); // } // // @Bean // public RestTemplate restTemplate(RestTemplateBuilder restTemplateBuilder) { // return restTemplateBuilder.build(); // } // // @Bean // public AsyncRestTemplate asyncRestTemplate() { // return new AsyncRestTemplate(); // } // // public static TestRestTemplate createNotTracedRestTemplate(int port) { // return new TestRestTemplate(new RestTemplateBuilder().rootUri("http://localhost:" + port)); // } // } // // Path: instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/TestUtils.java // public class TestUtils { // // /** // * Check if all spans have same traceId. // * // * @param spans the spans to check // */ // public static void assertSameTraceId(Collection<MockSpan> spans) { // if (!spans.isEmpty()) { // final long traceId = spans.iterator().next().context().traceId(); // for (MockSpan span : spans) { // Assert.assertEquals(traceId, span.context().traceId()); // } // } // } // } // // Path: instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/scheduled/ScheduledTest.java // @EnableScheduling // static class Configuration { // // } // // Path: instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/scheduled/ScheduledTest.java // @Component // @EnableScheduling // static class ScheduledComponent { // // @Autowired // private Tracer tracer; // @Autowired // private ScheduledAnnotationBeanPostProcessor scheduledAnnotationBeanPostProcessor; // @Autowired // private BeanFactory beanFactory; // // @Scheduled(fixedDelay = 1) // public void scheduledFoo() { // // disable upcoming scheduling // scheduledAnnotationBeanPostProcessor // .postProcessBeforeDestruction(beanFactory.getBean(ScheduledComponent.class), null); // tracer.buildSpan("child").start().finish(); // } // } // Path: instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/scheduled/ScheduledTest.java import static org.awaitility.Awaitility.await; import static org.junit.Assert.assertEquals; import io.opentracing.Tracer; import io.opentracing.contrib.spring.cloud.ExtensionTags; import io.opentracing.contrib.spring.cloud.MockTracingConfiguration; import io.opentracing.contrib.spring.cloud.TestUtils; import io.opentracing.contrib.spring.cloud.scheduled.ScheduledTest.Configuration; import io.opentracing.contrib.spring.cloud.scheduled.ScheduledTest.ScheduledComponent; import io.opentracing.mock.MockSpan; import io.opentracing.mock.MockTracer; import io.opentracing.tag.Tags; import java.util.List; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor; import org.springframework.stereotype.Component; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; private Tracer tracer; @Autowired private ScheduledAnnotationBeanPostProcessor scheduledAnnotationBeanPostProcessor; @Autowired private BeanFactory beanFactory; @Scheduled(fixedDelay = 1) public void scheduledFoo() { // disable upcoming scheduling scheduledAnnotationBeanPostProcessor .postProcessBeforeDestruction(beanFactory.getBean(ScheduledComponent.class), null); tracer.buildSpan("child").start().finish(); } } @Autowired private MockTracer tracer; @After public void after() { tracer.reset(); } @Test public void testScheduled() throws InterruptedException { await().until(() -> tracer.finishedSpans().size() == 2); // 1. span created for @Scheduled // 2. span created inside scheduled method List<MockSpan> mockSpans = tracer.finishedSpans(); assertEquals(2, mockSpans.size());
TestUtils.assertSameTraceId(mockSpans);
opentracing-contrib/java-spring-cloud
instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/scheduled/ScheduledTest.java
// Path: instrument-starters/opentracing-spring-cloud-core/src/main/java/io/opentracing/contrib/spring/cloud/ExtensionTags.java // public class ExtensionTags { // // private ExtensionTags() { // } // // /** // * Tag for {@link Class#getSimpleName()} // */ // public static final StringTag CLASS_TAG = new StringTag("class"); // // /** // * Tag for method name // */ // public static final StringTag METHOD_TAG = new StringTag("method"); // } // // Path: instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/MockTracingConfiguration.java // @Configuration // @EnableAutoConfiguration // public class MockTracingConfiguration { // // @Bean // public MockTracer mockTracer() { // GlobalTracerTestUtil.resetGlobalTracer(); // return new MockTracer(); // } // // @Bean // public RestTemplate restTemplate(RestTemplateBuilder restTemplateBuilder) { // return restTemplateBuilder.build(); // } // // @Bean // public AsyncRestTemplate asyncRestTemplate() { // return new AsyncRestTemplate(); // } // // public static TestRestTemplate createNotTracedRestTemplate(int port) { // return new TestRestTemplate(new RestTemplateBuilder().rootUri("http://localhost:" + port)); // } // } // // Path: instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/TestUtils.java // public class TestUtils { // // /** // * Check if all spans have same traceId. // * // * @param spans the spans to check // */ // public static void assertSameTraceId(Collection<MockSpan> spans) { // if (!spans.isEmpty()) { // final long traceId = spans.iterator().next().context().traceId(); // for (MockSpan span : spans) { // Assert.assertEquals(traceId, span.context().traceId()); // } // } // } // } // // Path: instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/scheduled/ScheduledTest.java // @EnableScheduling // static class Configuration { // // } // // Path: instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/scheduled/ScheduledTest.java // @Component // @EnableScheduling // static class ScheduledComponent { // // @Autowired // private Tracer tracer; // @Autowired // private ScheduledAnnotationBeanPostProcessor scheduledAnnotationBeanPostProcessor; // @Autowired // private BeanFactory beanFactory; // // @Scheduled(fixedDelay = 1) // public void scheduledFoo() { // // disable upcoming scheduling // scheduledAnnotationBeanPostProcessor // .postProcessBeforeDestruction(beanFactory.getBean(ScheduledComponent.class), null); // tracer.buildSpan("child").start().finish(); // } // }
import static org.awaitility.Awaitility.await; import static org.junit.Assert.assertEquals; import io.opentracing.Tracer; import io.opentracing.contrib.spring.cloud.ExtensionTags; import io.opentracing.contrib.spring.cloud.MockTracingConfiguration; import io.opentracing.contrib.spring.cloud.TestUtils; import io.opentracing.contrib.spring.cloud.scheduled.ScheduledTest.Configuration; import io.opentracing.contrib.spring.cloud.scheduled.ScheduledTest.ScheduledComponent; import io.opentracing.mock.MockSpan; import io.opentracing.mock.MockTracer; import io.opentracing.tag.Tags; import java.util.List; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor; import org.springframework.stereotype.Component; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
} } @Autowired private MockTracer tracer; @After public void after() { tracer.reset(); } @Test public void testScheduled() throws InterruptedException { await().until(() -> tracer.finishedSpans().size() == 2); // 1. span created for @Scheduled // 2. span created inside scheduled method List<MockSpan> mockSpans = tracer.finishedSpans(); assertEquals(2, mockSpans.size()); TestUtils.assertSameTraceId(mockSpans); MockSpan localSpan = mockSpans.get(0); assertEquals("child", localSpan.operationName()); MockSpan scheduledSpan = mockSpans.get(1); assertEquals(scheduledSpan.context().spanId(), localSpan.parentId()); assertEquals("scheduledFoo", scheduledSpan.operationName()); assertEquals(3, scheduledSpan.tags().size()); assertEquals(0, scheduledSpan.logEntries().size()); assertEquals("scheduled", scheduledSpan.tags().get(Tags.COMPONENT.getKey())); assertEquals(ScheduledComponent.class.getSimpleName(),
// Path: instrument-starters/opentracing-spring-cloud-core/src/main/java/io/opentracing/contrib/spring/cloud/ExtensionTags.java // public class ExtensionTags { // // private ExtensionTags() { // } // // /** // * Tag for {@link Class#getSimpleName()} // */ // public static final StringTag CLASS_TAG = new StringTag("class"); // // /** // * Tag for method name // */ // public static final StringTag METHOD_TAG = new StringTag("method"); // } // // Path: instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/MockTracingConfiguration.java // @Configuration // @EnableAutoConfiguration // public class MockTracingConfiguration { // // @Bean // public MockTracer mockTracer() { // GlobalTracerTestUtil.resetGlobalTracer(); // return new MockTracer(); // } // // @Bean // public RestTemplate restTemplate(RestTemplateBuilder restTemplateBuilder) { // return restTemplateBuilder.build(); // } // // @Bean // public AsyncRestTemplate asyncRestTemplate() { // return new AsyncRestTemplate(); // } // // public static TestRestTemplate createNotTracedRestTemplate(int port) { // return new TestRestTemplate(new RestTemplateBuilder().rootUri("http://localhost:" + port)); // } // } // // Path: instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/TestUtils.java // public class TestUtils { // // /** // * Check if all spans have same traceId. // * // * @param spans the spans to check // */ // public static void assertSameTraceId(Collection<MockSpan> spans) { // if (!spans.isEmpty()) { // final long traceId = spans.iterator().next().context().traceId(); // for (MockSpan span : spans) { // Assert.assertEquals(traceId, span.context().traceId()); // } // } // } // } // // Path: instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/scheduled/ScheduledTest.java // @EnableScheduling // static class Configuration { // // } // // Path: instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/scheduled/ScheduledTest.java // @Component // @EnableScheduling // static class ScheduledComponent { // // @Autowired // private Tracer tracer; // @Autowired // private ScheduledAnnotationBeanPostProcessor scheduledAnnotationBeanPostProcessor; // @Autowired // private BeanFactory beanFactory; // // @Scheduled(fixedDelay = 1) // public void scheduledFoo() { // // disable upcoming scheduling // scheduledAnnotationBeanPostProcessor // .postProcessBeforeDestruction(beanFactory.getBean(ScheduledComponent.class), null); // tracer.buildSpan("child").start().finish(); // } // } // Path: instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/scheduled/ScheduledTest.java import static org.awaitility.Awaitility.await; import static org.junit.Assert.assertEquals; import io.opentracing.Tracer; import io.opentracing.contrib.spring.cloud.ExtensionTags; import io.opentracing.contrib.spring.cloud.MockTracingConfiguration; import io.opentracing.contrib.spring.cloud.TestUtils; import io.opentracing.contrib.spring.cloud.scheduled.ScheduledTest.Configuration; import io.opentracing.contrib.spring.cloud.scheduled.ScheduledTest.ScheduledComponent; import io.opentracing.mock.MockSpan; import io.opentracing.mock.MockTracer; import io.opentracing.tag.Tags; import java.util.List; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor; import org.springframework.stereotype.Component; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; } } @Autowired private MockTracer tracer; @After public void after() { tracer.reset(); } @Test public void testScheduled() throws InterruptedException { await().until(() -> tracer.finishedSpans().size() == 2); // 1. span created for @Scheduled // 2. span created inside scheduled method List<MockSpan> mockSpans = tracer.finishedSpans(); assertEquals(2, mockSpans.size()); TestUtils.assertSameTraceId(mockSpans); MockSpan localSpan = mockSpans.get(0); assertEquals("child", localSpan.operationName()); MockSpan scheduledSpan = mockSpans.get(1); assertEquals(scheduledSpan.context().spanId(), localSpan.parentId()); assertEquals("scheduledFoo", scheduledSpan.operationName()); assertEquals(3, scheduledSpan.tags().size()); assertEquals(0, scheduledSpan.logEntries().size()); assertEquals("scheduled", scheduledSpan.tags().get(Tags.COMPONENT.getKey())); assertEquals(ScheduledComponent.class.getSimpleName(),
scheduledSpan.tags().get(ExtensionTags.CLASS_TAG.getKey()));
opentracing-contrib/java-spring-cloud
instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/async/instrument/TracedThreadPoolTaskSchedulerIntegrationTest.java
// Path: instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/MockTracingConfiguration.java // @Configuration // @EnableAutoConfiguration // public class MockTracingConfiguration { // // @Bean // public MockTracer mockTracer() { // GlobalTracerTestUtil.resetGlobalTracer(); // return new MockTracer(); // } // // @Bean // public RestTemplate restTemplate(RestTemplateBuilder restTemplateBuilder) { // return restTemplateBuilder.build(); // } // // @Bean // public AsyncRestTemplate asyncRestTemplate() { // return new AsyncRestTemplate(); // } // // public static TestRestTemplate createNotTracedRestTemplate(int port) { // return new TestRestTemplate(new RestTemplateBuilder().rootUri("http://localhost:" + port)); // } // } // // Path: instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/TestUtils.java // public class TestUtils { // // /** // * Check if all spans have same traceId. // * // * @param spans the spans to check // */ // public static void assertSameTraceId(Collection<MockSpan> spans) { // if (!spans.isEmpty()) { // final long traceId = spans.iterator().next().context().traceId(); // for (MockSpan span : spans) { // Assert.assertEquals(traceId, span.context().traceId()); // } // } // } // }
import static org.awaitility.Awaitility.await; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import io.opentracing.Scope; import io.opentracing.Span; import io.opentracing.contrib.spring.cloud.MockTracingConfiguration; import io.opentracing.contrib.spring.cloud.TestUtils; import io.opentracing.mock.MockSpan; import io.opentracing.mock.MockTracer; import java.time.Instant; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.RejectedExecutionException; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.task.SimpleAsyncTaskExecutor; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
} } @Autowired private MockTracer mockTracer; @Autowired @Qualifier("threadPoolTaskScheduler") private ThreadPoolTaskScheduler threadPoolTaskScheduler; @Before public void before() { mockTracer.reset(); } @Test public void testExecute() { final Span span = mockTracer.buildSpan("5150").start(); try (Scope scope = mockTracer.activateSpan(span)) { final CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> { mockTracer.buildSpan("child").start().finish(); return "ok"; }, threadPoolTaskScheduler); completableFuture.join(); } span.finish(); await().until(() -> mockTracer.finishedSpans().size() == 2); final List<MockSpan> mockSpans = mockTracer.finishedSpans(); assertEquals(2, mockSpans.size());
// Path: instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/MockTracingConfiguration.java // @Configuration // @EnableAutoConfiguration // public class MockTracingConfiguration { // // @Bean // public MockTracer mockTracer() { // GlobalTracerTestUtil.resetGlobalTracer(); // return new MockTracer(); // } // // @Bean // public RestTemplate restTemplate(RestTemplateBuilder restTemplateBuilder) { // return restTemplateBuilder.build(); // } // // @Bean // public AsyncRestTemplate asyncRestTemplate() { // return new AsyncRestTemplate(); // } // // public static TestRestTemplate createNotTracedRestTemplate(int port) { // return new TestRestTemplate(new RestTemplateBuilder().rootUri("http://localhost:" + port)); // } // } // // Path: instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/TestUtils.java // public class TestUtils { // // /** // * Check if all spans have same traceId. // * // * @param spans the spans to check // */ // public static void assertSameTraceId(Collection<MockSpan> spans) { // if (!spans.isEmpty()) { // final long traceId = spans.iterator().next().context().traceId(); // for (MockSpan span : spans) { // Assert.assertEquals(traceId, span.context().traceId()); // } // } // } // } // Path: instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/async/instrument/TracedThreadPoolTaskSchedulerIntegrationTest.java import static org.awaitility.Awaitility.await; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import io.opentracing.Scope; import io.opentracing.Span; import io.opentracing.contrib.spring.cloud.MockTracingConfiguration; import io.opentracing.contrib.spring.cloud.TestUtils; import io.opentracing.mock.MockSpan; import io.opentracing.mock.MockTracer; import java.time.Instant; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.RejectedExecutionException; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.task.SimpleAsyncTaskExecutor; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; } } @Autowired private MockTracer mockTracer; @Autowired @Qualifier("threadPoolTaskScheduler") private ThreadPoolTaskScheduler threadPoolTaskScheduler; @Before public void before() { mockTracer.reset(); } @Test public void testExecute() { final Span span = mockTracer.buildSpan("5150").start(); try (Scope scope = mockTracer.activateSpan(span)) { final CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> { mockTracer.buildSpan("child").start().finish(); return "ok"; }, threadPoolTaskScheduler); completableFuture.join(); } span.finish(); await().until(() -> mockTracer.finishedSpans().size() == 2); final List<MockSpan> mockSpans = mockTracer.finishedSpans(); assertEquals(2, mockSpans.size());
TestUtils.assertSameTraceId(mockSpans);
opentracing-contrib/java-spring-cloud
instrument-starters/opentracing-spring-cloud-core/src/main/java/io/opentracing/contrib/spring/cloud/traced/TracedAutoConfiguration.java
// Path: instrument-starters/opentracing-spring-cloud-core/src/main/java/io/opentracing/contrib/spring/cloud/aop/MethodInterceptorSpanDecorator.java // public interface MethodInterceptorSpanDecorator { // // /** // * Decorate span before invocation is done, e.g. before // * {@link ProceedingJoinPoint#proceed()} // * is called // * // * @param ProceedingJoinPoint pjp // * @param Object result // * @param span span // */ // void onPreProceed(ProceedingJoinPoint pjp, Span span); // // /** // * Decorate span after invocation is done, e.g. after // * {@link ProceedingJoinPoint#proceed()} // * is called // * // * @param ProceedingJoinPoint pjp // * @param Object result // * @param span span // */ // void onPostProceed(ProceedingJoinPoint pjp, Object result, Span span); // // /** // * Decorate span when exception is thrown during the invocation, e.g. during // * {@link ProceedingJoinPoint#proceed()} // * is processing. // * // * @param ProceedingJoinPoint pjp // * @param ex exception // * @param span span // */ // void onError(ProceedingJoinPoint pjp, Exception ex, Span span); // // /** // * This decorator adds set of standard tags to the span. // */ // class StandardTags implements MethodInterceptorSpanDecorator { // // @Override // public void onPreProceed(ProceedingJoinPoint pjp, Span span) { // ExtensionTags.CLASS_TAG.set(span, pjp.getTarget().getClass().getSimpleName()); // ExtensionTags.METHOD_TAG.set(span, ((MethodSignature) pjp.getSignature()).getName()); // } // // @Override // public void onPostProceed(ProceedingJoinPoint pjp, Object result, Span span) { // } // // @Override // public void onError(ProceedingJoinPoint pjp, Exception ex, Span span) { // SpanUtils.captureException(span, ex); // } // } // }
import org.springframework.util.CollectionUtils; import io.opentracing.Tracer; import io.opentracing.contrib.spring.cloud.aop.MethodInterceptorSpanDecorator; import io.opentracing.contrib.spring.tracer.configuration.TracerAutoConfiguration; import java.util.ArrayList; import java.util.List; import org.aspectj.lang.ProceedingJoinPoint; import org.springframework.beans.factory.ObjectProvider; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.annotation.AnnotationAwareOrderComparator;
/** * Copyright 2017-2018 The OpenTracing Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package io.opentracing.contrib.spring.cloud.traced; @Configuration @ConditionalOnBean(Tracer.class) @AutoConfigureAfter(TracerAutoConfiguration.class) @ConditionalOnProperty(name = "opentracing.spring.cloud.traced.enabled", havingValue = "true", matchIfMissing = true) @ConditionalOnWebApplication @ConditionalOnClass({ProceedingJoinPoint.class}) @EnableConfigurationProperties(TracedTracingProperties.class) public class TracedAutoConfiguration {
// Path: instrument-starters/opentracing-spring-cloud-core/src/main/java/io/opentracing/contrib/spring/cloud/aop/MethodInterceptorSpanDecorator.java // public interface MethodInterceptorSpanDecorator { // // /** // * Decorate span before invocation is done, e.g. before // * {@link ProceedingJoinPoint#proceed()} // * is called // * // * @param ProceedingJoinPoint pjp // * @param Object result // * @param span span // */ // void onPreProceed(ProceedingJoinPoint pjp, Span span); // // /** // * Decorate span after invocation is done, e.g. after // * {@link ProceedingJoinPoint#proceed()} // * is called // * // * @param ProceedingJoinPoint pjp // * @param Object result // * @param span span // */ // void onPostProceed(ProceedingJoinPoint pjp, Object result, Span span); // // /** // * Decorate span when exception is thrown during the invocation, e.g. during // * {@link ProceedingJoinPoint#proceed()} // * is processing. // * // * @param ProceedingJoinPoint pjp // * @param ex exception // * @param span span // */ // void onError(ProceedingJoinPoint pjp, Exception ex, Span span); // // /** // * This decorator adds set of standard tags to the span. // */ // class StandardTags implements MethodInterceptorSpanDecorator { // // @Override // public void onPreProceed(ProceedingJoinPoint pjp, Span span) { // ExtensionTags.CLASS_TAG.set(span, pjp.getTarget().getClass().getSimpleName()); // ExtensionTags.METHOD_TAG.set(span, ((MethodSignature) pjp.getSignature()).getName()); // } // // @Override // public void onPostProceed(ProceedingJoinPoint pjp, Object result, Span span) { // } // // @Override // public void onError(ProceedingJoinPoint pjp, Exception ex, Span span) { // SpanUtils.captureException(span, ex); // } // } // } // Path: instrument-starters/opentracing-spring-cloud-core/src/main/java/io/opentracing/contrib/spring/cloud/traced/TracedAutoConfiguration.java import org.springframework.util.CollectionUtils; import io.opentracing.Tracer; import io.opentracing.contrib.spring.cloud.aop.MethodInterceptorSpanDecorator; import io.opentracing.contrib.spring.tracer.configuration.TracerAutoConfiguration; import java.util.ArrayList; import java.util.List; import org.aspectj.lang.ProceedingJoinPoint; import org.springframework.beans.factory.ObjectProvider; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.annotation.AnnotationAwareOrderComparator; /** * Copyright 2017-2018 The OpenTracing Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package io.opentracing.contrib.spring.cloud.traced; @Configuration @ConditionalOnBean(Tracer.class) @AutoConfigureAfter(TracerAutoConfiguration.class) @ConditionalOnProperty(name = "opentracing.spring.cloud.traced.enabled", havingValue = "true", matchIfMissing = true) @ConditionalOnWebApplication @ConditionalOnClass({ProceedingJoinPoint.class}) @EnableConfigurationProperties(TracedTracingProperties.class) public class TracedAutoConfiguration {
private final ObjectProvider<List<MethodInterceptorSpanDecorator>> methodInterceptorSpanDecorators;
opentracing-contrib/java-spring-cloud
instrument-starters/opentracing-spring-cloud-reactor-starter/src/test/java/io/opentracing/contrib/spring/cloud/reactor/ReactorTracingAutoConfigurationTest.java
// Path: instrument-starters/opentracing-spring-cloud-reactor-starter/src/test/java/io/opentracing/contrib/spring/cloud/reactor/ReactorTracingAutoConfigurationTest.java // @Configuration // @EnableAutoConfiguration // public static class MockTracingConfiguration { // @Bean // public MockTracer tracer() { // return new MockTracer(); // } // } // // Path: instrument-starters/opentracing-spring-cloud-reactor-starter/src/test/java/io/opentracing/contrib/spring/cloud/reactor/ReactorTracingAutoConfigurationTest.java // @RestController // public static class TestController { // // private static final Scheduler EARLY_CACHED_SCHEDULER = Schedulers.parallel(); // // @Autowired // private MockTracer mockTracer; // // @RequestMapping(method = RequestMethod.GET, value = "/single") // public Mono<Integer> single() { // return Flux.range(1, 10) // .subscribeOn(Schedulers.elastic()) // .publishOn(EARLY_CACHED_SCHEDULER) // .flatMap(x -> Mono.fromSupplier(() -> { // // without enabled Reactor instrumentation active span will be null // assertNotNull(mockTracer.activeSpan()); // mockTracer.activeSpan().setTag("reactor", "reactor"); // return x * 2; // }).subscribeOn(EARLY_CACHED_SCHEDULER)) // .take(1) // .single(); // } // // }
import static org.awaitility.Awaitility.await; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import io.opentracing.contrib.spring.cloud.reactor.ReactorTracingAutoConfigurationTest.MockTracingConfiguration; import io.opentracing.contrib.spring.cloud.reactor.ReactorTracingAutoConfigurationTest.TestController; import io.opentracing.mock.MockSpan; import io.opentracing.mock.MockTracer; import java.util.List; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.ResponseEntity; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.core.scheduler.Scheduler; import reactor.core.scheduler.Schedulers;
/** * Copyright 2017-2019 The OpenTracing Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package io.opentracing.contrib.spring.cloud.reactor; @SpringBootTest( webEnvironment = WebEnvironment.RANDOM_PORT,
// Path: instrument-starters/opentracing-spring-cloud-reactor-starter/src/test/java/io/opentracing/contrib/spring/cloud/reactor/ReactorTracingAutoConfigurationTest.java // @Configuration // @EnableAutoConfiguration // public static class MockTracingConfiguration { // @Bean // public MockTracer tracer() { // return new MockTracer(); // } // } // // Path: instrument-starters/opentracing-spring-cloud-reactor-starter/src/test/java/io/opentracing/contrib/spring/cloud/reactor/ReactorTracingAutoConfigurationTest.java // @RestController // public static class TestController { // // private static final Scheduler EARLY_CACHED_SCHEDULER = Schedulers.parallel(); // // @Autowired // private MockTracer mockTracer; // // @RequestMapping(method = RequestMethod.GET, value = "/single") // public Mono<Integer> single() { // return Flux.range(1, 10) // .subscribeOn(Schedulers.elastic()) // .publishOn(EARLY_CACHED_SCHEDULER) // .flatMap(x -> Mono.fromSupplier(() -> { // // without enabled Reactor instrumentation active span will be null // assertNotNull(mockTracer.activeSpan()); // mockTracer.activeSpan().setTag("reactor", "reactor"); // return x * 2; // }).subscribeOn(EARLY_CACHED_SCHEDULER)) // .take(1) // .single(); // } // // } // Path: instrument-starters/opentracing-spring-cloud-reactor-starter/src/test/java/io/opentracing/contrib/spring/cloud/reactor/ReactorTracingAutoConfigurationTest.java import static org.awaitility.Awaitility.await; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import io.opentracing.contrib.spring.cloud.reactor.ReactorTracingAutoConfigurationTest.MockTracingConfiguration; import io.opentracing.contrib.spring.cloud.reactor.ReactorTracingAutoConfigurationTest.TestController; import io.opentracing.mock.MockSpan; import io.opentracing.mock.MockTracer; import java.util.List; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.ResponseEntity; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.core.scheduler.Scheduler; import reactor.core.scheduler.Schedulers; /** * Copyright 2017-2019 The OpenTracing Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package io.opentracing.contrib.spring.cloud.reactor; @SpringBootTest( webEnvironment = WebEnvironment.RANDOM_PORT,
classes = {MockTracingConfiguration.class, TestController.class},
opentracing-contrib/java-spring-cloud
instrument-starters/opentracing-spring-cloud-reactor-starter/src/test/java/io/opentracing/contrib/spring/cloud/reactor/ReactorTracingAutoConfigurationTest.java
// Path: instrument-starters/opentracing-spring-cloud-reactor-starter/src/test/java/io/opentracing/contrib/spring/cloud/reactor/ReactorTracingAutoConfigurationTest.java // @Configuration // @EnableAutoConfiguration // public static class MockTracingConfiguration { // @Bean // public MockTracer tracer() { // return new MockTracer(); // } // } // // Path: instrument-starters/opentracing-spring-cloud-reactor-starter/src/test/java/io/opentracing/contrib/spring/cloud/reactor/ReactorTracingAutoConfigurationTest.java // @RestController // public static class TestController { // // private static final Scheduler EARLY_CACHED_SCHEDULER = Schedulers.parallel(); // // @Autowired // private MockTracer mockTracer; // // @RequestMapping(method = RequestMethod.GET, value = "/single") // public Mono<Integer> single() { // return Flux.range(1, 10) // .subscribeOn(Schedulers.elastic()) // .publishOn(EARLY_CACHED_SCHEDULER) // .flatMap(x -> Mono.fromSupplier(() -> { // // without enabled Reactor instrumentation active span will be null // assertNotNull(mockTracer.activeSpan()); // mockTracer.activeSpan().setTag("reactor", "reactor"); // return x * 2; // }).subscribeOn(EARLY_CACHED_SCHEDULER)) // .take(1) // .single(); // } // // }
import static org.awaitility.Awaitility.await; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import io.opentracing.contrib.spring.cloud.reactor.ReactorTracingAutoConfigurationTest.MockTracingConfiguration; import io.opentracing.contrib.spring.cloud.reactor.ReactorTracingAutoConfigurationTest.TestController; import io.opentracing.mock.MockSpan; import io.opentracing.mock.MockTracer; import java.util.List; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.ResponseEntity; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.core.scheduler.Scheduler; import reactor.core.scheduler.Schedulers;
/** * Copyright 2017-2019 The OpenTracing Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package io.opentracing.contrib.spring.cloud.reactor; @SpringBootTest( webEnvironment = WebEnvironment.RANDOM_PORT,
// Path: instrument-starters/opentracing-spring-cloud-reactor-starter/src/test/java/io/opentracing/contrib/spring/cloud/reactor/ReactorTracingAutoConfigurationTest.java // @Configuration // @EnableAutoConfiguration // public static class MockTracingConfiguration { // @Bean // public MockTracer tracer() { // return new MockTracer(); // } // } // // Path: instrument-starters/opentracing-spring-cloud-reactor-starter/src/test/java/io/opentracing/contrib/spring/cloud/reactor/ReactorTracingAutoConfigurationTest.java // @RestController // public static class TestController { // // private static final Scheduler EARLY_CACHED_SCHEDULER = Schedulers.parallel(); // // @Autowired // private MockTracer mockTracer; // // @RequestMapping(method = RequestMethod.GET, value = "/single") // public Mono<Integer> single() { // return Flux.range(1, 10) // .subscribeOn(Schedulers.elastic()) // .publishOn(EARLY_CACHED_SCHEDULER) // .flatMap(x -> Mono.fromSupplier(() -> { // // without enabled Reactor instrumentation active span will be null // assertNotNull(mockTracer.activeSpan()); // mockTracer.activeSpan().setTag("reactor", "reactor"); // return x * 2; // }).subscribeOn(EARLY_CACHED_SCHEDULER)) // .take(1) // .single(); // } // // } // Path: instrument-starters/opentracing-spring-cloud-reactor-starter/src/test/java/io/opentracing/contrib/spring/cloud/reactor/ReactorTracingAutoConfigurationTest.java import static org.awaitility.Awaitility.await; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import io.opentracing.contrib.spring.cloud.reactor.ReactorTracingAutoConfigurationTest.MockTracingConfiguration; import io.opentracing.contrib.spring.cloud.reactor.ReactorTracingAutoConfigurationTest.TestController; import io.opentracing.mock.MockSpan; import io.opentracing.mock.MockTracer; import java.util.List; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.ResponseEntity; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.core.scheduler.Scheduler; import reactor.core.scheduler.Schedulers; /** * Copyright 2017-2019 The OpenTracing Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package io.opentracing.contrib.spring.cloud.reactor; @SpringBootTest( webEnvironment = WebEnvironment.RANDOM_PORT,
classes = {MockTracingConfiguration.class, TestController.class},
opentracing-contrib/java-spring-cloud
instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/log/LoggingAutoConfigurationTest.java
// Path: instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/MockTracingConfiguration.java // @Configuration // @EnableAutoConfiguration // public class MockTracingConfiguration { // // @Bean // public MockTracer mockTracer() { // GlobalTracerTestUtil.resetGlobalTracer(); // return new MockTracer(); // } // // @Bean // public RestTemplate restTemplate(RestTemplateBuilder restTemplateBuilder) { // return restTemplateBuilder.build(); // } // // @Bean // public AsyncRestTemplate asyncRestTemplate() { // return new AsyncRestTemplate(); // } // // public static TestRestTemplate createNotTracedRestTemplate(int port) { // return new TestRestTemplate(new RestTemplateBuilder().rootUri("http://localhost:" + port)); // } // }
import static org.awaitility.Awaitility.await; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import io.opentracing.contrib.spring.cloud.MockTracingConfiguration; import io.opentracing.mock.MockSpan; import io.opentracing.mock.MockSpan.LogEntry; import io.opentracing.mock.MockTracer; import io.opentracing.tag.Tags; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.event.Level; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.http.ResponseEntity; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController;
/** * Copyright 2017-2018 The OpenTracing Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package io.opentracing.contrib.spring.cloud.log; /** * @author Pavol Loffay */ @SpringBootTest( webEnvironment = WebEnvironment.RANDOM_PORT,
// Path: instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/MockTracingConfiguration.java // @Configuration // @EnableAutoConfiguration // public class MockTracingConfiguration { // // @Bean // public MockTracer mockTracer() { // GlobalTracerTestUtil.resetGlobalTracer(); // return new MockTracer(); // } // // @Bean // public RestTemplate restTemplate(RestTemplateBuilder restTemplateBuilder) { // return restTemplateBuilder.build(); // } // // @Bean // public AsyncRestTemplate asyncRestTemplate() { // return new AsyncRestTemplate(); // } // // public static TestRestTemplate createNotTracedRestTemplate(int port) { // return new TestRestTemplate(new RestTemplateBuilder().rootUri("http://localhost:" + port)); // } // } // Path: instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/log/LoggingAutoConfigurationTest.java import static org.awaitility.Awaitility.await; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import io.opentracing.contrib.spring.cloud.MockTracingConfiguration; import io.opentracing.mock.MockSpan; import io.opentracing.mock.MockSpan.LogEntry; import io.opentracing.mock.MockTracer; import io.opentracing.tag.Tags; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.event.Level; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.http.ResponseEntity; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * Copyright 2017-2018 The OpenTracing Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package io.opentracing.contrib.spring.cloud.log; /** * @author Pavol Loffay */ @SpringBootTest( webEnvironment = WebEnvironment.RANDOM_PORT,
classes = {MockTracingConfiguration.class, LoggingAutoConfigurationTest.Controller.class},
opentracing-contrib/java-spring-cloud
instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/async/TracedExecutorTest.java
// Path: instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/MockTracingConfiguration.java // @Configuration // @EnableAutoConfiguration // public class MockTracingConfiguration { // // @Bean // public MockTracer mockTracer() { // GlobalTracerTestUtil.resetGlobalTracer(); // return new MockTracer(); // } // // @Bean // public RestTemplate restTemplate(RestTemplateBuilder restTemplateBuilder) { // return restTemplateBuilder.build(); // } // // @Bean // public AsyncRestTemplate asyncRestTemplate() { // return new AsyncRestTemplate(); // } // // public static TestRestTemplate createNotTracedRestTemplate(int port) { // return new TestRestTemplate(new RestTemplateBuilder().rootUri("http://localhost:" + port)); // } // } // // Path: instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/TestUtils.java // public class TestUtils { // // /** // * Check if all spans have same traceId. // * // * @param spans the spans to check // */ // public static void assertSameTraceId(Collection<MockSpan> spans) { // if (!spans.isEmpty()) { // final long traceId = spans.iterator().next().context().traceId(); // for (MockSpan span : spans) { // Assert.assertEquals(traceId, span.context().traceId()); // } // } // } // }
import static org.awaitility.Awaitility.await; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import io.opentracing.Scope; import io.opentracing.Span; import io.opentracing.contrib.spring.cloud.MockTracingConfiguration; import io.opentracing.contrib.spring.cloud.TestUtils; import io.opentracing.mock.MockSpan; import io.opentracing.mock.MockTracer; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.RejectedExecutionException; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.Bean; import org.springframework.core.task.SimpleAsyncTaskExecutor; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@Before public void before() { mockTracer.reset(); } @Test public void testThreadPoolTracedExecutor() { testTracedExecutor(threadPoolExecutor); } @Test public void testSimpleTracedExecutor() { testTracedExecutor(simpleAsyncExecutor); } private void testTracedExecutor(Executor executor) { Span span = mockTracer.buildSpan("foo").start(); try (Scope scope = mockTracer.activateSpan(span)) { CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> { mockTracer.buildSpan("child").start().finish(); return "ok"; }, executor); completableFuture.join(); } span.finish(); await().until(() -> mockTracer.finishedSpans().size() == 2); List<MockSpan> mockSpans = mockTracer.finishedSpans(); assertEquals(2, mockSpans.size());
// Path: instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/MockTracingConfiguration.java // @Configuration // @EnableAutoConfiguration // public class MockTracingConfiguration { // // @Bean // public MockTracer mockTracer() { // GlobalTracerTestUtil.resetGlobalTracer(); // return new MockTracer(); // } // // @Bean // public RestTemplate restTemplate(RestTemplateBuilder restTemplateBuilder) { // return restTemplateBuilder.build(); // } // // @Bean // public AsyncRestTemplate asyncRestTemplate() { // return new AsyncRestTemplate(); // } // // public static TestRestTemplate createNotTracedRestTemplate(int port) { // return new TestRestTemplate(new RestTemplateBuilder().rootUri("http://localhost:" + port)); // } // } // // Path: instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/TestUtils.java // public class TestUtils { // // /** // * Check if all spans have same traceId. // * // * @param spans the spans to check // */ // public static void assertSameTraceId(Collection<MockSpan> spans) { // if (!spans.isEmpty()) { // final long traceId = spans.iterator().next().context().traceId(); // for (MockSpan span : spans) { // Assert.assertEquals(traceId, span.context().traceId()); // } // } // } // } // Path: instrument-starters/opentracing-spring-cloud-core/src/test/java/io/opentracing/contrib/spring/cloud/async/TracedExecutorTest.java import static org.awaitility.Awaitility.await; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import io.opentracing.Scope; import io.opentracing.Span; import io.opentracing.contrib.spring.cloud.MockTracingConfiguration; import io.opentracing.contrib.spring.cloud.TestUtils; import io.opentracing.mock.MockSpan; import io.opentracing.mock.MockTracer; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.RejectedExecutionException; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.Bean; import org.springframework.core.task.SimpleAsyncTaskExecutor; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @Before public void before() { mockTracer.reset(); } @Test public void testThreadPoolTracedExecutor() { testTracedExecutor(threadPoolExecutor); } @Test public void testSimpleTracedExecutor() { testTracedExecutor(simpleAsyncExecutor); } private void testTracedExecutor(Executor executor) { Span span = mockTracer.buildSpan("foo").start(); try (Scope scope = mockTracer.activateSpan(span)) { CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> { mockTracer.buildSpan("child").start().finish(); return "ok"; }, executor); completableFuture.join(); } span.finish(); await().until(() -> mockTracer.finishedSpans().size() == 2); List<MockSpan> mockSpans = mockTracer.finishedSpans(); assertEquals(2, mockSpans.size());
TestUtils.assertSameTraceId(mockSpans);
opentracing-contrib/java-spring-cloud
instrument-starters/opentracing-spring-cloud-feign-starter/src/test/java/io/opentracing/contrib/spring/cloud/feign/FeignClientWithoutClientInContextTest.java
// Path: instrument-starters/opentracing-spring-cloud-feign-starter/src/test/java/io/opentracing/contrib/spring/cloud/feign/FeignTest.java // static void verify(MockTracer mockTracer) { // await().until(() -> mockTracer.finishedSpans().size() == 1); // List<MockSpan> mockSpans = mockTracer.finishedSpans(); // assertEquals(1, mockSpans.size()); // assertEquals(Tags.SPAN_KIND_CLIENT, mockSpans.get(0).tags().get(Tags.SPAN_KIND.getKey())); // }
import static io.opentracing.contrib.spring.cloud.feign.FeignTest.verify; import io.opentracing.mock.MockTracer; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.cloud.openfeign.EnableFeignClients; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.context.annotation.Configuration; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod;
/** * Copyright 2017-2019 The OpenTracing Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package io.opentracing.contrib.spring.cloud.feign; /** * @author Matthieu Ghilain */ @SpringBootTest( classes = {MockTracingWithoutFeignClientConfiguration.class, TestController.class, FeignClientWithoutClientInContextTest.FeignClientWithoutClientInContextTestConfiguration.class}, webEnvironment = WebEnvironment.DEFINED_PORT) @TestPropertySource(properties = { "opentracing.spring.web.skipPattern=/notTraced", "server.port=13599"}) @RunWith(SpringJUnit4ClassRunner.class) public class FeignClientWithoutClientInContextTest { @Autowired MockTracer mockTracer; @Autowired protected FeignInterface feignInterface; @Configuration @EnableFeignClients static class FeignClientWithoutClientInContextTestConfiguration { } @FeignClient(value = "FeignClientWithoutClientInContextTestFeignClient", url = "localhost:13599") interface FeignInterface { @RequestMapping(method = RequestMethod.GET, value = "/notTraced") String hello(); } @Test public void testTracedRequestWithoutFeignClientInContext() { feignInterface.hello();
// Path: instrument-starters/opentracing-spring-cloud-feign-starter/src/test/java/io/opentracing/contrib/spring/cloud/feign/FeignTest.java // static void verify(MockTracer mockTracer) { // await().until(() -> mockTracer.finishedSpans().size() == 1); // List<MockSpan> mockSpans = mockTracer.finishedSpans(); // assertEquals(1, mockSpans.size()); // assertEquals(Tags.SPAN_KIND_CLIENT, mockSpans.get(0).tags().get(Tags.SPAN_KIND.getKey())); // } // Path: instrument-starters/opentracing-spring-cloud-feign-starter/src/test/java/io/opentracing/contrib/spring/cloud/feign/FeignClientWithoutClientInContextTest.java import static io.opentracing.contrib.spring.cloud.feign.FeignTest.verify; import io.opentracing.mock.MockTracer; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.cloud.openfeign.EnableFeignClients; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.context.annotation.Configuration; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; /** * Copyright 2017-2019 The OpenTracing Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package io.opentracing.contrib.spring.cloud.feign; /** * @author Matthieu Ghilain */ @SpringBootTest( classes = {MockTracingWithoutFeignClientConfiguration.class, TestController.class, FeignClientWithoutClientInContextTest.FeignClientWithoutClientInContextTestConfiguration.class}, webEnvironment = WebEnvironment.DEFINED_PORT) @TestPropertySource(properties = { "opentracing.spring.web.skipPattern=/notTraced", "server.port=13599"}) @RunWith(SpringJUnit4ClassRunner.class) public class FeignClientWithoutClientInContextTest { @Autowired MockTracer mockTracer; @Autowired protected FeignInterface feignInterface; @Configuration @EnableFeignClients static class FeignClientWithoutClientInContextTestConfiguration { } @FeignClient(value = "FeignClientWithoutClientInContextTestFeignClient", url = "localhost:13599") interface FeignInterface { @RequestMapping(method = RequestMethod.GET, value = "/notTraced") String hello(); } @Test public void testTracedRequestWithoutFeignClientInContext() { feignInterface.hello();
verify(mockTracer);
opentracing-contrib/java-spring-cloud
instrument-starters/opentracing-spring-cloud-feign-starter/src/test/java/io/opentracing/contrib/spring/cloud/feign/FeignDefinedUrlTest.java
// Path: instrument-starters/opentracing-spring-cloud-feign-starter/src/test/java/io/opentracing/contrib/spring/cloud/feign/FeignTest.java // static void verify(MockTracer mockTracer) { // await().until(() -> mockTracer.finishedSpans().size() == 1); // List<MockSpan> mockSpans = mockTracer.finishedSpans(); // assertEquals(1, mockSpans.size()); // assertEquals(Tags.SPAN_KIND_CLIENT, mockSpans.get(0).tags().get(Tags.SPAN_KIND.getKey())); // } // // Path: instrument-starters/opentracing-spring-cloud-feign-starter/src/test/java/io/opentracing/contrib/spring/cloud/feign/FeignDefinedUrlTest.java // @Configuration // @EnableFeignClients(clients = FeignInterface.class) // static class FeignWithoutRibbonConfiguration { // // }
import static io.opentracing.contrib.spring.cloud.feign.FeignTest.verify; import io.opentracing.contrib.spring.cloud.feign.FeignDefinedUrlTest.FeignWithoutRibbonConfiguration; import io.opentracing.mock.MockTracer; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.cloud.openfeign.EnableFeignClients; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.context.annotation.Configuration; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod;
/** * Copyright 2017-2019 The OpenTracing Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package io.opentracing.contrib.spring.cloud.feign; /** * @author Pavol Loffay * @author Gilles Robert */ @SpringBootTest( webEnvironment = WebEnvironment.DEFINED_PORT, classes = {MockTracingConfiguration.class, TestController.class,
// Path: instrument-starters/opentracing-spring-cloud-feign-starter/src/test/java/io/opentracing/contrib/spring/cloud/feign/FeignTest.java // static void verify(MockTracer mockTracer) { // await().until(() -> mockTracer.finishedSpans().size() == 1); // List<MockSpan> mockSpans = mockTracer.finishedSpans(); // assertEquals(1, mockSpans.size()); // assertEquals(Tags.SPAN_KIND_CLIENT, mockSpans.get(0).tags().get(Tags.SPAN_KIND.getKey())); // } // // Path: instrument-starters/opentracing-spring-cloud-feign-starter/src/test/java/io/opentracing/contrib/spring/cloud/feign/FeignDefinedUrlTest.java // @Configuration // @EnableFeignClients(clients = FeignInterface.class) // static class FeignWithoutRibbonConfiguration { // // } // Path: instrument-starters/opentracing-spring-cloud-feign-starter/src/test/java/io/opentracing/contrib/spring/cloud/feign/FeignDefinedUrlTest.java import static io.opentracing.contrib.spring.cloud.feign.FeignTest.verify; import io.opentracing.contrib.spring.cloud.feign.FeignDefinedUrlTest.FeignWithoutRibbonConfiguration; import io.opentracing.mock.MockTracer; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.cloud.openfeign.EnableFeignClients; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.context.annotation.Configuration; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; /** * Copyright 2017-2019 The OpenTracing Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package io.opentracing.contrib.spring.cloud.feign; /** * @author Pavol Loffay * @author Gilles Robert */ @SpringBootTest( webEnvironment = WebEnvironment.DEFINED_PORT, classes = {MockTracingConfiguration.class, TestController.class,
FeignWithoutRibbonConfiguration.class})
opentracing-contrib/java-spring-cloud
instrument-starters/opentracing-spring-cloud-feign-starter/src/test/java/io/opentracing/contrib/spring/cloud/feign/FeignDefinedUrlTest.java
// Path: instrument-starters/opentracing-spring-cloud-feign-starter/src/test/java/io/opentracing/contrib/spring/cloud/feign/FeignTest.java // static void verify(MockTracer mockTracer) { // await().until(() -> mockTracer.finishedSpans().size() == 1); // List<MockSpan> mockSpans = mockTracer.finishedSpans(); // assertEquals(1, mockSpans.size()); // assertEquals(Tags.SPAN_KIND_CLIENT, mockSpans.get(0).tags().get(Tags.SPAN_KIND.getKey())); // } // // Path: instrument-starters/opentracing-spring-cloud-feign-starter/src/test/java/io/opentracing/contrib/spring/cloud/feign/FeignDefinedUrlTest.java // @Configuration // @EnableFeignClients(clients = FeignInterface.class) // static class FeignWithoutRibbonConfiguration { // // }
import static io.opentracing.contrib.spring.cloud.feign.FeignTest.verify; import io.opentracing.contrib.spring.cloud.feign.FeignDefinedUrlTest.FeignWithoutRibbonConfiguration; import io.opentracing.mock.MockTracer; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.cloud.openfeign.EnableFeignClients; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.context.annotation.Configuration; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod;
/** * Copyright 2017-2019 The OpenTracing Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package io.opentracing.contrib.spring.cloud.feign; /** * @author Pavol Loffay * @author Gilles Robert */ @SpringBootTest( webEnvironment = WebEnvironment.DEFINED_PORT, classes = {MockTracingConfiguration.class, TestController.class, FeignWithoutRibbonConfiguration.class}) @TestPropertySource(properties = { "opentracing.spring.web.skipPattern=/notTraced", "server.port=13598"}) @RunWith(SpringJUnit4ClassRunner.class) public class FeignDefinedUrlTest { @Configuration @EnableFeignClients(clients = FeignInterface.class) static class FeignWithoutRibbonConfiguration { } @FeignClient(value = "FeignDefinedUrlTestClient", url = "localhost:13598") interface FeignInterface { @RequestMapping(method = RequestMethod.GET, value = "/notTraced") String hello(); } @Autowired MockTracer mockTracer; @Autowired protected FeignInterface feignInterface; @Test public void testTracedRequestDefinedUrl() throws InterruptedException { feignInterface.hello();
// Path: instrument-starters/opentracing-spring-cloud-feign-starter/src/test/java/io/opentracing/contrib/spring/cloud/feign/FeignTest.java // static void verify(MockTracer mockTracer) { // await().until(() -> mockTracer.finishedSpans().size() == 1); // List<MockSpan> mockSpans = mockTracer.finishedSpans(); // assertEquals(1, mockSpans.size()); // assertEquals(Tags.SPAN_KIND_CLIENT, mockSpans.get(0).tags().get(Tags.SPAN_KIND.getKey())); // } // // Path: instrument-starters/opentracing-spring-cloud-feign-starter/src/test/java/io/opentracing/contrib/spring/cloud/feign/FeignDefinedUrlTest.java // @Configuration // @EnableFeignClients(clients = FeignInterface.class) // static class FeignWithoutRibbonConfiguration { // // } // Path: instrument-starters/opentracing-spring-cloud-feign-starter/src/test/java/io/opentracing/contrib/spring/cloud/feign/FeignDefinedUrlTest.java import static io.opentracing.contrib.spring.cloud.feign.FeignTest.verify; import io.opentracing.contrib.spring.cloud.feign.FeignDefinedUrlTest.FeignWithoutRibbonConfiguration; import io.opentracing.mock.MockTracer; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.cloud.openfeign.EnableFeignClients; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.context.annotation.Configuration; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; /** * Copyright 2017-2019 The OpenTracing Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package io.opentracing.contrib.spring.cloud.feign; /** * @author Pavol Loffay * @author Gilles Robert */ @SpringBootTest( webEnvironment = WebEnvironment.DEFINED_PORT, classes = {MockTracingConfiguration.class, TestController.class, FeignWithoutRibbonConfiguration.class}) @TestPropertySource(properties = { "opentracing.spring.web.skipPattern=/notTraced", "server.port=13598"}) @RunWith(SpringJUnit4ClassRunner.class) public class FeignDefinedUrlTest { @Configuration @EnableFeignClients(clients = FeignInterface.class) static class FeignWithoutRibbonConfiguration { } @FeignClient(value = "FeignDefinedUrlTestClient", url = "localhost:13598") interface FeignInterface { @RequestMapping(method = RequestMethod.GET, value = "/notTraced") String hello(); } @Autowired MockTracer mockTracer; @Autowired protected FeignInterface feignInterface; @Test public void testTracedRequestDefinedUrl() throws InterruptedException { feignInterface.hello();
verify(mockTracer);
opentracing-contrib/java-spring-cloud
instrument-starters/opentracing-spring-cloud-feign-starter/src/test/java/io/opentracing/contrib/spring/cloud/feign/FeignTest.java
// Path: instrument-starters/opentracing-spring-cloud-feign-starter/src/test/java/io/opentracing/contrib/spring/cloud/feign/FeignTest.java // @Configuration // @EnableFeignClients // @RibbonClients(@RibbonClient(name = "localService", configuration = RibbonConfiguration.class)) // static class FeignRibbonLocalConfiguration { // // }
import static org.awaitility.Awaitility.await; import static org.junit.Assert.assertEquals; import com.netflix.loadbalancer.BaseLoadBalancer; import com.netflix.loadbalancer.ILoadBalancer; import com.netflix.loadbalancer.Server; import io.opentracing.contrib.spring.cloud.feign.FeignTest.FeignRibbonLocalConfiguration; import io.opentracing.mock.MockSpan; import io.opentracing.mock.MockTracer; import io.opentracing.tag.Tags; import java.util.Collections; import java.util.List; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.web.server.LocalServerPort; import org.springframework.cloud.netflix.ribbon.RibbonClient; import org.springframework.cloud.netflix.ribbon.RibbonClients; import org.springframework.cloud.openfeign.EnableFeignClients; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod;
/** * Copyright 2017-2019 The OpenTracing Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package io.opentracing.contrib.spring.cloud.feign; /** * @author Pavol Loffay * @author Gilles Robert */ @SpringBootTest( webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = {MockTracingConfiguration.class, TestController.class,
// Path: instrument-starters/opentracing-spring-cloud-feign-starter/src/test/java/io/opentracing/contrib/spring/cloud/feign/FeignTest.java // @Configuration // @EnableFeignClients // @RibbonClients(@RibbonClient(name = "localService", configuration = RibbonConfiguration.class)) // static class FeignRibbonLocalConfiguration { // // } // Path: instrument-starters/opentracing-spring-cloud-feign-starter/src/test/java/io/opentracing/contrib/spring/cloud/feign/FeignTest.java import static org.awaitility.Awaitility.await; import static org.junit.Assert.assertEquals; import com.netflix.loadbalancer.BaseLoadBalancer; import com.netflix.loadbalancer.ILoadBalancer; import com.netflix.loadbalancer.Server; import io.opentracing.contrib.spring.cloud.feign.FeignTest.FeignRibbonLocalConfiguration; import io.opentracing.mock.MockSpan; import io.opentracing.mock.MockTracer; import io.opentracing.tag.Tags; import java.util.Collections; import java.util.List; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.web.server.LocalServerPort; import org.springframework.cloud.netflix.ribbon.RibbonClient; import org.springframework.cloud.netflix.ribbon.RibbonClients; import org.springframework.cloud.openfeign.EnableFeignClients; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; /** * Copyright 2017-2019 The OpenTracing Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package io.opentracing.contrib.spring.cloud.feign; /** * @author Pavol Loffay * @author Gilles Robert */ @SpringBootTest( webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = {MockTracingConfiguration.class, TestController.class,
FeignRibbonLocalConfiguration.class},
strepsirrhini-army/chaos-loris
src/main/java/io/pivotal/strepsirrhini/chaosloris/destroyer/StandardDestroyerFactory.java
// Path: src/main/java/io/pivotal/strepsirrhini/chaosloris/data/ChaosRepository.java // @Repository // public interface ChaosRepository extends JpaRepository<Chaos, Long> { // // /** // * Find all of the {@link Chaos}es related to an {@link Application} // * // * @param application the {@link Application} that {@link Chaos}es are related to // * @return a collection of {@link Chaos}es related to the {@link Application} // */ // @Transactional(readOnly = true) // List<Chaos> findByApplication(Application application); // // /** // * Find all of the {@link Chaos}es related to a {@link Schedule} // * // * @param schedule the {@link Schedule} that {@link Chaos}es are related to // * @return a collection of {@link Chaos}es related to the {@link Schedule} // */ // @Transactional(readOnly = true) // List<Chaos> findBySchedule(Schedule schedule); // // /** // * Find all of the {@link Chaos}es related to a {@link Schedule} // * // * @param id the id of {@link Schedule} that {@link Chaos}es are related to // * @return a collection of {@link Chaos}es related to the {@link Schedule} // */ // @Transactional(readOnly = true) // List<Chaos> findByScheduleId(Long id); // // } // // Path: src/main/java/io/pivotal/strepsirrhini/chaosloris/data/EventRepository.java // @Repository // public interface EventRepository extends JpaRepository<Event, Long> { // // /** // * Find all of the {@link Event}s related to a {@link Chaos} // * // * @param chaos the {@link Chaos} that {@link Event}s are related to // * @return a collection of {@link Event}s related to the {@link Chaos} // */ // @Transactional(readOnly = true) // List<Event> findByChaos(Chaos chaos); // // /** // * Find all of the {@link Event}s that occurred before an {@link Instant} // * // * @param instant the {@link Instant} to find {@link Event}s before // * @return a collection {@link Event}s that occurred before the {@link Instant} // */ // @Transactional(readOnly = true) // List<Event> findByExecutedAtBefore(Instant instant); // // }
import io.pivotal.strepsirrhini.chaosloris.data.ChaosRepository; import io.pivotal.strepsirrhini.chaosloris.data.EventRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component;
/* * Copyright 2015-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.pivotal.strepsirrhini.chaosloris.destroyer; @Component final class StandardDestroyerFactory implements DestroyerFactory {
// Path: src/main/java/io/pivotal/strepsirrhini/chaosloris/data/ChaosRepository.java // @Repository // public interface ChaosRepository extends JpaRepository<Chaos, Long> { // // /** // * Find all of the {@link Chaos}es related to an {@link Application} // * // * @param application the {@link Application} that {@link Chaos}es are related to // * @return a collection of {@link Chaos}es related to the {@link Application} // */ // @Transactional(readOnly = true) // List<Chaos> findByApplication(Application application); // // /** // * Find all of the {@link Chaos}es related to a {@link Schedule} // * // * @param schedule the {@link Schedule} that {@link Chaos}es are related to // * @return a collection of {@link Chaos}es related to the {@link Schedule} // */ // @Transactional(readOnly = true) // List<Chaos> findBySchedule(Schedule schedule); // // /** // * Find all of the {@link Chaos}es related to a {@link Schedule} // * // * @param id the id of {@link Schedule} that {@link Chaos}es are related to // * @return a collection of {@link Chaos}es related to the {@link Schedule} // */ // @Transactional(readOnly = true) // List<Chaos> findByScheduleId(Long id); // // } // // Path: src/main/java/io/pivotal/strepsirrhini/chaosloris/data/EventRepository.java // @Repository // public interface EventRepository extends JpaRepository<Event, Long> { // // /** // * Find all of the {@link Event}s related to a {@link Chaos} // * // * @param chaos the {@link Chaos} that {@link Event}s are related to // * @return a collection of {@link Event}s related to the {@link Chaos} // */ // @Transactional(readOnly = true) // List<Event> findByChaos(Chaos chaos); // // /** // * Find all of the {@link Event}s that occurred before an {@link Instant} // * // * @param instant the {@link Instant} to find {@link Event}s before // * @return a collection {@link Event}s that occurred before the {@link Instant} // */ // @Transactional(readOnly = true) // List<Event> findByExecutedAtBefore(Instant instant); // // } // Path: src/main/java/io/pivotal/strepsirrhini/chaosloris/destroyer/StandardDestroyerFactory.java import io.pivotal.strepsirrhini.chaosloris.data.ChaosRepository; import io.pivotal.strepsirrhini.chaosloris.data.EventRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; /* * Copyright 2015-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.pivotal.strepsirrhini.chaosloris.destroyer; @Component final class StandardDestroyerFactory implements DestroyerFactory {
private final ChaosRepository chaosRepository;
strepsirrhini-army/chaos-loris
src/main/java/io/pivotal/strepsirrhini/chaosloris/destroyer/StandardDestroyerFactory.java
// Path: src/main/java/io/pivotal/strepsirrhini/chaosloris/data/ChaosRepository.java // @Repository // public interface ChaosRepository extends JpaRepository<Chaos, Long> { // // /** // * Find all of the {@link Chaos}es related to an {@link Application} // * // * @param application the {@link Application} that {@link Chaos}es are related to // * @return a collection of {@link Chaos}es related to the {@link Application} // */ // @Transactional(readOnly = true) // List<Chaos> findByApplication(Application application); // // /** // * Find all of the {@link Chaos}es related to a {@link Schedule} // * // * @param schedule the {@link Schedule} that {@link Chaos}es are related to // * @return a collection of {@link Chaos}es related to the {@link Schedule} // */ // @Transactional(readOnly = true) // List<Chaos> findBySchedule(Schedule schedule); // // /** // * Find all of the {@link Chaos}es related to a {@link Schedule} // * // * @param id the id of {@link Schedule} that {@link Chaos}es are related to // * @return a collection of {@link Chaos}es related to the {@link Schedule} // */ // @Transactional(readOnly = true) // List<Chaos> findByScheduleId(Long id); // // } // // Path: src/main/java/io/pivotal/strepsirrhini/chaosloris/data/EventRepository.java // @Repository // public interface EventRepository extends JpaRepository<Event, Long> { // // /** // * Find all of the {@link Event}s related to a {@link Chaos} // * // * @param chaos the {@link Chaos} that {@link Event}s are related to // * @return a collection of {@link Event}s related to the {@link Chaos} // */ // @Transactional(readOnly = true) // List<Event> findByChaos(Chaos chaos); // // /** // * Find all of the {@link Event}s that occurred before an {@link Instant} // * // * @param instant the {@link Instant} to find {@link Event}s before // * @return a collection {@link Event}s that occurred before the {@link Instant} // */ // @Transactional(readOnly = true) // List<Event> findByExecutedAtBefore(Instant instant); // // }
import io.pivotal.strepsirrhini.chaosloris.data.ChaosRepository; import io.pivotal.strepsirrhini.chaosloris.data.EventRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component;
/* * Copyright 2015-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.pivotal.strepsirrhini.chaosloris.destroyer; @Component final class StandardDestroyerFactory implements DestroyerFactory { private final ChaosRepository chaosRepository;
// Path: src/main/java/io/pivotal/strepsirrhini/chaosloris/data/ChaosRepository.java // @Repository // public interface ChaosRepository extends JpaRepository<Chaos, Long> { // // /** // * Find all of the {@link Chaos}es related to an {@link Application} // * // * @param application the {@link Application} that {@link Chaos}es are related to // * @return a collection of {@link Chaos}es related to the {@link Application} // */ // @Transactional(readOnly = true) // List<Chaos> findByApplication(Application application); // // /** // * Find all of the {@link Chaos}es related to a {@link Schedule} // * // * @param schedule the {@link Schedule} that {@link Chaos}es are related to // * @return a collection of {@link Chaos}es related to the {@link Schedule} // */ // @Transactional(readOnly = true) // List<Chaos> findBySchedule(Schedule schedule); // // /** // * Find all of the {@link Chaos}es related to a {@link Schedule} // * // * @param id the id of {@link Schedule} that {@link Chaos}es are related to // * @return a collection of {@link Chaos}es related to the {@link Schedule} // */ // @Transactional(readOnly = true) // List<Chaos> findByScheduleId(Long id); // // } // // Path: src/main/java/io/pivotal/strepsirrhini/chaosloris/data/EventRepository.java // @Repository // public interface EventRepository extends JpaRepository<Event, Long> { // // /** // * Find all of the {@link Event}s related to a {@link Chaos} // * // * @param chaos the {@link Chaos} that {@link Event}s are related to // * @return a collection of {@link Event}s related to the {@link Chaos} // */ // @Transactional(readOnly = true) // List<Event> findByChaos(Chaos chaos); // // /** // * Find all of the {@link Event}s that occurred before an {@link Instant} // * // * @param instant the {@link Instant} to find {@link Event}s before // * @return a collection {@link Event}s that occurred before the {@link Instant} // */ // @Transactional(readOnly = true) // List<Event> findByExecutedAtBefore(Instant instant); // // } // Path: src/main/java/io/pivotal/strepsirrhini/chaosloris/destroyer/StandardDestroyerFactory.java import io.pivotal.strepsirrhini.chaosloris.data.ChaosRepository; import io.pivotal.strepsirrhini.chaosloris.data.EventRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; /* * Copyright 2015-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.pivotal.strepsirrhini.chaosloris.destroyer; @Component final class StandardDestroyerFactory implements DestroyerFactory { private final ChaosRepository chaosRepository;
private final EventRepository eventRepository;
strepsirrhini-army/chaos-loris
src/test/java/io/pivotal/strepsirrhini/chaosloris/destroyer/CloudFoundryPlatformTest.java
// Path: src/main/java/io/pivotal/strepsirrhini/chaosloris/data/Application.java // @Entity // public class Application { // // @Column(nullable = false, unique = true) // private UUID applicationId; // // @Column(nullable = false) // @GeneratedValue // @Id // @JsonIgnore // private Long id; // // /** // * Create a new instance // * // * @param applicationId the Cloud Foundry application id // */ // public Application(UUID applicationId) { // this.applicationId = applicationId; // } // // Application() { // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // Application that = (Application) o; // return Objects.equals(this.applicationId, that.applicationId) && // Objects.equals(this.id, that.id); // } // // /** // * Returns the application id // * // * @return the application id // */ // public UUID getApplicationId() { // return this.applicationId; // } // // /** // * Returns the id // * // * @return the id // */ // public Long getId() { // return this.id; // } // // /** // * Sets the id // * // * @param id the id // */ // public void setId(Long id) { // this.id = id; // } // // @Override // public int hashCode() { // return Objects.hash(this.applicationId, this.id); // } // // @Override // public String toString() { // return "Application{" + // "applicationId=" + this.applicationId + // ", id=" + this.id + // '}'; // } // // }
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import io.pivotal.strepsirrhini.chaosloris.data.Application; import org.cloudfoundry.client.CloudFoundryClient; import org.cloudfoundry.client.v2.applications.ApplicationsV2; import org.cloudfoundry.client.v2.applications.SummaryApplicationRequest; import org.cloudfoundry.client.v2.applications.SummaryApplicationResponse; import org.cloudfoundry.client.v2.applications.TerminateApplicationInstanceRequest; import org.junit.Before; import org.junit.Test; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; import java.util.UUID; import static org.mockito.Mockito.RETURNS_SMART_NULLS;
/* * Copyright 2015-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.pivotal.strepsirrhini.chaosloris.destroyer; public final class CloudFoundryPlatformTest { private final ApplicationsV2 applications = mock(ApplicationsV2.class, RETURNS_SMART_NULLS); private final CloudFoundryClient cloudFoundryClient = mock(CloudFoundryClient.class, RETURNS_SMART_NULLS); private final CloudFoundryPlatform platform = new CloudFoundryPlatform(this.cloudFoundryClient); @Test public void getInstanceCount() { UUID applicationId = UUID.randomUUID(); requestApplicationSummary(this.cloudFoundryClient, applicationId.toString(), Mono.just(SummaryApplicationResponse.builder() .instances(1) .build()));
// Path: src/main/java/io/pivotal/strepsirrhini/chaosloris/data/Application.java // @Entity // public class Application { // // @Column(nullable = false, unique = true) // private UUID applicationId; // // @Column(nullable = false) // @GeneratedValue // @Id // @JsonIgnore // private Long id; // // /** // * Create a new instance // * // * @param applicationId the Cloud Foundry application id // */ // public Application(UUID applicationId) { // this.applicationId = applicationId; // } // // Application() { // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // Application that = (Application) o; // return Objects.equals(this.applicationId, that.applicationId) && // Objects.equals(this.id, that.id); // } // // /** // * Returns the application id // * // * @return the application id // */ // public UUID getApplicationId() { // return this.applicationId; // } // // /** // * Returns the id // * // * @return the id // */ // public Long getId() { // return this.id; // } // // /** // * Sets the id // * // * @param id the id // */ // public void setId(Long id) { // this.id = id; // } // // @Override // public int hashCode() { // return Objects.hash(this.applicationId, this.id); // } // // @Override // public String toString() { // return "Application{" + // "applicationId=" + this.applicationId + // ", id=" + this.id + // '}'; // } // // } // Path: src/test/java/io/pivotal/strepsirrhini/chaosloris/destroyer/CloudFoundryPlatformTest.java import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import io.pivotal.strepsirrhini.chaosloris.data.Application; import org.cloudfoundry.client.CloudFoundryClient; import org.cloudfoundry.client.v2.applications.ApplicationsV2; import org.cloudfoundry.client.v2.applications.SummaryApplicationRequest; import org.cloudfoundry.client.v2.applications.SummaryApplicationResponse; import org.cloudfoundry.client.v2.applications.TerminateApplicationInstanceRequest; import org.junit.Before; import org.junit.Test; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; import java.util.UUID; import static org.mockito.Mockito.RETURNS_SMART_NULLS; /* * Copyright 2015-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.pivotal.strepsirrhini.chaosloris.destroyer; public final class CloudFoundryPlatformTest { private final ApplicationsV2 applications = mock(ApplicationsV2.class, RETURNS_SMART_NULLS); private final CloudFoundryClient cloudFoundryClient = mock(CloudFoundryClient.class, RETURNS_SMART_NULLS); private final CloudFoundryPlatform platform = new CloudFoundryPlatform(this.cloudFoundryClient); @Test public void getInstanceCount() { UUID applicationId = UUID.randomUUID(); requestApplicationSummary(this.cloudFoundryClient, applicationId.toString(), Mono.just(SummaryApplicationResponse.builder() .instances(1) .build()));
this.platform.getInstanceCount(new Application(applicationId))
strepsirrhini-army/chaos-loris
src/test/java/io/pivotal/strepsirrhini/chaosloris/docs/IndexDocumentation.java
// Path: src/main/java/io/pivotal/strepsirrhini/chaosloris/web/IndexController.java // @RestController // public class IndexController { // // @RequestMapping(method = GET, value = "/", produces = HAL_JSON_VALUE) // ResponseEntity index() { // ResourceSupport resource = new ResourceSupport(); // resource.add(linkTo(methodOn(IndexController.class).index()).withSelfRel()); // resource.add(linkTo(ApplicationController.class).withRel("applications")); // resource.add(linkTo(ChaosController.class).withRel("chaoses")); // resource.add(linkTo(EventController.class).withRel("events")); // resource.add(linkTo(ScheduleController.class).withRel("schedules")); // // return ResponseEntity.ok(resource); // } // // } // // Path: src/test/java/io/pivotal/strepsirrhini/chaosloris/docs/DocumentationUtilities.java // static RestDocumentationResultHandler document(Snippet... snippets) { // return MockMvcRestDocumentation.document("{method-name}", // preprocessRequest(prettyPrint()), // preprocessResponse(prettyPrint()), // snippets); // } // // Path: src/test/java/io/pivotal/strepsirrhini/chaosloris/docs/DocumentationUtilities.java // static LinksSnippet links(LinkDescriptor... descriptors) { // return HypermediaDocumentation.links( // linkWithRel("self").ignored()) // .and(descriptors); // }
import io.pivotal.strepsirrhini.chaosloris.web.IndexController; import org.cloudfoundry.client.CloudFoundryClient; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Answers; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.ImportAutoConfiguration; import org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration; import org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs; import org.springframework.boot.test.autoconfigure.restdocs.RestDocsMockMvcConfigurationCustomizer; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.context.TestConfiguration; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.restdocs.mockmvc.MockMvcRestDocumentationConfigurer; import org.springframework.restdocs.templates.TemplateFormats; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import static io.pivotal.strepsirrhini.chaosloris.docs.DocumentationUtilities.document; import static io.pivotal.strepsirrhini.chaosloris.docs.DocumentationUtilities.links; import static javax.servlet.RequestDispatcher.ERROR_MESSAGE; import static javax.servlet.RequestDispatcher.ERROR_REQUEST_URI; import static javax.servlet.RequestDispatcher.ERROR_STATUS_CODE; import static org.springframework.hateoas.MediaTypes.HAL_JSON; import static org.springframework.restdocs.hypermedia.HypermediaDocumentation.linkWithRel; import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.get; import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath; import static org.springframework.restdocs.payload.PayloadDocumentation.responseFields;
/* * Copyright 2015-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.pivotal.strepsirrhini.chaosloris.docs; @AutoConfigureRestDocs(outputDir = "target/generated-snippets", uriScheme = "https", uriHost = "chaos-loris", uriPort = 443) @RunWith(SpringRunner.class)
// Path: src/main/java/io/pivotal/strepsirrhini/chaosloris/web/IndexController.java // @RestController // public class IndexController { // // @RequestMapping(method = GET, value = "/", produces = HAL_JSON_VALUE) // ResponseEntity index() { // ResourceSupport resource = new ResourceSupport(); // resource.add(linkTo(methodOn(IndexController.class).index()).withSelfRel()); // resource.add(linkTo(ApplicationController.class).withRel("applications")); // resource.add(linkTo(ChaosController.class).withRel("chaoses")); // resource.add(linkTo(EventController.class).withRel("events")); // resource.add(linkTo(ScheduleController.class).withRel("schedules")); // // return ResponseEntity.ok(resource); // } // // } // // Path: src/test/java/io/pivotal/strepsirrhini/chaosloris/docs/DocumentationUtilities.java // static RestDocumentationResultHandler document(Snippet... snippets) { // return MockMvcRestDocumentation.document("{method-name}", // preprocessRequest(prettyPrint()), // preprocessResponse(prettyPrint()), // snippets); // } // // Path: src/test/java/io/pivotal/strepsirrhini/chaosloris/docs/DocumentationUtilities.java // static LinksSnippet links(LinkDescriptor... descriptors) { // return HypermediaDocumentation.links( // linkWithRel("self").ignored()) // .and(descriptors); // } // Path: src/test/java/io/pivotal/strepsirrhini/chaosloris/docs/IndexDocumentation.java import io.pivotal.strepsirrhini.chaosloris.web.IndexController; import org.cloudfoundry.client.CloudFoundryClient; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Answers; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.ImportAutoConfiguration; import org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration; import org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs; import org.springframework.boot.test.autoconfigure.restdocs.RestDocsMockMvcConfigurationCustomizer; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.context.TestConfiguration; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.restdocs.mockmvc.MockMvcRestDocumentationConfigurer; import org.springframework.restdocs.templates.TemplateFormats; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import static io.pivotal.strepsirrhini.chaosloris.docs.DocumentationUtilities.document; import static io.pivotal.strepsirrhini.chaosloris.docs.DocumentationUtilities.links; import static javax.servlet.RequestDispatcher.ERROR_MESSAGE; import static javax.servlet.RequestDispatcher.ERROR_REQUEST_URI; import static javax.servlet.RequestDispatcher.ERROR_STATUS_CODE; import static org.springframework.hateoas.MediaTypes.HAL_JSON; import static org.springframework.restdocs.hypermedia.HypermediaDocumentation.linkWithRel; import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.get; import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath; import static org.springframework.restdocs.payload.PayloadDocumentation.responseFields; /* * Copyright 2015-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.pivotal.strepsirrhini.chaosloris.docs; @AutoConfigureRestDocs(outputDir = "target/generated-snippets", uriScheme = "https", uriHost = "chaos-loris", uriPort = 443) @RunWith(SpringRunner.class)
@WebMvcTest(IndexController.class)
strepsirrhini-army/chaos-loris
src/test/java/io/pivotal/strepsirrhini/chaosloris/docs/IndexDocumentation.java
// Path: src/main/java/io/pivotal/strepsirrhini/chaosloris/web/IndexController.java // @RestController // public class IndexController { // // @RequestMapping(method = GET, value = "/", produces = HAL_JSON_VALUE) // ResponseEntity index() { // ResourceSupport resource = new ResourceSupport(); // resource.add(linkTo(methodOn(IndexController.class).index()).withSelfRel()); // resource.add(linkTo(ApplicationController.class).withRel("applications")); // resource.add(linkTo(ChaosController.class).withRel("chaoses")); // resource.add(linkTo(EventController.class).withRel("events")); // resource.add(linkTo(ScheduleController.class).withRel("schedules")); // // return ResponseEntity.ok(resource); // } // // } // // Path: src/test/java/io/pivotal/strepsirrhini/chaosloris/docs/DocumentationUtilities.java // static RestDocumentationResultHandler document(Snippet... snippets) { // return MockMvcRestDocumentation.document("{method-name}", // preprocessRequest(prettyPrint()), // preprocessResponse(prettyPrint()), // snippets); // } // // Path: src/test/java/io/pivotal/strepsirrhini/chaosloris/docs/DocumentationUtilities.java // static LinksSnippet links(LinkDescriptor... descriptors) { // return HypermediaDocumentation.links( // linkWithRel("self").ignored()) // .and(descriptors); // }
import io.pivotal.strepsirrhini.chaosloris.web.IndexController; import org.cloudfoundry.client.CloudFoundryClient; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Answers; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.ImportAutoConfiguration; import org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration; import org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs; import org.springframework.boot.test.autoconfigure.restdocs.RestDocsMockMvcConfigurationCustomizer; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.context.TestConfiguration; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.restdocs.mockmvc.MockMvcRestDocumentationConfigurer; import org.springframework.restdocs.templates.TemplateFormats; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import static io.pivotal.strepsirrhini.chaosloris.docs.DocumentationUtilities.document; import static io.pivotal.strepsirrhini.chaosloris.docs.DocumentationUtilities.links; import static javax.servlet.RequestDispatcher.ERROR_MESSAGE; import static javax.servlet.RequestDispatcher.ERROR_REQUEST_URI; import static javax.servlet.RequestDispatcher.ERROR_STATUS_CODE; import static org.springframework.hateoas.MediaTypes.HAL_JSON; import static org.springframework.restdocs.hypermedia.HypermediaDocumentation.linkWithRel; import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.get; import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath; import static org.springframework.restdocs.payload.PayloadDocumentation.responseFields;
/* * Copyright 2015-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.pivotal.strepsirrhini.chaosloris.docs; @AutoConfigureRestDocs(outputDir = "target/generated-snippets", uriScheme = "https", uriHost = "chaos-loris", uriPort = 443) @RunWith(SpringRunner.class) @WebMvcTest(IndexController.class) public class IndexDocumentation { @MockBean(answer = Answers.RETURNS_SMART_NULLS) private CloudFoundryClient cloudFoundryClient; @Autowired private MockMvc mockMvc; @Test public void error() throws Exception { this.mockMvc .perform(get("/error") .requestAttr(ERROR_STATUS_CODE, 400) .requestAttr(ERROR_REQUEST_URI, "/schedules") .requestAttr(ERROR_MESSAGE, "The schedule 'https://chaos-loris/schedules/123' does not exist"))
// Path: src/main/java/io/pivotal/strepsirrhini/chaosloris/web/IndexController.java // @RestController // public class IndexController { // // @RequestMapping(method = GET, value = "/", produces = HAL_JSON_VALUE) // ResponseEntity index() { // ResourceSupport resource = new ResourceSupport(); // resource.add(linkTo(methodOn(IndexController.class).index()).withSelfRel()); // resource.add(linkTo(ApplicationController.class).withRel("applications")); // resource.add(linkTo(ChaosController.class).withRel("chaoses")); // resource.add(linkTo(EventController.class).withRel("events")); // resource.add(linkTo(ScheduleController.class).withRel("schedules")); // // return ResponseEntity.ok(resource); // } // // } // // Path: src/test/java/io/pivotal/strepsirrhini/chaosloris/docs/DocumentationUtilities.java // static RestDocumentationResultHandler document(Snippet... snippets) { // return MockMvcRestDocumentation.document("{method-name}", // preprocessRequest(prettyPrint()), // preprocessResponse(prettyPrint()), // snippets); // } // // Path: src/test/java/io/pivotal/strepsirrhini/chaosloris/docs/DocumentationUtilities.java // static LinksSnippet links(LinkDescriptor... descriptors) { // return HypermediaDocumentation.links( // linkWithRel("self").ignored()) // .and(descriptors); // } // Path: src/test/java/io/pivotal/strepsirrhini/chaosloris/docs/IndexDocumentation.java import io.pivotal.strepsirrhini.chaosloris.web.IndexController; import org.cloudfoundry.client.CloudFoundryClient; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Answers; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.ImportAutoConfiguration; import org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration; import org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs; import org.springframework.boot.test.autoconfigure.restdocs.RestDocsMockMvcConfigurationCustomizer; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.context.TestConfiguration; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.restdocs.mockmvc.MockMvcRestDocumentationConfigurer; import org.springframework.restdocs.templates.TemplateFormats; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import static io.pivotal.strepsirrhini.chaosloris.docs.DocumentationUtilities.document; import static io.pivotal.strepsirrhini.chaosloris.docs.DocumentationUtilities.links; import static javax.servlet.RequestDispatcher.ERROR_MESSAGE; import static javax.servlet.RequestDispatcher.ERROR_REQUEST_URI; import static javax.servlet.RequestDispatcher.ERROR_STATUS_CODE; import static org.springframework.hateoas.MediaTypes.HAL_JSON; import static org.springframework.restdocs.hypermedia.HypermediaDocumentation.linkWithRel; import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.get; import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath; import static org.springframework.restdocs.payload.PayloadDocumentation.responseFields; /* * Copyright 2015-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.pivotal.strepsirrhini.chaosloris.docs; @AutoConfigureRestDocs(outputDir = "target/generated-snippets", uriScheme = "https", uriHost = "chaos-loris", uriPort = 443) @RunWith(SpringRunner.class) @WebMvcTest(IndexController.class) public class IndexDocumentation { @MockBean(answer = Answers.RETURNS_SMART_NULLS) private CloudFoundryClient cloudFoundryClient; @Autowired private MockMvc mockMvc; @Test public void error() throws Exception { this.mockMvc .perform(get("/error") .requestAttr(ERROR_STATUS_CODE, 400) .requestAttr(ERROR_REQUEST_URI, "/schedules") .requestAttr(ERROR_MESSAGE, "The schedule 'https://chaos-loris/schedules/123' does not exist"))
.andDo(document(
strepsirrhini-army/chaos-loris
src/test/java/io/pivotal/strepsirrhini/chaosloris/docs/IndexDocumentation.java
// Path: src/main/java/io/pivotal/strepsirrhini/chaosloris/web/IndexController.java // @RestController // public class IndexController { // // @RequestMapping(method = GET, value = "/", produces = HAL_JSON_VALUE) // ResponseEntity index() { // ResourceSupport resource = new ResourceSupport(); // resource.add(linkTo(methodOn(IndexController.class).index()).withSelfRel()); // resource.add(linkTo(ApplicationController.class).withRel("applications")); // resource.add(linkTo(ChaosController.class).withRel("chaoses")); // resource.add(linkTo(EventController.class).withRel("events")); // resource.add(linkTo(ScheduleController.class).withRel("schedules")); // // return ResponseEntity.ok(resource); // } // // } // // Path: src/test/java/io/pivotal/strepsirrhini/chaosloris/docs/DocumentationUtilities.java // static RestDocumentationResultHandler document(Snippet... snippets) { // return MockMvcRestDocumentation.document("{method-name}", // preprocessRequest(prettyPrint()), // preprocessResponse(prettyPrint()), // snippets); // } // // Path: src/test/java/io/pivotal/strepsirrhini/chaosloris/docs/DocumentationUtilities.java // static LinksSnippet links(LinkDescriptor... descriptors) { // return HypermediaDocumentation.links( // linkWithRel("self").ignored()) // .and(descriptors); // }
import io.pivotal.strepsirrhini.chaosloris.web.IndexController; import org.cloudfoundry.client.CloudFoundryClient; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Answers; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.ImportAutoConfiguration; import org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration; import org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs; import org.springframework.boot.test.autoconfigure.restdocs.RestDocsMockMvcConfigurationCustomizer; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.context.TestConfiguration; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.restdocs.mockmvc.MockMvcRestDocumentationConfigurer; import org.springframework.restdocs.templates.TemplateFormats; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import static io.pivotal.strepsirrhini.chaosloris.docs.DocumentationUtilities.document; import static io.pivotal.strepsirrhini.chaosloris.docs.DocumentationUtilities.links; import static javax.servlet.RequestDispatcher.ERROR_MESSAGE; import static javax.servlet.RequestDispatcher.ERROR_REQUEST_URI; import static javax.servlet.RequestDispatcher.ERROR_STATUS_CODE; import static org.springframework.hateoas.MediaTypes.HAL_JSON; import static org.springframework.restdocs.hypermedia.HypermediaDocumentation.linkWithRel; import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.get; import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath; import static org.springframework.restdocs.payload.PayloadDocumentation.responseFields;
/* * Copyright 2015-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.pivotal.strepsirrhini.chaosloris.docs; @AutoConfigureRestDocs(outputDir = "target/generated-snippets", uriScheme = "https", uriHost = "chaos-loris", uriPort = 443) @RunWith(SpringRunner.class) @WebMvcTest(IndexController.class) public class IndexDocumentation { @MockBean(answer = Answers.RETURNS_SMART_NULLS) private CloudFoundryClient cloudFoundryClient; @Autowired private MockMvc mockMvc; @Test public void error() throws Exception { this.mockMvc .perform(get("/error") .requestAttr(ERROR_STATUS_CODE, 400) .requestAttr(ERROR_REQUEST_URI, "/schedules") .requestAttr(ERROR_MESSAGE, "The schedule 'https://chaos-loris/schedules/123' does not exist")) .andDo(document( responseFields( fieldWithPath("error").description("The HTTP error that occurred, e.g. `Bad Request`"), fieldWithPath("message").description("A description of the cause of the error"), fieldWithPath("path").description("The path to which the request was made"), fieldWithPath("status").description("The HTTP status code, e.g. `400`"), fieldWithPath("timestamp").description("The time, in milliseconds, at which the error occurred")))); } @Test public void index() throws Exception { this.mockMvc.perform(get("/").accept(HAL_JSON)) .andDo(document(
// Path: src/main/java/io/pivotal/strepsirrhini/chaosloris/web/IndexController.java // @RestController // public class IndexController { // // @RequestMapping(method = GET, value = "/", produces = HAL_JSON_VALUE) // ResponseEntity index() { // ResourceSupport resource = new ResourceSupport(); // resource.add(linkTo(methodOn(IndexController.class).index()).withSelfRel()); // resource.add(linkTo(ApplicationController.class).withRel("applications")); // resource.add(linkTo(ChaosController.class).withRel("chaoses")); // resource.add(linkTo(EventController.class).withRel("events")); // resource.add(linkTo(ScheduleController.class).withRel("schedules")); // // return ResponseEntity.ok(resource); // } // // } // // Path: src/test/java/io/pivotal/strepsirrhini/chaosloris/docs/DocumentationUtilities.java // static RestDocumentationResultHandler document(Snippet... snippets) { // return MockMvcRestDocumentation.document("{method-name}", // preprocessRequest(prettyPrint()), // preprocessResponse(prettyPrint()), // snippets); // } // // Path: src/test/java/io/pivotal/strepsirrhini/chaosloris/docs/DocumentationUtilities.java // static LinksSnippet links(LinkDescriptor... descriptors) { // return HypermediaDocumentation.links( // linkWithRel("self").ignored()) // .and(descriptors); // } // Path: src/test/java/io/pivotal/strepsirrhini/chaosloris/docs/IndexDocumentation.java import io.pivotal.strepsirrhini.chaosloris.web.IndexController; import org.cloudfoundry.client.CloudFoundryClient; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Answers; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.ImportAutoConfiguration; import org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration; import org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs; import org.springframework.boot.test.autoconfigure.restdocs.RestDocsMockMvcConfigurationCustomizer; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.context.TestConfiguration; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.restdocs.mockmvc.MockMvcRestDocumentationConfigurer; import org.springframework.restdocs.templates.TemplateFormats; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import static io.pivotal.strepsirrhini.chaosloris.docs.DocumentationUtilities.document; import static io.pivotal.strepsirrhini.chaosloris.docs.DocumentationUtilities.links; import static javax.servlet.RequestDispatcher.ERROR_MESSAGE; import static javax.servlet.RequestDispatcher.ERROR_REQUEST_URI; import static javax.servlet.RequestDispatcher.ERROR_STATUS_CODE; import static org.springframework.hateoas.MediaTypes.HAL_JSON; import static org.springframework.restdocs.hypermedia.HypermediaDocumentation.linkWithRel; import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.get; import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath; import static org.springframework.restdocs.payload.PayloadDocumentation.responseFields; /* * Copyright 2015-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.pivotal.strepsirrhini.chaosloris.docs; @AutoConfigureRestDocs(outputDir = "target/generated-snippets", uriScheme = "https", uriHost = "chaos-loris", uriPort = 443) @RunWith(SpringRunner.class) @WebMvcTest(IndexController.class) public class IndexDocumentation { @MockBean(answer = Answers.RETURNS_SMART_NULLS) private CloudFoundryClient cloudFoundryClient; @Autowired private MockMvc mockMvc; @Test public void error() throws Exception { this.mockMvc .perform(get("/error") .requestAttr(ERROR_STATUS_CODE, 400) .requestAttr(ERROR_REQUEST_URI, "/schedules") .requestAttr(ERROR_MESSAGE, "The schedule 'https://chaos-loris/schedules/123' does not exist")) .andDo(document( responseFields( fieldWithPath("error").description("The HTTP error that occurred, e.g. `Bad Request`"), fieldWithPath("message").description("A description of the cause of the error"), fieldWithPath("path").description("The path to which the request was made"), fieldWithPath("status").description("The HTTP status code, e.g. `400`"), fieldWithPath("timestamp").description("The time, in milliseconds, at which the error occurred")))); } @Test public void index() throws Exception { this.mockMvc.perform(get("/").accept(HAL_JSON)) .andDo(document(
links(
strepsirrhini-army/chaos-loris
src/main/java/io/pivotal/strepsirrhini/chaosloris/destroyer/RandomFateEngine.java
// Path: src/main/java/io/pivotal/strepsirrhini/chaosloris/data/Chaos.java // @Entity // @Table(uniqueConstraints = @UniqueConstraint(columnNames = {"application_id", "schedule_id"})) // public class Chaos { // // @JoinColumn(nullable = false) // @JsonIgnore // @ManyToOne // private Application application; // // @Column(nullable = false) // @GeneratedValue // @Id // @JsonIgnore // private Long id; // // @Column(nullable = false) // private Double probability; // // @JoinColumn(nullable = false) // @JsonIgnore // @ManyToOne // private Schedule schedule; // // /** // * Create a new instance // * // * @param application the application to apply chaos to // * @param probability the probability of an instance being destroyed // * @param schedule the schedule to apply chaos on // */ // public Chaos(Application application, Double probability, Schedule schedule) { // this.application = application; // this.probability = probability; // this.schedule = schedule; // } // // Chaos() { // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // Chaos chaos = (Chaos) o; // return Objects.equals(this.application, chaos.application) && // Objects.equals(this.id, chaos.id) && // Objects.equals(this.probability, chaos.probability) && // Objects.equals(this.schedule, chaos.schedule); // } // // /** // * Returns the application // * // * @return the application // */ // public Application getApplication() { // return this.application; // } // // /** // * Returns the id // * // * @return the id // */ // public Long getId() { // return this.id; // } // // /** // * Sets the id // * // * @param id the id // */ // public void setId(Long id) { // this.id = id; // } // // /** // * Returns the probability // * // * @return the probability // */ // public Double getProbability() { // return this.probability; // } // // /** // * Sets the probability // * // * @param probability the probability // */ // public void setProbability(Double probability) { // this.probability = probability; // } // // /** // * Returns the schedule // * // * @return the schedule // */ // public Schedule getSchedule() { // return this.schedule; // } // // @Override // public int hashCode() { // return Objects.hash(this.application, this.id, this.probability, this.schedule); // } // // @Override // public String toString() { // return "Chaos{" + // "application=" + this.application + // ", id=" + this.id + // ", probability=" + this.probability + // ", schedule=" + this.schedule + // '}'; // } // // }
import io.pivotal.strepsirrhini.chaosloris.data.Chaos; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.Random; import static io.pivotal.strepsirrhini.chaosloris.destroyer.FateEngine.Fate.THUMBS_DOWN; import static io.pivotal.strepsirrhini.chaosloris.destroyer.FateEngine.Fate.THUMBS_UP;
/* * Copyright 2015-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.pivotal.strepsirrhini.chaosloris.destroyer; @Component final class RandomFateEngine implements FateEngine { private final Random random; @Autowired RandomFateEngine(Random random) { this.random = random; } @Override
// Path: src/main/java/io/pivotal/strepsirrhini/chaosloris/data/Chaos.java // @Entity // @Table(uniqueConstraints = @UniqueConstraint(columnNames = {"application_id", "schedule_id"})) // public class Chaos { // // @JoinColumn(nullable = false) // @JsonIgnore // @ManyToOne // private Application application; // // @Column(nullable = false) // @GeneratedValue // @Id // @JsonIgnore // private Long id; // // @Column(nullable = false) // private Double probability; // // @JoinColumn(nullable = false) // @JsonIgnore // @ManyToOne // private Schedule schedule; // // /** // * Create a new instance // * // * @param application the application to apply chaos to // * @param probability the probability of an instance being destroyed // * @param schedule the schedule to apply chaos on // */ // public Chaos(Application application, Double probability, Schedule schedule) { // this.application = application; // this.probability = probability; // this.schedule = schedule; // } // // Chaos() { // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // Chaos chaos = (Chaos) o; // return Objects.equals(this.application, chaos.application) && // Objects.equals(this.id, chaos.id) && // Objects.equals(this.probability, chaos.probability) && // Objects.equals(this.schedule, chaos.schedule); // } // // /** // * Returns the application // * // * @return the application // */ // public Application getApplication() { // return this.application; // } // // /** // * Returns the id // * // * @return the id // */ // public Long getId() { // return this.id; // } // // /** // * Sets the id // * // * @param id the id // */ // public void setId(Long id) { // this.id = id; // } // // /** // * Returns the probability // * // * @return the probability // */ // public Double getProbability() { // return this.probability; // } // // /** // * Sets the probability // * // * @param probability the probability // */ // public void setProbability(Double probability) { // this.probability = probability; // } // // /** // * Returns the schedule // * // * @return the schedule // */ // public Schedule getSchedule() { // return this.schedule; // } // // @Override // public int hashCode() { // return Objects.hash(this.application, this.id, this.probability, this.schedule); // } // // @Override // public String toString() { // return "Chaos{" + // "application=" + this.application + // ", id=" + this.id + // ", probability=" + this.probability + // ", schedule=" + this.schedule + // '}'; // } // // } // Path: src/main/java/io/pivotal/strepsirrhini/chaosloris/destroyer/RandomFateEngine.java import io.pivotal.strepsirrhini.chaosloris.data.Chaos; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.Random; import static io.pivotal.strepsirrhini.chaosloris.destroyer.FateEngine.Fate.THUMBS_DOWN; import static io.pivotal.strepsirrhini.chaosloris.destroyer.FateEngine.Fate.THUMBS_UP; /* * Copyright 2015-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.pivotal.strepsirrhini.chaosloris.destroyer; @Component final class RandomFateEngine implements FateEngine { private final Random random; @Autowired RandomFateEngine(Random random) { this.random = random; } @Override
public Fate getFate(Chaos chaos) {
strepsirrhini-army/chaos-loris
src/main/java/io/pivotal/strepsirrhini/chaosloris/web/ChaosResourceAssembler.java
// Path: src/main/java/io/pivotal/strepsirrhini/chaosloris/data/Chaos.java // @Entity // @Table(uniqueConstraints = @UniqueConstraint(columnNames = {"application_id", "schedule_id"})) // public class Chaos { // // @JoinColumn(nullable = false) // @JsonIgnore // @ManyToOne // private Application application; // // @Column(nullable = false) // @GeneratedValue // @Id // @JsonIgnore // private Long id; // // @Column(nullable = false) // private Double probability; // // @JoinColumn(nullable = false) // @JsonIgnore // @ManyToOne // private Schedule schedule; // // /** // * Create a new instance // * // * @param application the application to apply chaos to // * @param probability the probability of an instance being destroyed // * @param schedule the schedule to apply chaos on // */ // public Chaos(Application application, Double probability, Schedule schedule) { // this.application = application; // this.probability = probability; // this.schedule = schedule; // } // // Chaos() { // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // Chaos chaos = (Chaos) o; // return Objects.equals(this.application, chaos.application) && // Objects.equals(this.id, chaos.id) && // Objects.equals(this.probability, chaos.probability) && // Objects.equals(this.schedule, chaos.schedule); // } // // /** // * Returns the application // * // * @return the application // */ // public Application getApplication() { // return this.application; // } // // /** // * Returns the id // * // * @return the id // */ // public Long getId() { // return this.id; // } // // /** // * Sets the id // * // * @param id the id // */ // public void setId(Long id) { // this.id = id; // } // // /** // * Returns the probability // * // * @return the probability // */ // public Double getProbability() { // return this.probability; // } // // /** // * Sets the probability // * // * @param probability the probability // */ // public void setProbability(Double probability) { // this.probability = probability; // } // // /** // * Returns the schedule // * // * @return the schedule // */ // public Schedule getSchedule() { // return this.schedule; // } // // @Override // public int hashCode() { // return Objects.hash(this.application, this.id, this.probability, this.schedule); // } // // @Override // public String toString() { // return "Chaos{" + // "application=" + this.application + // ", id=" + this.id + // ", probability=" + this.probability + // ", schedule=" + this.schedule + // '}'; // } // // } // // Path: src/main/java/io/pivotal/strepsirrhini/chaosloris/data/EventRepository.java // @Repository // public interface EventRepository extends JpaRepository<Event, Long> { // // /** // * Find all of the {@link Event}s related to a {@link Chaos} // * // * @param chaos the {@link Chaos} that {@link Event}s are related to // * @return a collection of {@link Event}s related to the {@link Chaos} // */ // @Transactional(readOnly = true) // List<Event> findByChaos(Chaos chaos); // // /** // * Find all of the {@link Event}s that occurred before an {@link Instant} // * // * @param instant the {@link Instant} to find {@link Event}s before // * @return a collection {@link Event}s that occurred before the {@link Instant} // */ // @Transactional(readOnly = true) // List<Event> findByExecutedAtBefore(Instant instant); // // }
import io.pivotal.strepsirrhini.chaosloris.data.Chaos; import io.pivotal.strepsirrhini.chaosloris.data.EventRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.hateoas.Resource; import org.springframework.hateoas.mvc.ResourceAssemblerSupport; import org.springframework.stereotype.Component; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn;
/* * Copyright 2015-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.pivotal.strepsirrhini.chaosloris.web; @Component public final class ChaosResourceAssembler extends ResourceAssemblerSupport<Chaos, ChaosResourceAssembler.ChaosResource> {
// Path: src/main/java/io/pivotal/strepsirrhini/chaosloris/data/Chaos.java // @Entity // @Table(uniqueConstraints = @UniqueConstraint(columnNames = {"application_id", "schedule_id"})) // public class Chaos { // // @JoinColumn(nullable = false) // @JsonIgnore // @ManyToOne // private Application application; // // @Column(nullable = false) // @GeneratedValue // @Id // @JsonIgnore // private Long id; // // @Column(nullable = false) // private Double probability; // // @JoinColumn(nullable = false) // @JsonIgnore // @ManyToOne // private Schedule schedule; // // /** // * Create a new instance // * // * @param application the application to apply chaos to // * @param probability the probability of an instance being destroyed // * @param schedule the schedule to apply chaos on // */ // public Chaos(Application application, Double probability, Schedule schedule) { // this.application = application; // this.probability = probability; // this.schedule = schedule; // } // // Chaos() { // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // Chaos chaos = (Chaos) o; // return Objects.equals(this.application, chaos.application) && // Objects.equals(this.id, chaos.id) && // Objects.equals(this.probability, chaos.probability) && // Objects.equals(this.schedule, chaos.schedule); // } // // /** // * Returns the application // * // * @return the application // */ // public Application getApplication() { // return this.application; // } // // /** // * Returns the id // * // * @return the id // */ // public Long getId() { // return this.id; // } // // /** // * Sets the id // * // * @param id the id // */ // public void setId(Long id) { // this.id = id; // } // // /** // * Returns the probability // * // * @return the probability // */ // public Double getProbability() { // return this.probability; // } // // /** // * Sets the probability // * // * @param probability the probability // */ // public void setProbability(Double probability) { // this.probability = probability; // } // // /** // * Returns the schedule // * // * @return the schedule // */ // public Schedule getSchedule() { // return this.schedule; // } // // @Override // public int hashCode() { // return Objects.hash(this.application, this.id, this.probability, this.schedule); // } // // @Override // public String toString() { // return "Chaos{" + // "application=" + this.application + // ", id=" + this.id + // ", probability=" + this.probability + // ", schedule=" + this.schedule + // '}'; // } // // } // // Path: src/main/java/io/pivotal/strepsirrhini/chaosloris/data/EventRepository.java // @Repository // public interface EventRepository extends JpaRepository<Event, Long> { // // /** // * Find all of the {@link Event}s related to a {@link Chaos} // * // * @param chaos the {@link Chaos} that {@link Event}s are related to // * @return a collection of {@link Event}s related to the {@link Chaos} // */ // @Transactional(readOnly = true) // List<Event> findByChaos(Chaos chaos); // // /** // * Find all of the {@link Event}s that occurred before an {@link Instant} // * // * @param instant the {@link Instant} to find {@link Event}s before // * @return a collection {@link Event}s that occurred before the {@link Instant} // */ // @Transactional(readOnly = true) // List<Event> findByExecutedAtBefore(Instant instant); // // } // Path: src/main/java/io/pivotal/strepsirrhini/chaosloris/web/ChaosResourceAssembler.java import io.pivotal.strepsirrhini.chaosloris.data.Chaos; import io.pivotal.strepsirrhini.chaosloris.data.EventRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.hateoas.Resource; import org.springframework.hateoas.mvc.ResourceAssemblerSupport; import org.springframework.stereotype.Component; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn; /* * Copyright 2015-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.pivotal.strepsirrhini.chaosloris.web; @Component public final class ChaosResourceAssembler extends ResourceAssemblerSupport<Chaos, ChaosResourceAssembler.ChaosResource> {
private final EventRepository eventRepository;
strepsirrhini-army/chaos-loris
src/main/java/io/pivotal/strepsirrhini/chaosloris/reaper/EventReaper.java
// Path: src/main/java/io/pivotal/strepsirrhini/chaosloris/data/Event.java // @Entity // public class Event { // // @JoinColumn(nullable = false) // @ManyToOne // @JsonIgnore // private Chaos chaos; // // @Column(nullable = false) // private Instant executedAt; // // @Column(nullable = false) // @GeneratedValue // @Id // @JsonIgnore // private Long id; // // @Column(nullable = false) // @ElementCollection // @OrderBy // private List<Integer> terminatedInstances; // // @Column(nullable = false) // private Integer totalInstanceCount; // // public Event(Chaos chaos, Instant executedAt, List<Integer> terminatedInstances, Integer totalInstanceCount) { // this.chaos = chaos; // this.executedAt = executedAt; // this.terminatedInstances = terminatedInstances; // this.totalInstanceCount = totalInstanceCount; // } // // Event() { // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // Event event = (Event) o; // return Objects.equals(this.chaos, event.chaos) && // Objects.equals(this.executedAt, event.executedAt) && // Objects.equals(this.id, event.id) && // Objects.equals(this.terminatedInstances, event.terminatedInstances) && // Objects.equals(this.totalInstanceCount, event.totalInstanceCount); // } // // /** // * Returns the chaos // * // * @return the chaos // */ // public Chaos getChaos() { // return this.chaos; // } // // /** // * Returns when the event was executed // * // * @return when the event was executed // */ // public Instant getExecutedAt() { // return this.executedAt; // } // // /** // * Returns the id // * // * @return the id // */ // public Long getId() { // return this.id; // } // // /** // * Sets the id // * // * @param id the id // */ // public void setId(Long id) { // this.id = id; // } // // /** // * Returns the number of instances terminated // * // * @return the number of instances terminated // */ // public int getTerminatedInstanceCount() { // return this.getTerminatedInstances().size(); // } // // /** // * Returns the terminated instances // * // * @return the terminated instances // */ // public List<Integer> getTerminatedInstances() { // return this.terminatedInstances; // } // // /** // * Returns the total instance count // * // * @return the total instance count // */ // public Integer getTotalInstanceCount() { // return this.totalInstanceCount; // } // // @Override // public int hashCode() { // return Objects.hash(this.chaos, this.executedAt, this.id, this.terminatedInstances, this.totalInstanceCount); // } // // @Override // public String toString() { // return "Event{" + // "chaos=" + this.chaos + // ", executedAt=" + this.executedAt + // ", id=" + this.id + // ", terminatedInstances=" + this.terminatedInstances + // ", totalInstanceCount=" + this.totalInstanceCount + // '}'; // } // // } // // Path: src/main/java/io/pivotal/strepsirrhini/chaosloris/data/EventRepository.java // @Repository // public interface EventRepository extends JpaRepository<Event, Long> { // // /** // * Find all of the {@link Event}s related to a {@link Chaos} // * // * @param chaos the {@link Chaos} that {@link Event}s are related to // * @return a collection of {@link Event}s related to the {@link Chaos} // */ // @Transactional(readOnly = true) // List<Event> findByChaos(Chaos chaos); // // /** // * Find all of the {@link Event}s that occurred before an {@link Instant} // * // * @param instant the {@link Instant} to find {@link Event}s before // * @return a collection {@link Event}s that occurred before the {@link Instant} // */ // @Transactional(readOnly = true) // List<Event> findByExecutedAtBefore(Instant instant); // // }
import io.pivotal.strepsirrhini.chaosloris.data.Event; import io.pivotal.strepsirrhini.chaosloris.data.EventRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import java.time.Instant; import java.time.Period;
/* * Copyright 2015-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.pivotal.strepsirrhini.chaosloris.reaper; @Component class EventReaper { private final Logger logger = LoggerFactory.getLogger(this.getClass());
// Path: src/main/java/io/pivotal/strepsirrhini/chaosloris/data/Event.java // @Entity // public class Event { // // @JoinColumn(nullable = false) // @ManyToOne // @JsonIgnore // private Chaos chaos; // // @Column(nullable = false) // private Instant executedAt; // // @Column(nullable = false) // @GeneratedValue // @Id // @JsonIgnore // private Long id; // // @Column(nullable = false) // @ElementCollection // @OrderBy // private List<Integer> terminatedInstances; // // @Column(nullable = false) // private Integer totalInstanceCount; // // public Event(Chaos chaos, Instant executedAt, List<Integer> terminatedInstances, Integer totalInstanceCount) { // this.chaos = chaos; // this.executedAt = executedAt; // this.terminatedInstances = terminatedInstances; // this.totalInstanceCount = totalInstanceCount; // } // // Event() { // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // Event event = (Event) o; // return Objects.equals(this.chaos, event.chaos) && // Objects.equals(this.executedAt, event.executedAt) && // Objects.equals(this.id, event.id) && // Objects.equals(this.terminatedInstances, event.terminatedInstances) && // Objects.equals(this.totalInstanceCount, event.totalInstanceCount); // } // // /** // * Returns the chaos // * // * @return the chaos // */ // public Chaos getChaos() { // return this.chaos; // } // // /** // * Returns when the event was executed // * // * @return when the event was executed // */ // public Instant getExecutedAt() { // return this.executedAt; // } // // /** // * Returns the id // * // * @return the id // */ // public Long getId() { // return this.id; // } // // /** // * Sets the id // * // * @param id the id // */ // public void setId(Long id) { // this.id = id; // } // // /** // * Returns the number of instances terminated // * // * @return the number of instances terminated // */ // public int getTerminatedInstanceCount() { // return this.getTerminatedInstances().size(); // } // // /** // * Returns the terminated instances // * // * @return the terminated instances // */ // public List<Integer> getTerminatedInstances() { // return this.terminatedInstances; // } // // /** // * Returns the total instance count // * // * @return the total instance count // */ // public Integer getTotalInstanceCount() { // return this.totalInstanceCount; // } // // @Override // public int hashCode() { // return Objects.hash(this.chaos, this.executedAt, this.id, this.terminatedInstances, this.totalInstanceCount); // } // // @Override // public String toString() { // return "Event{" + // "chaos=" + this.chaos + // ", executedAt=" + this.executedAt + // ", id=" + this.id + // ", terminatedInstances=" + this.terminatedInstances + // ", totalInstanceCount=" + this.totalInstanceCount + // '}'; // } // // } // // Path: src/main/java/io/pivotal/strepsirrhini/chaosloris/data/EventRepository.java // @Repository // public interface EventRepository extends JpaRepository<Event, Long> { // // /** // * Find all of the {@link Event}s related to a {@link Chaos} // * // * @param chaos the {@link Chaos} that {@link Event}s are related to // * @return a collection of {@link Event}s related to the {@link Chaos} // */ // @Transactional(readOnly = true) // List<Event> findByChaos(Chaos chaos); // // /** // * Find all of the {@link Event}s that occurred before an {@link Instant} // * // * @param instant the {@link Instant} to find {@link Event}s before // * @return a collection {@link Event}s that occurred before the {@link Instant} // */ // @Transactional(readOnly = true) // List<Event> findByExecutedAtBefore(Instant instant); // // } // Path: src/main/java/io/pivotal/strepsirrhini/chaosloris/reaper/EventReaper.java import io.pivotal.strepsirrhini.chaosloris.data.Event; import io.pivotal.strepsirrhini.chaosloris.data.EventRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import java.time.Instant; import java.time.Period; /* * Copyright 2015-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.pivotal.strepsirrhini.chaosloris.reaper; @Component class EventReaper { private final Logger logger = LoggerFactory.getLogger(this.getClass());
private final EventRepository eventRepository;
strepsirrhini-army/chaos-loris
src/main/java/io/pivotal/strepsirrhini/chaosloris/web/ScheduleResourceAssembler.java
// Path: src/main/java/io/pivotal/strepsirrhini/chaosloris/data/ChaosRepository.java // @Repository // public interface ChaosRepository extends JpaRepository<Chaos, Long> { // // /** // * Find all of the {@link Chaos}es related to an {@link Application} // * // * @param application the {@link Application} that {@link Chaos}es are related to // * @return a collection of {@link Chaos}es related to the {@link Application} // */ // @Transactional(readOnly = true) // List<Chaos> findByApplication(Application application); // // /** // * Find all of the {@link Chaos}es related to a {@link Schedule} // * // * @param schedule the {@link Schedule} that {@link Chaos}es are related to // * @return a collection of {@link Chaos}es related to the {@link Schedule} // */ // @Transactional(readOnly = true) // List<Chaos> findBySchedule(Schedule schedule); // // /** // * Find all of the {@link Chaos}es related to a {@link Schedule} // * // * @param id the id of {@link Schedule} that {@link Chaos}es are related to // * @return a collection of {@link Chaos}es related to the {@link Schedule} // */ // @Transactional(readOnly = true) // List<Chaos> findByScheduleId(Long id); // // } // // Path: src/main/java/io/pivotal/strepsirrhini/chaosloris/data/Schedule.java // @Entity // public class Schedule { // // @Column(nullable = false) // private String expression; // // @Column(nullable = false) // @GeneratedValue // @Id // @JsonIgnore // private Long id; // // @Column(nullable = false, unique = true) // private String name; // // /** // * Create a new instance // * // * @param expression the cron expression of the schedule // * @param name the name of the schedule // */ // public Schedule(String expression, String name) { // this.name = name; // this.expression = expression; // } // // Schedule() { // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // Schedule schedule = (Schedule) o; // return Objects.equals(this.expression, schedule.expression) && // Objects.equals(this.id, schedule.id) && // Objects.equals(this.name, schedule.name); // } // // /** // * Returns the expression // * // * @return the expression // */ // public String getExpression() { // return this.expression; // } // // /** // * Sets the expression // * // * @param expression the expression // */ // public void setExpression(String expression) { // this.expression = expression; // } // // /** // * Returns the id // * // * @return the id // */ // public Long getId() { // return this.id; // } // // /** // * Sets the id // * // * @param id the id // */ // public void setId(Long id) { // this.id = id; // } // // /** // * Returns the name // * // * @return the name // */ // public String getName() { // return this.name; // } // // /** // * Sets the name // * // * @param name the name // */ // public void setName(String name) { // this.name = name; // } // // @Override // public int hashCode() { // return Objects.hash(this.expression, this.id, this.name); // } // // @Override // public String toString() { // return "Schedule{" + // "expression='" + this.expression + '\'' + // ", id=" + this.id + // ", name='" + this.name + '\'' + // '}'; // } // // }
import io.pivotal.strepsirrhini.chaosloris.data.ChaosRepository; import io.pivotal.strepsirrhini.chaosloris.data.Schedule; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.hateoas.Resource; import org.springframework.hateoas.mvc.ResourceAssemblerSupport; import org.springframework.stereotype.Component; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn;
/* * Copyright 2015-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.pivotal.strepsirrhini.chaosloris.web; @Component public final class ScheduleResourceAssembler extends ResourceAssemblerSupport<Schedule, ScheduleResourceAssembler.ScheduleResource> {
// Path: src/main/java/io/pivotal/strepsirrhini/chaosloris/data/ChaosRepository.java // @Repository // public interface ChaosRepository extends JpaRepository<Chaos, Long> { // // /** // * Find all of the {@link Chaos}es related to an {@link Application} // * // * @param application the {@link Application} that {@link Chaos}es are related to // * @return a collection of {@link Chaos}es related to the {@link Application} // */ // @Transactional(readOnly = true) // List<Chaos> findByApplication(Application application); // // /** // * Find all of the {@link Chaos}es related to a {@link Schedule} // * // * @param schedule the {@link Schedule} that {@link Chaos}es are related to // * @return a collection of {@link Chaos}es related to the {@link Schedule} // */ // @Transactional(readOnly = true) // List<Chaos> findBySchedule(Schedule schedule); // // /** // * Find all of the {@link Chaos}es related to a {@link Schedule} // * // * @param id the id of {@link Schedule} that {@link Chaos}es are related to // * @return a collection of {@link Chaos}es related to the {@link Schedule} // */ // @Transactional(readOnly = true) // List<Chaos> findByScheduleId(Long id); // // } // // Path: src/main/java/io/pivotal/strepsirrhini/chaosloris/data/Schedule.java // @Entity // public class Schedule { // // @Column(nullable = false) // private String expression; // // @Column(nullable = false) // @GeneratedValue // @Id // @JsonIgnore // private Long id; // // @Column(nullable = false, unique = true) // private String name; // // /** // * Create a new instance // * // * @param expression the cron expression of the schedule // * @param name the name of the schedule // */ // public Schedule(String expression, String name) { // this.name = name; // this.expression = expression; // } // // Schedule() { // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // Schedule schedule = (Schedule) o; // return Objects.equals(this.expression, schedule.expression) && // Objects.equals(this.id, schedule.id) && // Objects.equals(this.name, schedule.name); // } // // /** // * Returns the expression // * // * @return the expression // */ // public String getExpression() { // return this.expression; // } // // /** // * Sets the expression // * // * @param expression the expression // */ // public void setExpression(String expression) { // this.expression = expression; // } // // /** // * Returns the id // * // * @return the id // */ // public Long getId() { // return this.id; // } // // /** // * Sets the id // * // * @param id the id // */ // public void setId(Long id) { // this.id = id; // } // // /** // * Returns the name // * // * @return the name // */ // public String getName() { // return this.name; // } // // /** // * Sets the name // * // * @param name the name // */ // public void setName(String name) { // this.name = name; // } // // @Override // public int hashCode() { // return Objects.hash(this.expression, this.id, this.name); // } // // @Override // public String toString() { // return "Schedule{" + // "expression='" + this.expression + '\'' + // ", id=" + this.id + // ", name='" + this.name + '\'' + // '}'; // } // // } // Path: src/main/java/io/pivotal/strepsirrhini/chaosloris/web/ScheduleResourceAssembler.java import io.pivotal.strepsirrhini.chaosloris.data.ChaosRepository; import io.pivotal.strepsirrhini.chaosloris.data.Schedule; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.hateoas.Resource; import org.springframework.hateoas.mvc.ResourceAssemblerSupport; import org.springframework.stereotype.Component; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn; /* * Copyright 2015-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.pivotal.strepsirrhini.chaosloris.web; @Component public final class ScheduleResourceAssembler extends ResourceAssemblerSupport<Schedule, ScheduleResourceAssembler.ScheduleResource> {
private final ChaosRepository chaosRepository;
strepsirrhini-army/chaos-loris
src/main/java/io/pivotal/strepsirrhini/chaosloris/web/ApplicationResourceAssembler.java
// Path: src/main/java/io/pivotal/strepsirrhini/chaosloris/data/Application.java // @Entity // public class Application { // // @Column(nullable = false, unique = true) // private UUID applicationId; // // @Column(nullable = false) // @GeneratedValue // @Id // @JsonIgnore // private Long id; // // /** // * Create a new instance // * // * @param applicationId the Cloud Foundry application id // */ // public Application(UUID applicationId) { // this.applicationId = applicationId; // } // // Application() { // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // Application that = (Application) o; // return Objects.equals(this.applicationId, that.applicationId) && // Objects.equals(this.id, that.id); // } // // /** // * Returns the application id // * // * @return the application id // */ // public UUID getApplicationId() { // return this.applicationId; // } // // /** // * Returns the id // * // * @return the id // */ // public Long getId() { // return this.id; // } // // /** // * Sets the id // * // * @param id the id // */ // public void setId(Long id) { // this.id = id; // } // // @Override // public int hashCode() { // return Objects.hash(this.applicationId, this.id); // } // // @Override // public String toString() { // return "Application{" + // "applicationId=" + this.applicationId + // ", id=" + this.id + // '}'; // } // // } // // Path: src/main/java/io/pivotal/strepsirrhini/chaosloris/data/ChaosRepository.java // @Repository // public interface ChaosRepository extends JpaRepository<Chaos, Long> { // // /** // * Find all of the {@link Chaos}es related to an {@link Application} // * // * @param application the {@link Application} that {@link Chaos}es are related to // * @return a collection of {@link Chaos}es related to the {@link Application} // */ // @Transactional(readOnly = true) // List<Chaos> findByApplication(Application application); // // /** // * Find all of the {@link Chaos}es related to a {@link Schedule} // * // * @param schedule the {@link Schedule} that {@link Chaos}es are related to // * @return a collection of {@link Chaos}es related to the {@link Schedule} // */ // @Transactional(readOnly = true) // List<Chaos> findBySchedule(Schedule schedule); // // /** // * Find all of the {@link Chaos}es related to a {@link Schedule} // * // * @param id the id of {@link Schedule} that {@link Chaos}es are related to // * @return a collection of {@link Chaos}es related to the {@link Schedule} // */ // @Transactional(readOnly = true) // List<Chaos> findByScheduleId(Long id); // // }
import io.pivotal.strepsirrhini.chaosloris.data.Application; import io.pivotal.strepsirrhini.chaosloris.data.ChaosRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.hateoas.Resource; import org.springframework.hateoas.mvc.ResourceAssemblerSupport; import org.springframework.stereotype.Component; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn;
/* * Copyright 2015-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.pivotal.strepsirrhini.chaosloris.web; @Component public final class ApplicationResourceAssembler extends ResourceAssemblerSupport<Application, ApplicationResourceAssembler.ApplicationResource> {
// Path: src/main/java/io/pivotal/strepsirrhini/chaosloris/data/Application.java // @Entity // public class Application { // // @Column(nullable = false, unique = true) // private UUID applicationId; // // @Column(nullable = false) // @GeneratedValue // @Id // @JsonIgnore // private Long id; // // /** // * Create a new instance // * // * @param applicationId the Cloud Foundry application id // */ // public Application(UUID applicationId) { // this.applicationId = applicationId; // } // // Application() { // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // Application that = (Application) o; // return Objects.equals(this.applicationId, that.applicationId) && // Objects.equals(this.id, that.id); // } // // /** // * Returns the application id // * // * @return the application id // */ // public UUID getApplicationId() { // return this.applicationId; // } // // /** // * Returns the id // * // * @return the id // */ // public Long getId() { // return this.id; // } // // /** // * Sets the id // * // * @param id the id // */ // public void setId(Long id) { // this.id = id; // } // // @Override // public int hashCode() { // return Objects.hash(this.applicationId, this.id); // } // // @Override // public String toString() { // return "Application{" + // "applicationId=" + this.applicationId + // ", id=" + this.id + // '}'; // } // // } // // Path: src/main/java/io/pivotal/strepsirrhini/chaosloris/data/ChaosRepository.java // @Repository // public interface ChaosRepository extends JpaRepository<Chaos, Long> { // // /** // * Find all of the {@link Chaos}es related to an {@link Application} // * // * @param application the {@link Application} that {@link Chaos}es are related to // * @return a collection of {@link Chaos}es related to the {@link Application} // */ // @Transactional(readOnly = true) // List<Chaos> findByApplication(Application application); // // /** // * Find all of the {@link Chaos}es related to a {@link Schedule} // * // * @param schedule the {@link Schedule} that {@link Chaos}es are related to // * @return a collection of {@link Chaos}es related to the {@link Schedule} // */ // @Transactional(readOnly = true) // List<Chaos> findBySchedule(Schedule schedule); // // /** // * Find all of the {@link Chaos}es related to a {@link Schedule} // * // * @param id the id of {@link Schedule} that {@link Chaos}es are related to // * @return a collection of {@link Chaos}es related to the {@link Schedule} // */ // @Transactional(readOnly = true) // List<Chaos> findByScheduleId(Long id); // // } // Path: src/main/java/io/pivotal/strepsirrhini/chaosloris/web/ApplicationResourceAssembler.java import io.pivotal.strepsirrhini.chaosloris.data.Application; import io.pivotal.strepsirrhini.chaosloris.data.ChaosRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.hateoas.Resource; import org.springframework.hateoas.mvc.ResourceAssemblerSupport; import org.springframework.stereotype.Component; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn; /* * Copyright 2015-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.pivotal.strepsirrhini.chaosloris.web; @Component public final class ApplicationResourceAssembler extends ResourceAssemblerSupport<Application, ApplicationResourceAssembler.ApplicationResource> {
private final ChaosRepository chaosRepository;
strepsirrhini-army/chaos-loris
src/main/java/io/pivotal/strepsirrhini/chaosloris/web/ApplicationController.java
// Path: src/main/java/io/pivotal/strepsirrhini/chaosloris/data/Application.java // @Entity // public class Application { // // @Column(nullable = false, unique = true) // private UUID applicationId; // // @Column(nullable = false) // @GeneratedValue // @Id // @JsonIgnore // private Long id; // // /** // * Create a new instance // * // * @param applicationId the Cloud Foundry application id // */ // public Application(UUID applicationId) { // this.applicationId = applicationId; // } // // Application() { // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // Application that = (Application) o; // return Objects.equals(this.applicationId, that.applicationId) && // Objects.equals(this.id, that.id); // } // // /** // * Returns the application id // * // * @return the application id // */ // public UUID getApplicationId() { // return this.applicationId; // } // // /** // * Returns the id // * // * @return the id // */ // public Long getId() { // return this.id; // } // // /** // * Sets the id // * // * @param id the id // */ // public void setId(Long id) { // this.id = id; // } // // @Override // public int hashCode() { // return Objects.hash(this.applicationId, this.id); // } // // @Override // public String toString() { // return "Application{" + // "applicationId=" + this.applicationId + // ", id=" + this.id + // '}'; // } // // } // // Path: src/main/java/io/pivotal/strepsirrhini/chaosloris/data/ApplicationRepository.java // @Repository // public interface ApplicationRepository extends JpaRepository<Application, Long> { // // }
import io.pivotal.strepsirrhini.chaosloris.data.Application; import io.pivotal.strepsirrhini.chaosloris.data.ApplicationRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.web.PagedResourcesAssembler; import org.springframework.http.ResponseEntity; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.validation.Valid; import static org.springframework.hateoas.MediaTypes.HAL_JSON_VALUE; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn; import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE; import static org.springframework.web.bind.annotation.RequestMethod.DELETE; import static org.springframework.web.bind.annotation.RequestMethod.GET; import static org.springframework.web.bind.annotation.RequestMethod.POST;
/* * Copyright 2015-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.pivotal.strepsirrhini.chaosloris.web; @RestController @RequestMapping("/applications") public class ApplicationController {
// Path: src/main/java/io/pivotal/strepsirrhini/chaosloris/data/Application.java // @Entity // public class Application { // // @Column(nullable = false, unique = true) // private UUID applicationId; // // @Column(nullable = false) // @GeneratedValue // @Id // @JsonIgnore // private Long id; // // /** // * Create a new instance // * // * @param applicationId the Cloud Foundry application id // */ // public Application(UUID applicationId) { // this.applicationId = applicationId; // } // // Application() { // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // Application that = (Application) o; // return Objects.equals(this.applicationId, that.applicationId) && // Objects.equals(this.id, that.id); // } // // /** // * Returns the application id // * // * @return the application id // */ // public UUID getApplicationId() { // return this.applicationId; // } // // /** // * Returns the id // * // * @return the id // */ // public Long getId() { // return this.id; // } // // /** // * Sets the id // * // * @param id the id // */ // public void setId(Long id) { // this.id = id; // } // // @Override // public int hashCode() { // return Objects.hash(this.applicationId, this.id); // } // // @Override // public String toString() { // return "Application{" + // "applicationId=" + this.applicationId + // ", id=" + this.id + // '}'; // } // // } // // Path: src/main/java/io/pivotal/strepsirrhini/chaosloris/data/ApplicationRepository.java // @Repository // public interface ApplicationRepository extends JpaRepository<Application, Long> { // // } // Path: src/main/java/io/pivotal/strepsirrhini/chaosloris/web/ApplicationController.java import io.pivotal.strepsirrhini.chaosloris.data.Application; import io.pivotal.strepsirrhini.chaosloris.data.ApplicationRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.web.PagedResourcesAssembler; import org.springframework.http.ResponseEntity; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.validation.Valid; import static org.springframework.hateoas.MediaTypes.HAL_JSON_VALUE; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn; import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE; import static org.springframework.web.bind.annotation.RequestMethod.DELETE; import static org.springframework.web.bind.annotation.RequestMethod.GET; import static org.springframework.web.bind.annotation.RequestMethod.POST; /* * Copyright 2015-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.pivotal.strepsirrhini.chaosloris.web; @RestController @RequestMapping("/applications") public class ApplicationController {
private final ApplicationRepository applicationRepository;
strepsirrhini-army/chaos-loris
src/main/java/io/pivotal/strepsirrhini/chaosloris/web/ApplicationController.java
// Path: src/main/java/io/pivotal/strepsirrhini/chaosloris/data/Application.java // @Entity // public class Application { // // @Column(nullable = false, unique = true) // private UUID applicationId; // // @Column(nullable = false) // @GeneratedValue // @Id // @JsonIgnore // private Long id; // // /** // * Create a new instance // * // * @param applicationId the Cloud Foundry application id // */ // public Application(UUID applicationId) { // this.applicationId = applicationId; // } // // Application() { // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // Application that = (Application) o; // return Objects.equals(this.applicationId, that.applicationId) && // Objects.equals(this.id, that.id); // } // // /** // * Returns the application id // * // * @return the application id // */ // public UUID getApplicationId() { // return this.applicationId; // } // // /** // * Returns the id // * // * @return the id // */ // public Long getId() { // return this.id; // } // // /** // * Sets the id // * // * @param id the id // */ // public void setId(Long id) { // this.id = id; // } // // @Override // public int hashCode() { // return Objects.hash(this.applicationId, this.id); // } // // @Override // public String toString() { // return "Application{" + // "applicationId=" + this.applicationId + // ", id=" + this.id + // '}'; // } // // } // // Path: src/main/java/io/pivotal/strepsirrhini/chaosloris/data/ApplicationRepository.java // @Repository // public interface ApplicationRepository extends JpaRepository<Application, Long> { // // }
import io.pivotal.strepsirrhini.chaosloris.data.Application; import io.pivotal.strepsirrhini.chaosloris.data.ApplicationRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.web.PagedResourcesAssembler; import org.springframework.http.ResponseEntity; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.validation.Valid; import static org.springframework.hateoas.MediaTypes.HAL_JSON_VALUE; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn; import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE; import static org.springframework.web.bind.annotation.RequestMethod.DELETE; import static org.springframework.web.bind.annotation.RequestMethod.GET; import static org.springframework.web.bind.annotation.RequestMethod.POST;
/* * Copyright 2015-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.pivotal.strepsirrhini.chaosloris.web; @RestController @RequestMapping("/applications") public class ApplicationController { private final ApplicationRepository applicationRepository; private final ApplicationResourceAssembler applicationResourceAssembler; @Autowired ApplicationController(ApplicationRepository applicationRepository, ApplicationResourceAssembler applicationResourceAssembler) { this.applicationRepository = applicationRepository; this.applicationResourceAssembler = applicationResourceAssembler; } @Transactional @RequestMapping(method = POST, value = "", consumes = APPLICATION_JSON_VALUE) public ResponseEntity create(@Valid @RequestBody ApplicationCreateInput input) {
// Path: src/main/java/io/pivotal/strepsirrhini/chaosloris/data/Application.java // @Entity // public class Application { // // @Column(nullable = false, unique = true) // private UUID applicationId; // // @Column(nullable = false) // @GeneratedValue // @Id // @JsonIgnore // private Long id; // // /** // * Create a new instance // * // * @param applicationId the Cloud Foundry application id // */ // public Application(UUID applicationId) { // this.applicationId = applicationId; // } // // Application() { // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // Application that = (Application) o; // return Objects.equals(this.applicationId, that.applicationId) && // Objects.equals(this.id, that.id); // } // // /** // * Returns the application id // * // * @return the application id // */ // public UUID getApplicationId() { // return this.applicationId; // } // // /** // * Returns the id // * // * @return the id // */ // public Long getId() { // return this.id; // } // // /** // * Sets the id // * // * @param id the id // */ // public void setId(Long id) { // this.id = id; // } // // @Override // public int hashCode() { // return Objects.hash(this.applicationId, this.id); // } // // @Override // public String toString() { // return "Application{" + // "applicationId=" + this.applicationId + // ", id=" + this.id + // '}'; // } // // } // // Path: src/main/java/io/pivotal/strepsirrhini/chaosloris/data/ApplicationRepository.java // @Repository // public interface ApplicationRepository extends JpaRepository<Application, Long> { // // } // Path: src/main/java/io/pivotal/strepsirrhini/chaosloris/web/ApplicationController.java import io.pivotal.strepsirrhini.chaosloris.data.Application; import io.pivotal.strepsirrhini.chaosloris.data.ApplicationRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.web.PagedResourcesAssembler; import org.springframework.http.ResponseEntity; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.validation.Valid; import static org.springframework.hateoas.MediaTypes.HAL_JSON_VALUE; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn; import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE; import static org.springframework.web.bind.annotation.RequestMethod.DELETE; import static org.springframework.web.bind.annotation.RequestMethod.GET; import static org.springframework.web.bind.annotation.RequestMethod.POST; /* * Copyright 2015-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.pivotal.strepsirrhini.chaosloris.web; @RestController @RequestMapping("/applications") public class ApplicationController { private final ApplicationRepository applicationRepository; private final ApplicationResourceAssembler applicationResourceAssembler; @Autowired ApplicationController(ApplicationRepository applicationRepository, ApplicationResourceAssembler applicationResourceAssembler) { this.applicationRepository = applicationRepository; this.applicationResourceAssembler = applicationResourceAssembler; } @Transactional @RequestMapping(method = POST, value = "", consumes = APPLICATION_JSON_VALUE) public ResponseEntity create(@Valid @RequestBody ApplicationCreateInput input) {
Application application = new Application(input.getApplicationId());
strepsirrhini-army/chaos-loris
src/main/java/io/pivotal/strepsirrhini/chaosloris/destroyer/CloudFoundryPlatform.java
// Path: src/main/java/io/pivotal/strepsirrhini/chaosloris/data/Application.java // @Entity // public class Application { // // @Column(nullable = false, unique = true) // private UUID applicationId; // // @Column(nullable = false) // @GeneratedValue // @Id // @JsonIgnore // private Long id; // // /** // * Create a new instance // * // * @param applicationId the Cloud Foundry application id // */ // public Application(UUID applicationId) { // this.applicationId = applicationId; // } // // Application() { // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // Application that = (Application) o; // return Objects.equals(this.applicationId, that.applicationId) && // Objects.equals(this.id, that.id); // } // // /** // * Returns the application id // * // * @return the application id // */ // public UUID getApplicationId() { // return this.applicationId; // } // // /** // * Returns the id // * // * @return the id // */ // public Long getId() { // return this.id; // } // // /** // * Sets the id // * // * @param id the id // */ // public void setId(Long id) { // this.id = id; // } // // @Override // public int hashCode() { // return Objects.hash(this.applicationId, this.id); // } // // @Override // public String toString() { // return "Application{" + // "applicationId=" + this.applicationId + // ", id=" + this.id + // '}'; // } // // }
import io.pivotal.strepsirrhini.chaosloris.data.Application; import org.cloudfoundry.client.CloudFoundryClient; import org.cloudfoundry.client.v2.applications.SummaryApplicationRequest; import org.cloudfoundry.client.v2.applications.SummaryApplicationResponse; import org.cloudfoundry.client.v2.applications.TerminateApplicationInstanceRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import reactor.core.publisher.Mono;
/* * Copyright 2015-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.pivotal.strepsirrhini.chaosloris.destroyer; @Component final class CloudFoundryPlatform implements Platform { private final Logger logger = LoggerFactory.getLogger(this.getClass()); private final CloudFoundryClient cloudFoundryClient; @Autowired protected CloudFoundryPlatform(CloudFoundryClient cloudFoundryClient) { this.cloudFoundryClient = cloudFoundryClient; } @Override
// Path: src/main/java/io/pivotal/strepsirrhini/chaosloris/data/Application.java // @Entity // public class Application { // // @Column(nullable = false, unique = true) // private UUID applicationId; // // @Column(nullable = false) // @GeneratedValue // @Id // @JsonIgnore // private Long id; // // /** // * Create a new instance // * // * @param applicationId the Cloud Foundry application id // */ // public Application(UUID applicationId) { // this.applicationId = applicationId; // } // // Application() { // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // Application that = (Application) o; // return Objects.equals(this.applicationId, that.applicationId) && // Objects.equals(this.id, that.id); // } // // /** // * Returns the application id // * // * @return the application id // */ // public UUID getApplicationId() { // return this.applicationId; // } // // /** // * Returns the id // * // * @return the id // */ // public Long getId() { // return this.id; // } // // /** // * Sets the id // * // * @param id the id // */ // public void setId(Long id) { // this.id = id; // } // // @Override // public int hashCode() { // return Objects.hash(this.applicationId, this.id); // } // // @Override // public String toString() { // return "Application{" + // "applicationId=" + this.applicationId + // ", id=" + this.id + // '}'; // } // // } // Path: src/main/java/io/pivotal/strepsirrhini/chaosloris/destroyer/CloudFoundryPlatform.java import io.pivotal.strepsirrhini.chaosloris.data.Application; import org.cloudfoundry.client.CloudFoundryClient; import org.cloudfoundry.client.v2.applications.SummaryApplicationRequest; import org.cloudfoundry.client.v2.applications.SummaryApplicationResponse; import org.cloudfoundry.client.v2.applications.TerminateApplicationInstanceRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import reactor.core.publisher.Mono; /* * Copyright 2015-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.pivotal.strepsirrhini.chaosloris.destroyer; @Component final class CloudFoundryPlatform implements Platform { private final Logger logger = LoggerFactory.getLogger(this.getClass()); private final CloudFoundryClient cloudFoundryClient; @Autowired protected CloudFoundryPlatform(CloudFoundryClient cloudFoundryClient) { this.cloudFoundryClient = cloudFoundryClient; } @Override
public Mono<Integer> getInstanceCount(Application application) {
strepsirrhini-army/chaos-loris
src/main/java/io/pivotal/strepsirrhini/chaosloris/web/EventController.java
// Path: src/main/java/io/pivotal/strepsirrhini/chaosloris/data/Event.java // @Entity // public class Event { // // @JoinColumn(nullable = false) // @ManyToOne // @JsonIgnore // private Chaos chaos; // // @Column(nullable = false) // private Instant executedAt; // // @Column(nullable = false) // @GeneratedValue // @Id // @JsonIgnore // private Long id; // // @Column(nullable = false) // @ElementCollection // @OrderBy // private List<Integer> terminatedInstances; // // @Column(nullable = false) // private Integer totalInstanceCount; // // public Event(Chaos chaos, Instant executedAt, List<Integer> terminatedInstances, Integer totalInstanceCount) { // this.chaos = chaos; // this.executedAt = executedAt; // this.terminatedInstances = terminatedInstances; // this.totalInstanceCount = totalInstanceCount; // } // // Event() { // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // Event event = (Event) o; // return Objects.equals(this.chaos, event.chaos) && // Objects.equals(this.executedAt, event.executedAt) && // Objects.equals(this.id, event.id) && // Objects.equals(this.terminatedInstances, event.terminatedInstances) && // Objects.equals(this.totalInstanceCount, event.totalInstanceCount); // } // // /** // * Returns the chaos // * // * @return the chaos // */ // public Chaos getChaos() { // return this.chaos; // } // // /** // * Returns when the event was executed // * // * @return when the event was executed // */ // public Instant getExecutedAt() { // return this.executedAt; // } // // /** // * Returns the id // * // * @return the id // */ // public Long getId() { // return this.id; // } // // /** // * Sets the id // * // * @param id the id // */ // public void setId(Long id) { // this.id = id; // } // // /** // * Returns the number of instances terminated // * // * @return the number of instances terminated // */ // public int getTerminatedInstanceCount() { // return this.getTerminatedInstances().size(); // } // // /** // * Returns the terminated instances // * // * @return the terminated instances // */ // public List<Integer> getTerminatedInstances() { // return this.terminatedInstances; // } // // /** // * Returns the total instance count // * // * @return the total instance count // */ // public Integer getTotalInstanceCount() { // return this.totalInstanceCount; // } // // @Override // public int hashCode() { // return Objects.hash(this.chaos, this.executedAt, this.id, this.terminatedInstances, this.totalInstanceCount); // } // // @Override // public String toString() { // return "Event{" + // "chaos=" + this.chaos + // ", executedAt=" + this.executedAt + // ", id=" + this.id + // ", terminatedInstances=" + this.terminatedInstances + // ", totalInstanceCount=" + this.totalInstanceCount + // '}'; // } // // } // // Path: src/main/java/io/pivotal/strepsirrhini/chaosloris/data/EventRepository.java // @Repository // public interface EventRepository extends JpaRepository<Event, Long> { // // /** // * Find all of the {@link Event}s related to a {@link Chaos} // * // * @param chaos the {@link Chaos} that {@link Event}s are related to // * @return a collection of {@link Event}s related to the {@link Chaos} // */ // @Transactional(readOnly = true) // List<Event> findByChaos(Chaos chaos); // // /** // * Find all of the {@link Event}s that occurred before an {@link Instant} // * // * @param instant the {@link Instant} to find {@link Event}s before // * @return a collection {@link Event}s that occurred before the {@link Instant} // */ // @Transactional(readOnly = true) // List<Event> findByExecutedAtBefore(Instant instant); // // }
import static org.springframework.web.bind.annotation.RequestMethod.GET; import io.pivotal.strepsirrhini.chaosloris.data.Event; import io.pivotal.strepsirrhini.chaosloris.data.EventRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.web.PagedResourcesAssembler; import org.springframework.http.ResponseEntity; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import static org.springframework.hateoas.MediaTypes.HAL_JSON_VALUE; import static org.springframework.web.bind.annotation.RequestMethod.DELETE;
/* * Copyright 2015-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.pivotal.strepsirrhini.chaosloris.web; @RestController @RequestMapping("/events") public class EventController {
// Path: src/main/java/io/pivotal/strepsirrhini/chaosloris/data/Event.java // @Entity // public class Event { // // @JoinColumn(nullable = false) // @ManyToOne // @JsonIgnore // private Chaos chaos; // // @Column(nullable = false) // private Instant executedAt; // // @Column(nullable = false) // @GeneratedValue // @Id // @JsonIgnore // private Long id; // // @Column(nullable = false) // @ElementCollection // @OrderBy // private List<Integer> terminatedInstances; // // @Column(nullable = false) // private Integer totalInstanceCount; // // public Event(Chaos chaos, Instant executedAt, List<Integer> terminatedInstances, Integer totalInstanceCount) { // this.chaos = chaos; // this.executedAt = executedAt; // this.terminatedInstances = terminatedInstances; // this.totalInstanceCount = totalInstanceCount; // } // // Event() { // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // Event event = (Event) o; // return Objects.equals(this.chaos, event.chaos) && // Objects.equals(this.executedAt, event.executedAt) && // Objects.equals(this.id, event.id) && // Objects.equals(this.terminatedInstances, event.terminatedInstances) && // Objects.equals(this.totalInstanceCount, event.totalInstanceCount); // } // // /** // * Returns the chaos // * // * @return the chaos // */ // public Chaos getChaos() { // return this.chaos; // } // // /** // * Returns when the event was executed // * // * @return when the event was executed // */ // public Instant getExecutedAt() { // return this.executedAt; // } // // /** // * Returns the id // * // * @return the id // */ // public Long getId() { // return this.id; // } // // /** // * Sets the id // * // * @param id the id // */ // public void setId(Long id) { // this.id = id; // } // // /** // * Returns the number of instances terminated // * // * @return the number of instances terminated // */ // public int getTerminatedInstanceCount() { // return this.getTerminatedInstances().size(); // } // // /** // * Returns the terminated instances // * // * @return the terminated instances // */ // public List<Integer> getTerminatedInstances() { // return this.terminatedInstances; // } // // /** // * Returns the total instance count // * // * @return the total instance count // */ // public Integer getTotalInstanceCount() { // return this.totalInstanceCount; // } // // @Override // public int hashCode() { // return Objects.hash(this.chaos, this.executedAt, this.id, this.terminatedInstances, this.totalInstanceCount); // } // // @Override // public String toString() { // return "Event{" + // "chaos=" + this.chaos + // ", executedAt=" + this.executedAt + // ", id=" + this.id + // ", terminatedInstances=" + this.terminatedInstances + // ", totalInstanceCount=" + this.totalInstanceCount + // '}'; // } // // } // // Path: src/main/java/io/pivotal/strepsirrhini/chaosloris/data/EventRepository.java // @Repository // public interface EventRepository extends JpaRepository<Event, Long> { // // /** // * Find all of the {@link Event}s related to a {@link Chaos} // * // * @param chaos the {@link Chaos} that {@link Event}s are related to // * @return a collection of {@link Event}s related to the {@link Chaos} // */ // @Transactional(readOnly = true) // List<Event> findByChaos(Chaos chaos); // // /** // * Find all of the {@link Event}s that occurred before an {@link Instant} // * // * @param instant the {@link Instant} to find {@link Event}s before // * @return a collection {@link Event}s that occurred before the {@link Instant} // */ // @Transactional(readOnly = true) // List<Event> findByExecutedAtBefore(Instant instant); // // } // Path: src/main/java/io/pivotal/strepsirrhini/chaosloris/web/EventController.java import static org.springframework.web.bind.annotation.RequestMethod.GET; import io.pivotal.strepsirrhini.chaosloris.data.Event; import io.pivotal.strepsirrhini.chaosloris.data.EventRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.web.PagedResourcesAssembler; import org.springframework.http.ResponseEntity; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import static org.springframework.hateoas.MediaTypes.HAL_JSON_VALUE; import static org.springframework.web.bind.annotation.RequestMethod.DELETE; /* * Copyright 2015-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.pivotal.strepsirrhini.chaosloris.web; @RestController @RequestMapping("/events") public class EventController {
private final EventRepository eventRepository;
Simperium/simperium-android
Simperium/src/main/java/com/simperium/client/Channel.java
// Path: Simperium/src/main/java/com/simperium/SimperiumException.java // public class SimperiumException extends Exception { // public SimperiumException() { super(); } // public SimperiumException(String message) { super(message); } // public SimperiumException(String message, Throwable cause) { super(message, cause); } // public SimperiumException(Throwable cause) { super(cause); } // } // // Path: Simperium/src/main/java/com/simperium/util/Logger.java // public class Logger { // // public static final String TAG = "Simperium"; // // public static final void log(String msg){ // Log.d(TAG, msg); // } // // public static final void log(String tag, String msg){ // Log.d(tag, msg); // } // // public static final void log(String msg, Throwable error){ // Log.e(TAG, msg, error); // } // // public static final void log(String tag, String msg, Throwable error){ // Log.e(tag, msg, error); // } // // }
import com.simperium.BuildConfig; import com.simperium.SimperiumException; import com.simperium.Version; import com.simperium.util.Logger; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.EventObject; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.Timer; import java.util.TreeMap; import java.util.concurrent.Executor; import android.util.Log;
public SerializedQueue(Map<String,Change> pendingChanges, List<Change> queuedChanges) { this.pending = pendingChanges; this.queued = queuedChanges; } } public Channel(Executor executor, String appId, String sessionId, final Bucket bucket, Serializer serializer, OnMessageListener listener) { mExecutor = executor; mSerializer = serializer; mAppId = appId; mSessionId = sessionId; mBucket = bucket; mListener = listener; // Receive auth: command command(COMMAND_AUTH, new Command() { public void execute(String param) { User user = getUser(); // ignore auth:expired, implement new auth:{JSON} for failures if(EXPIRED_AUTH.equals(param.trim())) return; // if it starts with { let's see if it's error JSON if (param.indexOf(EXPIRED_AUTH_INDICATOR) == 0) { try { JSONObject authResponse = new JSONObject(param); int code = authResponse.getInt(EXPIRED_AUTH_CODE_KEY); if (code == EXPIRED_AUTH_INVALID_TOKEN_CODE || code == EXPIRED_AUTH_MALFORMED_TOKEN_CODE) { user.setStatus(User.Status.NOT_AUTHORIZED); stop(); return; } else { // TODO retry auth?
// Path: Simperium/src/main/java/com/simperium/SimperiumException.java // public class SimperiumException extends Exception { // public SimperiumException() { super(); } // public SimperiumException(String message) { super(message); } // public SimperiumException(String message, Throwable cause) { super(message, cause); } // public SimperiumException(Throwable cause) { super(cause); } // } // // Path: Simperium/src/main/java/com/simperium/util/Logger.java // public class Logger { // // public static final String TAG = "Simperium"; // // public static final void log(String msg){ // Log.d(TAG, msg); // } // // public static final void log(String tag, String msg){ // Log.d(tag, msg); // } // // public static final void log(String msg, Throwable error){ // Log.e(TAG, msg, error); // } // // public static final void log(String tag, String msg, Throwable error){ // Log.e(tag, msg, error); // } // // } // Path: Simperium/src/main/java/com/simperium/client/Channel.java import com.simperium.BuildConfig; import com.simperium.SimperiumException; import com.simperium.Version; import com.simperium.util.Logger; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.EventObject; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.Timer; import java.util.TreeMap; import java.util.concurrent.Executor; import android.util.Log; public SerializedQueue(Map<String,Change> pendingChanges, List<Change> queuedChanges) { this.pending = pendingChanges; this.queued = queuedChanges; } } public Channel(Executor executor, String appId, String sessionId, final Bucket bucket, Serializer serializer, OnMessageListener listener) { mExecutor = executor; mSerializer = serializer; mAppId = appId; mSessionId = sessionId; mBucket = bucket; mListener = listener; // Receive auth: command command(COMMAND_AUTH, new Command() { public void execute(String param) { User user = getUser(); // ignore auth:expired, implement new auth:{JSON} for failures if(EXPIRED_AUTH.equals(param.trim())) return; // if it starts with { let's see if it's error JSON if (param.indexOf(EXPIRED_AUTH_INDICATOR) == 0) { try { JSONObject authResponse = new JSONObject(param); int code = authResponse.getInt(EXPIRED_AUTH_CODE_KEY); if (code == EXPIRED_AUTH_INVALID_TOKEN_CODE || code == EXPIRED_AUTH_MALFORMED_TOKEN_CODE) { user.setStatus(User.Status.NOT_AUTHORIZED); stop(); return; } else { // TODO retry auth?
Logger.log(TAG, String.format("Unable to auth: %d", code));
Simperium/simperium-android
Simperium/src/main/java/com/simperium/client/Channel.java
// Path: Simperium/src/main/java/com/simperium/SimperiumException.java // public class SimperiumException extends Exception { // public SimperiumException() { super(); } // public SimperiumException(String message) { super(message); } // public SimperiumException(String message, Throwable cause) { super(message, cause); } // public SimperiumException(Throwable cause) { super(cause); } // } // // Path: Simperium/src/main/java/com/simperium/util/Logger.java // public class Logger { // // public static final String TAG = "Simperium"; // // public static final void log(String msg){ // Log.d(TAG, msg); // } // // public static final void log(String tag, String msg){ // Log.d(tag, msg); // } // // public static final void log(String msg, Throwable error){ // Log.e(TAG, msg, error); // } // // public static final void log(String tag, String msg, Throwable error){ // Log.e(tag, msg, error); // } // // }
import com.simperium.BuildConfig; import com.simperium.SimperiumException; import com.simperium.Version; import com.simperium.util.Logger; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.EventObject; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.Timer; import java.util.TreeMap; import java.util.concurrent.Executor; import android.util.Log;
public static ObjectVersionData parseString(String versionString) throws ObjectVersionParseException, ObjectVersionUnknownException, ObjectVersionDataInvalidException { String[] objectParts = versionString.split("\n"); String prefix = objectParts[0]; String payload = objectParts[1]; ObjectVersion objectVersion; objectVersion = ObjectVersion.parseString(prefix); if (payload.equals(RESPONSE_UNKNOWN)) { throw new ObjectVersionUnknownException(objectVersion); } try { JSONObject data = new JSONObject(payload); return new ObjectVersionData(objectVersion, data.getJSONObject(ENTITY_DATA_KEY)); } catch (JSONException e) { throw new ObjectVersionDataInvalidException(objectVersion, e); } } } /** * Thrown when e:id.v\n? received */
// Path: Simperium/src/main/java/com/simperium/SimperiumException.java // public class SimperiumException extends Exception { // public SimperiumException() { super(); } // public SimperiumException(String message) { super(message); } // public SimperiumException(String message, Throwable cause) { super(message, cause); } // public SimperiumException(Throwable cause) { super(cause); } // } // // Path: Simperium/src/main/java/com/simperium/util/Logger.java // public class Logger { // // public static final String TAG = "Simperium"; // // public static final void log(String msg){ // Log.d(TAG, msg); // } // // public static final void log(String tag, String msg){ // Log.d(tag, msg); // } // // public static final void log(String msg, Throwable error){ // Log.e(TAG, msg, error); // } // // public static final void log(String tag, String msg, Throwable error){ // Log.e(tag, msg, error); // } // // } // Path: Simperium/src/main/java/com/simperium/client/Channel.java import com.simperium.BuildConfig; import com.simperium.SimperiumException; import com.simperium.Version; import com.simperium.util.Logger; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.EventObject; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.Timer; import java.util.TreeMap; import java.util.concurrent.Executor; import android.util.Log; public static ObjectVersionData parseString(String versionString) throws ObjectVersionParseException, ObjectVersionUnknownException, ObjectVersionDataInvalidException { String[] objectParts = versionString.split("\n"); String prefix = objectParts[0]; String payload = objectParts[1]; ObjectVersion objectVersion; objectVersion = ObjectVersion.parseString(prefix); if (payload.equals(RESPONSE_UNKNOWN)) { throw new ObjectVersionUnknownException(objectVersion); } try { JSONObject data = new JSONObject(payload); return new ObjectVersionData(objectVersion, data.getJSONObject(ENTITY_DATA_KEY)); } catch (JSONException e) { throw new ObjectVersionDataInvalidException(objectVersion, e); } } } /** * Thrown when e:id.v\n? received */
public static class ObjectVersionUnknownException extends SimperiumException {
Simperium/simperium-android
Simperium/src/support/java/com/simperium/test/MockClient.java
// Path: Simperium/src/main/java/com/simperium/client/ClientFactory.java // public interface ClientFactory { // // public AuthProvider buildAuthProvider(String appId, String appSecret); // public ChannelProvider buildChannelProvider(String appId); // public StorageProvider buildStorageProvider(); // public GhostStorageProvider buildGhostStorageProvider(); // public Executor buildExecutor(); // // } // // Path: Simperium/src/main/java/com/simperium/storage/MemoryStore.java // public class MemoryStore implements StorageProvider { // // public <T extends Syncable> BucketStore<T> createStore(String bucketName, BucketSchema<T> schema){ // return new Storage<T>(); // } // // class Storage<T extends Syncable> implements StorageProvider.BucketStore<T> { // private Map<String, T> objects = Collections.synchronizedMap(new HashMap<String, T>(32)); // // @Override // public void prepare(Bucket<T> bucket){ // // noop // } // // /** // * Add/Update the given object // */ // @Override // public void save(T object, String simperiumKey, String json, List<Index> indexes) { // objects.put(simperiumKey, object); // } // // /** // * Remove the given object from the storage // */ // @Override // public void delete(T object){ // objects.remove(object.getSimperiumKey()); // } // // /** // * Delete all objects from storage // */ // @Override // public void reset(){ // objects.clear(); // } // // /** // * Get an object with the given key // */ // @Override // public T get(String key){ // return objects.get(key); // } // // /** // * Get a cursor to all the objects // */ // public Bucket.ObjectCursor<T> all(){ // return null; // } // // /** // * Search // */ // public Bucket.ObjectCursor<T> search(Query query){ // return null; // } // // /** // * Count // */ // public int count(Query query){ // return 0; // } // } // // }
import com.simperium.client.ClientFactory; import com.simperium.storage.MemoryStore;
/** * A nice fake client */ package com.simperium.test; public class MockClient implements ClientFactory { public MockAuthProvider authProvider = new MockAuthProvider(); public MockChannelProvider channelProvider = new MockChannelProvider(); @Override public MockAuthProvider buildAuthProvider(String appId, String appSecret){ return authProvider; } @Override public MockChannelProvider buildChannelProvider(String appId){ return channelProvider; } @Override
// Path: Simperium/src/main/java/com/simperium/client/ClientFactory.java // public interface ClientFactory { // // public AuthProvider buildAuthProvider(String appId, String appSecret); // public ChannelProvider buildChannelProvider(String appId); // public StorageProvider buildStorageProvider(); // public GhostStorageProvider buildGhostStorageProvider(); // public Executor buildExecutor(); // // } // // Path: Simperium/src/main/java/com/simperium/storage/MemoryStore.java // public class MemoryStore implements StorageProvider { // // public <T extends Syncable> BucketStore<T> createStore(String bucketName, BucketSchema<T> schema){ // return new Storage<T>(); // } // // class Storage<T extends Syncable> implements StorageProvider.BucketStore<T> { // private Map<String, T> objects = Collections.synchronizedMap(new HashMap<String, T>(32)); // // @Override // public void prepare(Bucket<T> bucket){ // // noop // } // // /** // * Add/Update the given object // */ // @Override // public void save(T object, String simperiumKey, String json, List<Index> indexes) { // objects.put(simperiumKey, object); // } // // /** // * Remove the given object from the storage // */ // @Override // public void delete(T object){ // objects.remove(object.getSimperiumKey()); // } // // /** // * Delete all objects from storage // */ // @Override // public void reset(){ // objects.clear(); // } // // /** // * Get an object with the given key // */ // @Override // public T get(String key){ // return objects.get(key); // } // // /** // * Get a cursor to all the objects // */ // public Bucket.ObjectCursor<T> all(){ // return null; // } // // /** // * Search // */ // public Bucket.ObjectCursor<T> search(Query query){ // return null; // } // // /** // * Count // */ // public int count(Query query){ // return 0; // } // } // // } // Path: Simperium/src/support/java/com/simperium/test/MockClient.java import com.simperium.client.ClientFactory; import com.simperium.storage.MemoryStore; /** * A nice fake client */ package com.simperium.test; public class MockClient implements ClientFactory { public MockAuthProvider authProvider = new MockAuthProvider(); public MockChannelProvider channelProvider = new MockChannelProvider(); @Override public MockAuthProvider buildAuthProvider(String appId, String appSecret){ return authProvider; } @Override public MockChannelProvider buildChannelProvider(String appId){ return channelProvider; } @Override
public MemoryStore buildStorageProvider(){
Simperium/simperium-android
Simperium/src/main/java/com/simperium/client/AuthResponseHandler.java
// Path: Simperium/src/main/java/com/simperium/util/AuthUtil.java // public class AuthUtil { // // public static final String USERNAME_KEY = "username"; // public static final String ACCESS_TOKEN_KEY = "access_token"; // public static final String PASSWORD_KEY = "password"; // public static final String USERID_KEY = "userid"; // public static final String PROVIDER_KEY = "provider"; // // public static JSONObject makeAuthRequestBody(User user){ // return makeAuthRequestBody(user.getEmail(), user.getPassword()); // } // // public static JSONObject makeAuthRequestBody(CharSequence username, CharSequence password){ // JSONObject body = new JSONObject(); // try { // if (username != null) body.put(USERNAME_KEY, username); // } catch (JSONException e) { // // could not set username // } // try { // if (password != null) body.put(PASSWORD_KEY, password); // } catch (JSONException e) { // // could not set password // } // return body; // } // // }
import com.simperium.util.AuthUtil; import org.json.JSONObject;
package com.simperium.client; public class AuthResponseHandler { private AuthProvider mProvider; private AuthResponseListener mListener; private User mUser; public AuthResponseHandler(User user, AuthResponseListener listener, AuthProvider provider) { mUser = user; mListener = listener; mProvider = provider; } public void onResponse(JSONObject response){
// Path: Simperium/src/main/java/com/simperium/util/AuthUtil.java // public class AuthUtil { // // public static final String USERNAME_KEY = "username"; // public static final String ACCESS_TOKEN_KEY = "access_token"; // public static final String PASSWORD_KEY = "password"; // public static final String USERID_KEY = "userid"; // public static final String PROVIDER_KEY = "provider"; // // public static JSONObject makeAuthRequestBody(User user){ // return makeAuthRequestBody(user.getEmail(), user.getPassword()); // } // // public static JSONObject makeAuthRequestBody(CharSequence username, CharSequence password){ // JSONObject body = new JSONObject(); // try { // if (username != null) body.put(USERNAME_KEY, username); // } catch (JSONException e) { // // could not set username // } // try { // if (password != null) body.put(PASSWORD_KEY, password); // } catch (JSONException e) { // // could not set password // } // return body; // } // // } // Path: Simperium/src/main/java/com/simperium/client/AuthResponseHandler.java import com.simperium.util.AuthUtil; import org.json.JSONObject; package com.simperium.client; public class AuthResponseHandler { private AuthProvider mProvider; private AuthResponseListener mListener; private User mUser; public AuthResponseHandler(User user, AuthResponseListener listener, AuthProvider provider) { mUser = user; mListener = listener; mProvider = provider; } public void onResponse(JSONObject response){
if (!response.optString(AuthUtil.USERID_KEY).isEmpty() && !response.optString(AuthUtil.ACCESS_TOKEN_KEY).isEmpty()) {
Simperium/simperium-android
Simperium/src/main/java/com/simperium/android/AndroidClient.java
// Path: Simperium/src/main/java/com/simperium/client/ClientFactory.java // public interface ClientFactory { // // public AuthProvider buildAuthProvider(String appId, String appSecret); // public ChannelProvider buildChannelProvider(String appId); // public StorageProvider buildStorageProvider(); // public GhostStorageProvider buildGhostStorageProvider(); // public Executor buildExecutor(); // // } // // Path: Simperium/src/main/java/com/simperium/util/Uuid.java // public class Uuid { // // public static String uuid(){ // return UUID.randomUUID().toString().replace("-",""); // } // // /** // * Take only the specified number of characters from the front of the UUID // */ // public static String uuid(int length){ // return uuid().substring(0, length); // } // // }
import android.content.Context; import android.content.SharedPreferences; import android.database.sqlite.SQLiteDatabase; import com.koushikdutta.async.http.AsyncHttpClient; import org.thoughtcrime.ssl.pinning.PinningTrustManager; import org.thoughtcrime.ssl.pinning.SystemKeyStore; import com.simperium.BuildConfig; import com.simperium.Version; import com.simperium.client.ClientFactory; import com.simperium.util.Uuid; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.concurrent.ExecutorService; import javax.net.ssl.TrustManager; import android.util.Log;
protected final String mSessionId; protected ExecutorService mExecutor; protected AsyncHttpClient mHttpClient = AsyncHttpClient.getDefaultInstance(); public AndroidClient(Context context){ int threads = Runtime.getRuntime().availableProcessors(); if (threads > 1) { threads -= 1; } if (BuildConfig.DEBUG) { Log.d(TAG, String.format("Using %d cores for executors", threads)); } mExecutor = Executors.newFixedThreadPool(threads); mContext = context; mDatabase = mContext.openOrCreateDatabase(DEFAULT_DATABASE_NAME, 0, null); SharedPreferences preferences = sharedPreferences(mContext); String sessionToken = null; if (preferences.contains(SESSION_ID_PREFERENCE)) { try { sessionToken = preferences.getString(SESSION_ID_PREFERENCE, null); } catch (ClassCastException e) { sessionToken = null; } } if (sessionToken == null) {
// Path: Simperium/src/main/java/com/simperium/client/ClientFactory.java // public interface ClientFactory { // // public AuthProvider buildAuthProvider(String appId, String appSecret); // public ChannelProvider buildChannelProvider(String appId); // public StorageProvider buildStorageProvider(); // public GhostStorageProvider buildGhostStorageProvider(); // public Executor buildExecutor(); // // } // // Path: Simperium/src/main/java/com/simperium/util/Uuid.java // public class Uuid { // // public static String uuid(){ // return UUID.randomUUID().toString().replace("-",""); // } // // /** // * Take only the specified number of characters from the front of the UUID // */ // public static String uuid(int length){ // return uuid().substring(0, length); // } // // } // Path: Simperium/src/main/java/com/simperium/android/AndroidClient.java import android.content.Context; import android.content.SharedPreferences; import android.database.sqlite.SQLiteDatabase; import com.koushikdutta.async.http.AsyncHttpClient; import org.thoughtcrime.ssl.pinning.PinningTrustManager; import org.thoughtcrime.ssl.pinning.SystemKeyStore; import com.simperium.BuildConfig; import com.simperium.Version; import com.simperium.client.ClientFactory; import com.simperium.util.Uuid; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.concurrent.ExecutorService; import javax.net.ssl.TrustManager; import android.util.Log; protected final String mSessionId; protected ExecutorService mExecutor; protected AsyncHttpClient mHttpClient = AsyncHttpClient.getDefaultInstance(); public AndroidClient(Context context){ int threads = Runtime.getRuntime().availableProcessors(); if (threads > 1) { threads -= 1; } if (BuildConfig.DEBUG) { Log.d(TAG, String.format("Using %d cores for executors", threads)); } mExecutor = Executors.newFixedThreadPool(threads); mContext = context; mDatabase = mContext.openOrCreateDatabase(DEFAULT_DATABASE_NAME, 0, null); SharedPreferences preferences = sharedPreferences(mContext); String sessionToken = null; if (preferences.contains(SESSION_ID_PREFERENCE)) { try { sessionToken = preferences.getString(SESSION_ID_PREFERENCE, null); } catch (ClassCastException e) { sessionToken = null; } } if (sessionToken == null) {
sessionToken = Uuid.uuid(6);
Simperium/simperium-android
Simperium/src/main/java/com/simperium/client/ClientFactory.java
// Path: Simperium/src/main/java/com/simperium/storage/StorageProvider.java // public interface StorageProvider { // /** // * Store and query bucket object data // */ // public interface BucketStore<T extends Syncable> { // // /** // * For initializing and performaing any necessary setup for storing // * bucket data. // */ // public void prepare(Bucket<T> bucket); // // /** // * Add/Update the given object // */ // public void save(T object, String simperiumKey, String json, List<Index> indexes); // // /** // * Remove the given object from the storage // */ // public void delete(T object); // // /** // * Delete all objects from storage // */ // public void reset(); // // /** // * Get an object with the given key // */ // public T get(String key) throws BucketObjectMissingException; // // /** // * All objects, returns a cursor for the given bucket // */ // public Bucket.ObjectCursor<T> all(); // // /** // * // */ // public Bucket.ObjectCursor<T> search(Query<T> query); // // /** // * Return the count for the given query // */ // public int count(Query<T> query); // // } // // /** // * // */ // public <T extends Syncable> BucketStore<T> createStore(String bucketName, BucketSchema<T> bucketSchema); // }
import java.util.concurrent.Executor; import com.simperium.storage.StorageProvider;
/** * Work in progress. Decoupling the pieces of a Simperium client to * allow alternate implementations for different platforms and dependency * injection for testing. */ package com.simperium.client; public interface ClientFactory { public AuthProvider buildAuthProvider(String appId, String appSecret); public ChannelProvider buildChannelProvider(String appId);
// Path: Simperium/src/main/java/com/simperium/storage/StorageProvider.java // public interface StorageProvider { // /** // * Store and query bucket object data // */ // public interface BucketStore<T extends Syncable> { // // /** // * For initializing and performaing any necessary setup for storing // * bucket data. // */ // public void prepare(Bucket<T> bucket); // // /** // * Add/Update the given object // */ // public void save(T object, String simperiumKey, String json, List<Index> indexes); // // /** // * Remove the given object from the storage // */ // public void delete(T object); // // /** // * Delete all objects from storage // */ // public void reset(); // // /** // * Get an object with the given key // */ // public T get(String key) throws BucketObjectMissingException; // // /** // * All objects, returns a cursor for the given bucket // */ // public Bucket.ObjectCursor<T> all(); // // /** // * // */ // public Bucket.ObjectCursor<T> search(Query<T> query); // // /** // * Return the count for the given query // */ // public int count(Query<T> query); // // } // // /** // * // */ // public <T extends Syncable> BucketStore<T> createStore(String bucketName, BucketSchema<T> bucketSchema); // } // Path: Simperium/src/main/java/com/simperium/client/ClientFactory.java import java.util.concurrent.Executor; import com.simperium.storage.StorageProvider; /** * Work in progress. Decoupling the pieces of a Simperium client to * allow alternate implementations for different platforms and dependency * injection for testing. */ package com.simperium.client; public interface ClientFactory { public AuthProvider buildAuthProvider(String appId, String appSecret); public ChannelProvider buildChannelProvider(String appId);
public StorageProvider buildStorageProvider();
Simperium/simperium-android
Simperium/src/main/java/com/simperium/util/AuthUtil.java
// Path: Simperium/src/main/java/com/simperium/client/User.java // public class User { // /** // * Applications can register a global authentication listener to get notified when a user's // * authenticated status has changed. // * // * Simperium simperium = new Simperium(appId, appSecret, appContext, new User.AuthenticationListener(){ // * public void onAuthenticationStatusChange(User.AuthenticationStatus status){ // * // Prompt user to log in or show they're offline // * } // * }); // */ // public interface StatusChangeListener { // void onUserStatusChange(Status authorized); // } // /** // * Determines a user's network status with Simperium: // * - AUTHENTICATED: user has an access token and is connected to Simperium // * - NOT_AUTHENTICATED: user does not have a valid access token. Create or auth the user // * - UKNOWN: User objects start in this state and then transitions to AUTHENTICATED or // * NOT_AUTHENTICATED. Also the state given when the Simperium is not reachable. // */ // public enum Status { // AUTHORIZED, NOT_AUTHORIZED, UNKNOWN // } // // private String email; // private String password; // private String userId; // private String accessToken; // private Status status = Status.UNKNOWN; // private StatusChangeListener listener; // // public User(){ // this(null, null, null); // } // // a user that hasn't been logged in // public User(StatusChangeListener listener){ // this(null, null, listener); // } // // public User(String email, StatusChangeListener listener){ // this(email, null, listener); // } // // public User(String email, String password, StatusChangeListener listener){ // this.email = email; // this.password = password; // this.listener = listener; // } // // public Status getStatus(){ // return status; // } // // public void setStatusChangeListener(StatusChangeListener authListener){ // listener = authListener; // } // // public StatusChangeListener getStatusChangeListener(){ // return listener; // } // // public void setStatus(Status status){ // if (this.status != status) { // this.status = status; // if (this.listener != null) { // listener.onUserStatusChange(this.status); // } // } // } // // // check if we have an access token // public boolean needsAuthorization(){ // return accessToken == null; // } // // public boolean hasAccessToken(){ // return accessToken != null; // } // // public void setCredentials(String email, String password){ // setEmail(email); // setPassword(password); // } // // public String getEmail(){ // return email; // } // // public void setEmail(String email){ // this.email = email; // } // // public void setPassword(String password){ // this.password = password; // } // // public String getPassword(){ // return password; // } // // public String getUserId(){ // return userId; // } // // public void setUserId(String userId){ // this.userId = userId; // } // // public String getAccessToken(){ // return accessToken; // } // // public void setAccessToken(String token){ // this.accessToken = token; // } // // }
import com.simperium.client.User; import org.json.JSONException; import org.json.JSONObject;
package com.simperium.util; public class AuthUtil { public static final String USERNAME_KEY = "username"; public static final String ACCESS_TOKEN_KEY = "access_token"; public static final String PASSWORD_KEY = "password"; public static final String USERID_KEY = "userid"; public static final String PROVIDER_KEY = "provider";
// Path: Simperium/src/main/java/com/simperium/client/User.java // public class User { // /** // * Applications can register a global authentication listener to get notified when a user's // * authenticated status has changed. // * // * Simperium simperium = new Simperium(appId, appSecret, appContext, new User.AuthenticationListener(){ // * public void onAuthenticationStatusChange(User.AuthenticationStatus status){ // * // Prompt user to log in or show they're offline // * } // * }); // */ // public interface StatusChangeListener { // void onUserStatusChange(Status authorized); // } // /** // * Determines a user's network status with Simperium: // * - AUTHENTICATED: user has an access token and is connected to Simperium // * - NOT_AUTHENTICATED: user does not have a valid access token. Create or auth the user // * - UKNOWN: User objects start in this state and then transitions to AUTHENTICATED or // * NOT_AUTHENTICATED. Also the state given when the Simperium is not reachable. // */ // public enum Status { // AUTHORIZED, NOT_AUTHORIZED, UNKNOWN // } // // private String email; // private String password; // private String userId; // private String accessToken; // private Status status = Status.UNKNOWN; // private StatusChangeListener listener; // // public User(){ // this(null, null, null); // } // // a user that hasn't been logged in // public User(StatusChangeListener listener){ // this(null, null, listener); // } // // public User(String email, StatusChangeListener listener){ // this(email, null, listener); // } // // public User(String email, String password, StatusChangeListener listener){ // this.email = email; // this.password = password; // this.listener = listener; // } // // public Status getStatus(){ // return status; // } // // public void setStatusChangeListener(StatusChangeListener authListener){ // listener = authListener; // } // // public StatusChangeListener getStatusChangeListener(){ // return listener; // } // // public void setStatus(Status status){ // if (this.status != status) { // this.status = status; // if (this.listener != null) { // listener.onUserStatusChange(this.status); // } // } // } // // // check if we have an access token // public boolean needsAuthorization(){ // return accessToken == null; // } // // public boolean hasAccessToken(){ // return accessToken != null; // } // // public void setCredentials(String email, String password){ // setEmail(email); // setPassword(password); // } // // public String getEmail(){ // return email; // } // // public void setEmail(String email){ // this.email = email; // } // // public void setPassword(String password){ // this.password = password; // } // // public String getPassword(){ // return password; // } // // public String getUserId(){ // return userId; // } // // public void setUserId(String userId){ // this.userId = userId; // } // // public String getAccessToken(){ // return accessToken; // } // // public void setAccessToken(String token){ // this.accessToken = token; // } // // } // Path: Simperium/src/main/java/com/simperium/util/AuthUtil.java import com.simperium.client.User; import org.json.JSONException; import org.json.JSONObject; package com.simperium.util; public class AuthUtil { public static final String USERNAME_KEY = "username"; public static final String ACCESS_TOKEN_KEY = "access_token"; public static final String PASSWORD_KEY = "password"; public static final String USERID_KEY = "userid"; public static final String PROVIDER_KEY = "provider";
public static JSONObject makeAuthRequestBody(User user){
xylo/JErgometer
src/org/jergometer/translation/I18n.java
// Path: src/de/endrullis/utils/Utf8ResourceBundle.java // public abstract class Utf8ResourceBundle { // // public static ResourceBundle getBundle(String baseName) { // ResourceBundle bundle = ResourceBundle.getBundle(baseName); // return createUtf8PropertyResourceBundle(bundle); // } // // public static ResourceBundle getBundle(String baseName, Locale locale) { // ResourceBundle bundle = ResourceBundle.getBundle(baseName, locale); // return createUtf8PropertyResourceBundle(bundle); // } // // public static ResourceBundle getBundle(String baseName, Locale locale, ClassLoader loader) { // ResourceBundle bundle = ResourceBundle.getBundle(baseName, locale, loader); // return createUtf8PropertyResourceBundle(bundle); // } // // private static ResourceBundle createUtf8PropertyResourceBundle(ResourceBundle bundle) { // if (!(bundle instanceof PropertyResourceBundle)) return bundle; // // return new Utf8PropertyResourceBundle((PropertyResourceBundle)bundle); // } // // // // // inner classes // // private static class Utf8PropertyResourceBundle extends ResourceBundle { // PropertyResourceBundle bundle; // // private Utf8PropertyResourceBundle(PropertyResourceBundle bundle) { // this.bundle = bundle; // } // /* (non-Javadoc) // * @see java.util.ResourceBundle#getKeys() // */ // public Enumeration<String> getKeys() { // return bundle.getKeys(); // } // /* (non-Javadoc) // * @see java.util.ResourceBundle#handleGetObject(java.lang.String) // */ // protected Object handleGetObject(String key) { // String value = bundle.getString(key); // if (value==null) return null; // try { // return new String (value.getBytes("ISO-8859-1"),"UTF-8") ; // } catch (UnsupportedEncodingException e) { // // Shouldn't fail - but should we still add logging message? // return null; // } // } // } // }
import de.endrullis.utils.Utf8ResourceBundle; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.PropertyKey; import java.util.ResourceBundle;
package org.jergometer.translation; /** * I18n support for the project jergometer. */ public class I18n { @NonNls
// Path: src/de/endrullis/utils/Utf8ResourceBundle.java // public abstract class Utf8ResourceBundle { // // public static ResourceBundle getBundle(String baseName) { // ResourceBundle bundle = ResourceBundle.getBundle(baseName); // return createUtf8PropertyResourceBundle(bundle); // } // // public static ResourceBundle getBundle(String baseName, Locale locale) { // ResourceBundle bundle = ResourceBundle.getBundle(baseName, locale); // return createUtf8PropertyResourceBundle(bundle); // } // // public static ResourceBundle getBundle(String baseName, Locale locale, ClassLoader loader) { // ResourceBundle bundle = ResourceBundle.getBundle(baseName, locale, loader); // return createUtf8PropertyResourceBundle(bundle); // } // // private static ResourceBundle createUtf8PropertyResourceBundle(ResourceBundle bundle) { // if (!(bundle instanceof PropertyResourceBundle)) return bundle; // // return new Utf8PropertyResourceBundle((PropertyResourceBundle)bundle); // } // // // // // inner classes // // private static class Utf8PropertyResourceBundle extends ResourceBundle { // PropertyResourceBundle bundle; // // private Utf8PropertyResourceBundle(PropertyResourceBundle bundle) { // this.bundle = bundle; // } // /* (non-Javadoc) // * @see java.util.ResourceBundle#getKeys() // */ // public Enumeration<String> getKeys() { // return bundle.getKeys(); // } // /* (non-Javadoc) // * @see java.util.ResourceBundle#handleGetObject(java.lang.String) // */ // protected Object handleGetObject(String key) { // String value = bundle.getString(key); // if (value==null) return null; // try { // return new String (value.getBytes("ISO-8859-1"),"UTF-8") ; // } catch (UnsupportedEncodingException e) { // // Shouldn't fail - but should we still add logging message? // return null; // } // } // } // } // Path: src/org/jergometer/translation/I18n.java import de.endrullis.utils.Utf8ResourceBundle; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.PropertyKey; import java.util.ResourceBundle; package org.jergometer.translation; /** * I18n support for the project jergometer. */ public class I18n { @NonNls
public static final ResourceBundle bundle = Utf8ResourceBundle.getBundle("org.jergometer.translation.jergometer");
xylo/JErgometer
src/org/jergometer/communication/KettlerBikeConnector.java
// Path: src/org/jergometer/translation/I18n.java // public class I18n { // @NonNls // public static final ResourceBundle bundle = Utf8ResourceBundle.getBundle("org.jergometer.translation.jergometer"); // // public static String getString(@PropertyKey(resourceBundle = "org.jergometer.translation.jergometer") String key, Object... params) { // String value = bundle.getString(key); // if (params.length == 0) { // return value; // } else { // return String.format(value, params); // } // } // // public static char getMnemonic(@PropertyKey(resourceBundle = "org.jergometer.translation.jergometer") String key) { // String value = getString(key); // if (value == null) { // return '!'; // } // return value.charAt(0); // } // }
import gnu.io.*; import java.io.IOException; import java.util.ArrayList; import java.util.Enumeration; import org.jergometer.translation.I18n;
package org.jergometer.communication; /** * KettlerBikeConnector connects to the bike via serial port (e.g. RS232 or USB). * It is used to receive data from the bike and to control it. */ public class KettlerBikeConnector implements BikeConnector { // dynamic private SerialPort serialPort; public KettlerBikeReader reader = null; public KettlerBikeWriter writer = null; private int power; public void connect(String serialName, BikeListener listener) throws BikeException, UnsupportedCommOperationException, IOException { RXTXLibrary.init(); Enumeration portList = CommPortIdentifier.getPortIdentifiers(); while (portList.hasMoreElements()) { CommPortIdentifier portId = (CommPortIdentifier) portList.nextElement(); if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) { if(portId.getName().equals(serialName)) { if(portId.isCurrentlyOwned()) {
// Path: src/org/jergometer/translation/I18n.java // public class I18n { // @NonNls // public static final ResourceBundle bundle = Utf8ResourceBundle.getBundle("org.jergometer.translation.jergometer"); // // public static String getString(@PropertyKey(resourceBundle = "org.jergometer.translation.jergometer") String key, Object... params) { // String value = bundle.getString(key); // if (params.length == 0) { // return value; // } else { // return String.format(value, params); // } // } // // public static char getMnemonic(@PropertyKey(resourceBundle = "org.jergometer.translation.jergometer") String key) { // String value = getString(key); // if (value == null) { // return '!'; // } // return value.charAt(0); // } // } // Path: src/org/jergometer/communication/KettlerBikeConnector.java import gnu.io.*; import java.io.IOException; import java.util.ArrayList; import java.util.Enumeration; import org.jergometer.translation.I18n; package org.jergometer.communication; /** * KettlerBikeConnector connects to the bike via serial port (e.g. RS232 or USB). * It is used to receive data from the bike and to control it. */ public class KettlerBikeConnector implements BikeConnector { // dynamic private SerialPort serialPort; public KettlerBikeReader reader = null; public KettlerBikeWriter writer = null; private int power; public void connect(String serialName, BikeListener listener) throws BikeException, UnsupportedCommOperationException, IOException { RXTXLibrary.init(); Enumeration portList = CommPortIdentifier.getPortIdentifiers(); while (portList.hasMoreElements()) { CommPortIdentifier portId = (CommPortIdentifier) portList.nextElement(); if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) { if(portId.getName().equals(serialName)) { if(portId.isCurrentlyOwned()) {
throw new BikeException(I18n.getString("msg.serial_port_used_by_the_following_application", portId.getCurrentOwner()));
xylo/JErgometer
src/org/jergometer/communication/BikeListener.java
// Path: src/org/jergometer/model/DataRecord.java // public class DataRecord { // protected int pulse; // protected int pedalRpm; // protected int speed; // protected int distance; // protected int destPower; // protected int energy; // protected String time; // protected int realPower; // // public DataRecord(int pulse, int pedalRpm, int speed, int distance, int destPower, int energy, String time, int realPower) { // this.pulse = pulse; // this.pedalRpm = pedalRpm; // this.speed = speed; // this.distance = distance; // this.destPower = destPower; // this.energy = energy; // this.time = time; // this.realPower = realPower; // } // // public DataRecord(String dataString) { // String[] parts = dataString.split("\\t"); // pulse = Integer.parseInt(parts[0]); // pedalRpm = Integer.parseInt(parts[1]); // speed = Integer.parseInt(parts[2]); // distance = Integer.parseInt(parts[3]); // destPower = Integer.parseInt(parts[4]); // energy = Integer.parseInt(parts[5]); // time = parts[6]; // realPower = Integer.parseInt(parts[7]); // } // // public DataRecord(DataInputStream in) throws IOException { // fromStream(in); // } // // public String toString() { // return new StringBuilder().append("pulse: ").append(pulse).append(",\tpedal rpm: ").append(pedalRpm).append(",\tspeed: ").append(speed).append(",\tdistance: ").append(distance).append(",\tdest. power: ").append(destPower).append(",\tenergy: ").append(energy).append(",\ttime: ").append(time).append(",\treal power: ").append(realPower).toString(); // } // // public void toStream(DataOutputStream out) throws IOException { // out.writeInt(pulse); // out.writeInt(pedalRpm); // out.writeInt(speed); // out.writeInt(distance); // out.writeInt(destPower); // out.writeInt(energy); // out.writeUTF(time); // out.writeInt(realPower); // } // // public void fromStream(DataInputStream in) throws IOException { // pulse = in.readInt(); // pedalRpm = in.readInt(); // speed = in.readInt(); // distance = in.readInt(); // destPower = in.readInt(); // energy = in.readInt(); // time = in.readUTF(); // realPower = in.readInt(); // } // // // // getters and setters // // public int getPulse() { // return pulse; // } // // public int getPedalRpm() { // return pedalRpm; // } // // public int getSpeed() { // return speed; // } // // public int getDistance() { // return distance; // } // // public int getDestPower() { // return destPower; // } // // public int getEnergy() { // return energy; // } // // public String getTime() { // return time; // } // // public int getRealPower() { // return realPower; // } // }
import org.jergometer.model.DataRecord;
package org.jergometer.communication; /** * Listener of the bike. */ public interface BikeListener { /** * Called if the bike has sent the ACK getString. */ public void bikeAck(); /** * Called if the bike has sent the data. * * @param data date from the bike */
// Path: src/org/jergometer/model/DataRecord.java // public class DataRecord { // protected int pulse; // protected int pedalRpm; // protected int speed; // protected int distance; // protected int destPower; // protected int energy; // protected String time; // protected int realPower; // // public DataRecord(int pulse, int pedalRpm, int speed, int distance, int destPower, int energy, String time, int realPower) { // this.pulse = pulse; // this.pedalRpm = pedalRpm; // this.speed = speed; // this.distance = distance; // this.destPower = destPower; // this.energy = energy; // this.time = time; // this.realPower = realPower; // } // // public DataRecord(String dataString) { // String[] parts = dataString.split("\\t"); // pulse = Integer.parseInt(parts[0]); // pedalRpm = Integer.parseInt(parts[1]); // speed = Integer.parseInt(parts[2]); // distance = Integer.parseInt(parts[3]); // destPower = Integer.parseInt(parts[4]); // energy = Integer.parseInt(parts[5]); // time = parts[6]; // realPower = Integer.parseInt(parts[7]); // } // // public DataRecord(DataInputStream in) throws IOException { // fromStream(in); // } // // public String toString() { // return new StringBuilder().append("pulse: ").append(pulse).append(",\tpedal rpm: ").append(pedalRpm).append(",\tspeed: ").append(speed).append(",\tdistance: ").append(distance).append(",\tdest. power: ").append(destPower).append(",\tenergy: ").append(energy).append(",\ttime: ").append(time).append(",\treal power: ").append(realPower).toString(); // } // // public void toStream(DataOutputStream out) throws IOException { // out.writeInt(pulse); // out.writeInt(pedalRpm); // out.writeInt(speed); // out.writeInt(distance); // out.writeInt(destPower); // out.writeInt(energy); // out.writeUTF(time); // out.writeInt(realPower); // } // // public void fromStream(DataInputStream in) throws IOException { // pulse = in.readInt(); // pedalRpm = in.readInt(); // speed = in.readInt(); // distance = in.readInt(); // destPower = in.readInt(); // energy = in.readInt(); // time = in.readUTF(); // realPower = in.readInt(); // } // // // // getters and setters // // public int getPulse() { // return pulse; // } // // public int getPedalRpm() { // return pedalRpm; // } // // public int getSpeed() { // return speed; // } // // public int getDistance() { // return distance; // } // // public int getDestPower() { // return destPower; // } // // public int getEnergy() { // return energy; // } // // public String getTime() { // return time; // } // // public int getRealPower() { // return realPower; // } // } // Path: src/org/jergometer/communication/BikeListener.java import org.jergometer.model.DataRecord; package org.jergometer.communication; /** * Listener of the bike. */ public interface BikeListener { /** * Called if the bike has sent the ACK getString. */ public void bikeAck(); /** * Called if the bike has sent the data. * * @param data date from the bike */
public void bikeData(DataRecord data);
xylo/JErgometer
src/org/jergometer/communication/KettlerBikeReader.java
// Path: src/org/jergometer/model/DataRecord.java // public class DataRecord { // protected int pulse; // protected int pedalRpm; // protected int speed; // protected int distance; // protected int destPower; // protected int energy; // protected String time; // protected int realPower; // // public DataRecord(int pulse, int pedalRpm, int speed, int distance, int destPower, int energy, String time, int realPower) { // this.pulse = pulse; // this.pedalRpm = pedalRpm; // this.speed = speed; // this.distance = distance; // this.destPower = destPower; // this.energy = energy; // this.time = time; // this.realPower = realPower; // } // // public DataRecord(String dataString) { // String[] parts = dataString.split("\\t"); // pulse = Integer.parseInt(parts[0]); // pedalRpm = Integer.parseInt(parts[1]); // speed = Integer.parseInt(parts[2]); // distance = Integer.parseInt(parts[3]); // destPower = Integer.parseInt(parts[4]); // energy = Integer.parseInt(parts[5]); // time = parts[6]; // realPower = Integer.parseInt(parts[7]); // } // // public DataRecord(DataInputStream in) throws IOException { // fromStream(in); // } // // public String toString() { // return new StringBuilder().append("pulse: ").append(pulse).append(",\tpedal rpm: ").append(pedalRpm).append(",\tspeed: ").append(speed).append(",\tdistance: ").append(distance).append(",\tdest. power: ").append(destPower).append(",\tenergy: ").append(energy).append(",\ttime: ").append(time).append(",\treal power: ").append(realPower).toString(); // } // // public void toStream(DataOutputStream out) throws IOException { // out.writeInt(pulse); // out.writeInt(pedalRpm); // out.writeInt(speed); // out.writeInt(distance); // out.writeInt(destPower); // out.writeInt(energy); // out.writeUTF(time); // out.writeInt(realPower); // } // // public void fromStream(DataInputStream in) throws IOException { // pulse = in.readInt(); // pedalRpm = in.readInt(); // speed = in.readInt(); // distance = in.readInt(); // destPower = in.readInt(); // energy = in.readInt(); // time = in.readUTF(); // realPower = in.readInt(); // } // // // // getters and setters // // public int getPulse() { // return pulse; // } // // public int getPedalRpm() { // return pedalRpm; // } // // public int getSpeed() { // return speed; // } // // public int getDistance() { // return distance; // } // // public int getDestPower() { // return destPower; // } // // public int getEnergy() { // return energy; // } // // public String getTime() { // return time; // } // // public int getRealPower() { // return realPower; // } // }
import org.jergometer.model.DataRecord; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList;
public KettlerBikeReader(InputStream in) { this.inStream = in; this.in = new BufferedReader(new InputStreamReader(inStream), 1); } public void run() { while(!isInterrupted()) { try { String dataString = in.readLine(); if (dataString == null || closed) { return; } if(printAvailable == PrintAvailable.none) { if (dataString.contains(CMD_ACK)) { for (BikeListener listener : bikeListeners) { listener.bikeAck(); } } else if (dataString.equals(CMD_ERROR)) { for (BikeListener listener : bikeListeners) { listener.bikeError(); } } else if (dataString.equals(CMD_RUN)) { for (BikeListener listener : bikeListeners) { listener.bikeAck(); } } else {
// Path: src/org/jergometer/model/DataRecord.java // public class DataRecord { // protected int pulse; // protected int pedalRpm; // protected int speed; // protected int distance; // protected int destPower; // protected int energy; // protected String time; // protected int realPower; // // public DataRecord(int pulse, int pedalRpm, int speed, int distance, int destPower, int energy, String time, int realPower) { // this.pulse = pulse; // this.pedalRpm = pedalRpm; // this.speed = speed; // this.distance = distance; // this.destPower = destPower; // this.energy = energy; // this.time = time; // this.realPower = realPower; // } // // public DataRecord(String dataString) { // String[] parts = dataString.split("\\t"); // pulse = Integer.parseInt(parts[0]); // pedalRpm = Integer.parseInt(parts[1]); // speed = Integer.parseInt(parts[2]); // distance = Integer.parseInt(parts[3]); // destPower = Integer.parseInt(parts[4]); // energy = Integer.parseInt(parts[5]); // time = parts[6]; // realPower = Integer.parseInt(parts[7]); // } // // public DataRecord(DataInputStream in) throws IOException { // fromStream(in); // } // // public String toString() { // return new StringBuilder().append("pulse: ").append(pulse).append(",\tpedal rpm: ").append(pedalRpm).append(",\tspeed: ").append(speed).append(",\tdistance: ").append(distance).append(",\tdest. power: ").append(destPower).append(",\tenergy: ").append(energy).append(",\ttime: ").append(time).append(",\treal power: ").append(realPower).toString(); // } // // public void toStream(DataOutputStream out) throws IOException { // out.writeInt(pulse); // out.writeInt(pedalRpm); // out.writeInt(speed); // out.writeInt(distance); // out.writeInt(destPower); // out.writeInt(energy); // out.writeUTF(time); // out.writeInt(realPower); // } // // public void fromStream(DataInputStream in) throws IOException { // pulse = in.readInt(); // pedalRpm = in.readInt(); // speed = in.readInt(); // distance = in.readInt(); // destPower = in.readInt(); // energy = in.readInt(); // time = in.readUTF(); // realPower = in.readInt(); // } // // // // getters and setters // // public int getPulse() { // return pulse; // } // // public int getPedalRpm() { // return pedalRpm; // } // // public int getSpeed() { // return speed; // } // // public int getDistance() { // return distance; // } // // public int getDestPower() { // return destPower; // } // // public int getEnergy() { // return energy; // } // // public String getTime() { // return time; // } // // public int getRealPower() { // return realPower; // } // } // Path: src/org/jergometer/communication/KettlerBikeReader.java import org.jergometer.model.DataRecord; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; public KettlerBikeReader(InputStream in) { this.inStream = in; this.in = new BufferedReader(new InputStreamReader(inStream), 1); } public void run() { while(!isInterrupted()) { try { String dataString = in.readLine(); if (dataString == null || closed) { return; } if(printAvailable == PrintAvailable.none) { if (dataString.contains(CMD_ACK)) { for (BikeListener listener : bikeListeners) { listener.bikeAck(); } } else if (dataString.equals(CMD_ERROR)) { for (BikeListener listener : bikeListeners) { listener.bikeError(); } } else if (dataString.equals(CMD_RUN)) { for (BikeListener listener : bikeListeners) { listener.bikeAck(); } } else {
DataRecord data = new DataRecord(dataString);
xylo/JErgometer
src/org/jergometer/communication/FileRecorder.java
// Path: src/org/jergometer/model/DataRecord.java // public class DataRecord { // protected int pulse; // protected int pedalRpm; // protected int speed; // protected int distance; // protected int destPower; // protected int energy; // protected String time; // protected int realPower; // // public DataRecord(int pulse, int pedalRpm, int speed, int distance, int destPower, int energy, String time, int realPower) { // this.pulse = pulse; // this.pedalRpm = pedalRpm; // this.speed = speed; // this.distance = distance; // this.destPower = destPower; // this.energy = energy; // this.time = time; // this.realPower = realPower; // } // // public DataRecord(String dataString) { // String[] parts = dataString.split("\\t"); // pulse = Integer.parseInt(parts[0]); // pedalRpm = Integer.parseInt(parts[1]); // speed = Integer.parseInt(parts[2]); // distance = Integer.parseInt(parts[3]); // destPower = Integer.parseInt(parts[4]); // energy = Integer.parseInt(parts[5]); // time = parts[6]; // realPower = Integer.parseInt(parts[7]); // } // // public DataRecord(DataInputStream in) throws IOException { // fromStream(in); // } // // public String toString() { // return new StringBuilder().append("pulse: ").append(pulse).append(",\tpedal rpm: ").append(pedalRpm).append(",\tspeed: ").append(speed).append(",\tdistance: ").append(distance).append(",\tdest. power: ").append(destPower).append(",\tenergy: ").append(energy).append(",\ttime: ").append(time).append(",\treal power: ").append(realPower).toString(); // } // // public void toStream(DataOutputStream out) throws IOException { // out.writeInt(pulse); // out.writeInt(pedalRpm); // out.writeInt(speed); // out.writeInt(distance); // out.writeInt(destPower); // out.writeInt(energy); // out.writeUTF(time); // out.writeInt(realPower); // } // // public void fromStream(DataInputStream in) throws IOException { // pulse = in.readInt(); // pedalRpm = in.readInt(); // speed = in.readInt(); // distance = in.readInt(); // destPower = in.readInt(); // energy = in.readInt(); // time = in.readUTF(); // realPower = in.readInt(); // } // // // // getters and setters // // public int getPulse() { // return pulse; // } // // public int getPedalRpm() { // return pedalRpm; // } // // public int getSpeed() { // return speed; // } // // public int getDistance() { // return distance; // } // // public int getDestPower() { // return destPower; // } // // public int getEnergy() { // return energy; // } // // public String getTime() { // return time; // } // // public int getRealPower() { // return realPower; // } // }
import org.jergometer.model.DataRecord; import java.io.*;
package org.jergometer.communication; /** * Records file sessions. * * @author Stefan Endrullis &lt;[email protected]&gt; */ public class FileRecorder implements BikeListener { private DataOutputStream out = null; public FileRecorder(String simulatorSession) throws FileNotFoundException { out = new DataOutputStream(new FileOutputStream(simulatorSession)); } @Override public void bikeAck() { } @Override
// Path: src/org/jergometer/model/DataRecord.java // public class DataRecord { // protected int pulse; // protected int pedalRpm; // protected int speed; // protected int distance; // protected int destPower; // protected int energy; // protected String time; // protected int realPower; // // public DataRecord(int pulse, int pedalRpm, int speed, int distance, int destPower, int energy, String time, int realPower) { // this.pulse = pulse; // this.pedalRpm = pedalRpm; // this.speed = speed; // this.distance = distance; // this.destPower = destPower; // this.energy = energy; // this.time = time; // this.realPower = realPower; // } // // public DataRecord(String dataString) { // String[] parts = dataString.split("\\t"); // pulse = Integer.parseInt(parts[0]); // pedalRpm = Integer.parseInt(parts[1]); // speed = Integer.parseInt(parts[2]); // distance = Integer.parseInt(parts[3]); // destPower = Integer.parseInt(parts[4]); // energy = Integer.parseInt(parts[5]); // time = parts[6]; // realPower = Integer.parseInt(parts[7]); // } // // public DataRecord(DataInputStream in) throws IOException { // fromStream(in); // } // // public String toString() { // return new StringBuilder().append("pulse: ").append(pulse).append(",\tpedal rpm: ").append(pedalRpm).append(",\tspeed: ").append(speed).append(",\tdistance: ").append(distance).append(",\tdest. power: ").append(destPower).append(",\tenergy: ").append(energy).append(",\ttime: ").append(time).append(",\treal power: ").append(realPower).toString(); // } // // public void toStream(DataOutputStream out) throws IOException { // out.writeInt(pulse); // out.writeInt(pedalRpm); // out.writeInt(speed); // out.writeInt(distance); // out.writeInt(destPower); // out.writeInt(energy); // out.writeUTF(time); // out.writeInt(realPower); // } // // public void fromStream(DataInputStream in) throws IOException { // pulse = in.readInt(); // pedalRpm = in.readInt(); // speed = in.readInt(); // distance = in.readInt(); // destPower = in.readInt(); // energy = in.readInt(); // time = in.readUTF(); // realPower = in.readInt(); // } // // // // getters and setters // // public int getPulse() { // return pulse; // } // // public int getPedalRpm() { // return pedalRpm; // } // // public int getSpeed() { // return speed; // } // // public int getDistance() { // return distance; // } // // public int getDestPower() { // return destPower; // } // // public int getEnergy() { // return energy; // } // // public String getTime() { // return time; // } // // public int getRealPower() { // return realPower; // } // } // Path: src/org/jergometer/communication/FileRecorder.java import org.jergometer.model.DataRecord; import java.io.*; package org.jergometer.communication; /** * Records file sessions. * * @author Stefan Endrullis &lt;[email protected]&gt; */ public class FileRecorder implements BikeListener { private DataOutputStream out = null; public FileRecorder(String simulatorSession) throws FileNotFoundException { out = new DataOutputStream(new FileOutputStream(simulatorSession)); } @Override public void bikeAck() { } @Override
public void bikeData(DataRecord data) {
xylo/JErgometer
src/org/jergometer/communication/BikeConnectionTester.java
// Path: src/org/jergometer/translation/I18n.java // public class I18n { // @NonNls // public static final ResourceBundle bundle = Utf8ResourceBundle.getBundle("org.jergometer.translation.jergometer"); // // public static String getString(@PropertyKey(resourceBundle = "org.jergometer.translation.jergometer") String key, Object... params) { // String value = bundle.getString(key); // if (params.length == 0) { // return value; // } else { // return String.format(value, params); // } // } // // public static char getMnemonic(@PropertyKey(resourceBundle = "org.jergometer.translation.jergometer") String key) { // String value = getString(key); // if (value == null) { // return '!'; // } // return value.charAt(0); // } // }
import org.jergometer.translation.I18n; import javax.swing.*; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.awt.*; import java.util.Enumeration; import gnu.io.SerialPort; import gnu.io.CommPortIdentifier; import gnu.io.PortInUseException; import gnu.io.UnsupportedCommOperationException;
} public void close() throws IOException { // stop reader and writer if(reader != null) { reader.close(); reader = null; } if(writer != null) { writer = null; } // close streams and socket if(serialPort != null) { serialPort.getOutputStream().close(); serialPort.getInputStream().close(); serialPort.removeEventListener(); serialPort.close(); } } /** * Tests the connection and returns the ergometer id in case of success. * * @return ergometer id in case of success */ public String test() { // start connection this.start();
// Path: src/org/jergometer/translation/I18n.java // public class I18n { // @NonNls // public static final ResourceBundle bundle = Utf8ResourceBundle.getBundle("org.jergometer.translation.jergometer"); // // public static String getString(@PropertyKey(resourceBundle = "org.jergometer.translation.jergometer") String key, Object... params) { // String value = bundle.getString(key); // if (params.length == 0) { // return value; // } else { // return String.format(value, params); // } // } // // public static char getMnemonic(@PropertyKey(resourceBundle = "org.jergometer.translation.jergometer") String key) { // String value = getString(key); // if (value == null) { // return '!'; // } // return value.charAt(0); // } // } // Path: src/org/jergometer/communication/BikeConnectionTester.java import org.jergometer.translation.I18n; import javax.swing.*; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.awt.*; import java.util.Enumeration; import gnu.io.SerialPort; import gnu.io.CommPortIdentifier; import gnu.io.PortInUseException; import gnu.io.UnsupportedCommOperationException; } public void close() throws IOException { // stop reader and writer if(reader != null) { reader.close(); reader = null; } if(writer != null) { writer = null; } // close streams and socket if(serialPort != null) { serialPort.getOutputStream().close(); serialPort.getInputStream().close(); serialPort.removeEventListener(); serialPort.close(); } } /** * Tests the connection and returns the ergometer id in case of success. * * @return ergometer id in case of success */ public String test() { // start connection this.start();
pm = new ProgressMonitor(owner, I18n.getString("connection_tester.testing_connection_to_ergometer"), "", 0, 100);
xylo/JErgometer
test/src/velocity/HelloWorld.java
// Path: src/de/endrullis/utils/VelocityUtils.java // public class VelocityUtils { // private static boolean initialized = false; // // public static void init() throws Exception { // if (initialized) return; // // // initialize Velocity // InputStream inputStream = StreamUtils.getInputStream("velocity.properties"); // Properties properties = new Properties(); // properties.load(inputStream); // Velocity.init(properties); // // initialized = true; // } // // // public static Template getTemplate(String name) throws Exception { // init(); // // InputStream resourceAsStream = VelocityUtils.class.getResourceAsStream("/" + name); // if (resourceAsStream == null) throw new ResourceNotFoundException("Resource " + name + " could not be found"); // // // get the template // return Velocity.getTemplate(name); // } // }
import de.endrullis.utils.VelocityUtils; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; import java.io.StringWriter; import java.io.Writer;
package velocity; /** * Hello World using Velocity. */ public class HelloWorld { public static void main(String[] args) throws Exception { // get the template
// Path: src/de/endrullis/utils/VelocityUtils.java // public class VelocityUtils { // private static boolean initialized = false; // // public static void init() throws Exception { // if (initialized) return; // // // initialize Velocity // InputStream inputStream = StreamUtils.getInputStream("velocity.properties"); // Properties properties = new Properties(); // properties.load(inputStream); // Velocity.init(properties); // // initialized = true; // } // // // public static Template getTemplate(String name) throws Exception { // init(); // // InputStream resourceAsStream = VelocityUtils.class.getResourceAsStream("/" + name); // if (resourceAsStream == null) throw new ResourceNotFoundException("Resource " + name + " could not be found"); // // // get the template // return Velocity.getTemplate(name); // } // } // Path: test/src/velocity/HelloWorld.java import de.endrullis.utils.VelocityUtils; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; import java.io.StringWriter; import java.io.Writer; package velocity; /** * Hello World using Velocity. */ public class HelloWorld { public static void main(String[] args) throws Exception { // get the template
Template template = VelocityUtils.getTemplate("templates/HelloWorld.vm");
xylo/JErgometer
src/org/jergometer/JergometerTestConsole.java
// Path: src/org/jergometer/model/DataRecord.java // public class DataRecord { // protected int pulse; // protected int pedalRpm; // protected int speed; // protected int distance; // protected int destPower; // protected int energy; // protected String time; // protected int realPower; // // public DataRecord(int pulse, int pedalRpm, int speed, int distance, int destPower, int energy, String time, int realPower) { // this.pulse = pulse; // this.pedalRpm = pedalRpm; // this.speed = speed; // this.distance = distance; // this.destPower = destPower; // this.energy = energy; // this.time = time; // this.realPower = realPower; // } // // public DataRecord(String dataString) { // String[] parts = dataString.split("\\t"); // pulse = Integer.parseInt(parts[0]); // pedalRpm = Integer.parseInt(parts[1]); // speed = Integer.parseInt(parts[2]); // distance = Integer.parseInt(parts[3]); // destPower = Integer.parseInt(parts[4]); // energy = Integer.parseInt(parts[5]); // time = parts[6]; // realPower = Integer.parseInt(parts[7]); // } // // public DataRecord(DataInputStream in) throws IOException { // fromStream(in); // } // // public String toString() { // return new StringBuilder().append("pulse: ").append(pulse).append(",\tpedal rpm: ").append(pedalRpm).append(",\tspeed: ").append(speed).append(",\tdistance: ").append(distance).append(",\tdest. power: ").append(destPower).append(",\tenergy: ").append(energy).append(",\ttime: ").append(time).append(",\treal power: ").append(realPower).toString(); // } // // public void toStream(DataOutputStream out) throws IOException { // out.writeInt(pulse); // out.writeInt(pedalRpm); // out.writeInt(speed); // out.writeInt(distance); // out.writeInt(destPower); // out.writeInt(energy); // out.writeUTF(time); // out.writeInt(realPower); // } // // public void fromStream(DataInputStream in) throws IOException { // pulse = in.readInt(); // pedalRpm = in.readInt(); // speed = in.readInt(); // distance = in.readInt(); // destPower = in.readInt(); // energy = in.readInt(); // time = in.readUTF(); // realPower = in.readInt(); // } // // // // getters and setters // // public int getPulse() { // return pulse; // } // // public int getPedalRpm() { // return pedalRpm; // } // // public int getSpeed() { // return speed; // } // // public int getDistance() { // return distance; // } // // public int getDestPower() { // return destPower; // } // // public int getEnergy() { // return energy; // } // // public String getTime() { // return time; // } // // public int getRealPower() { // return realPower; // } // }
import org.jergometer.communication.*; import org.jergometer.model.DataRecord; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import gnu.io.UnsupportedCommOperationException;
break; case 9: bikeConnector.close(); return; case 11: bikeConnector.reader.setPrintAvailable(KettlerBikeReader.PrintAvailable.characters); break; case 12: bikeConnector.reader.setPrintAvailable(KettlerBikeReader.PrintAvailable.decimals); break; default: System.out.println("* error: unknown command"); } } } catch (IOException e) { System.err.println("* Cannot connect to bike."); e.printStackTrace(); } } public void bikeAck() { System.err.println("* bikeAck received."); }
// Path: src/org/jergometer/model/DataRecord.java // public class DataRecord { // protected int pulse; // protected int pedalRpm; // protected int speed; // protected int distance; // protected int destPower; // protected int energy; // protected String time; // protected int realPower; // // public DataRecord(int pulse, int pedalRpm, int speed, int distance, int destPower, int energy, String time, int realPower) { // this.pulse = pulse; // this.pedalRpm = pedalRpm; // this.speed = speed; // this.distance = distance; // this.destPower = destPower; // this.energy = energy; // this.time = time; // this.realPower = realPower; // } // // public DataRecord(String dataString) { // String[] parts = dataString.split("\\t"); // pulse = Integer.parseInt(parts[0]); // pedalRpm = Integer.parseInt(parts[1]); // speed = Integer.parseInt(parts[2]); // distance = Integer.parseInt(parts[3]); // destPower = Integer.parseInt(parts[4]); // energy = Integer.parseInt(parts[5]); // time = parts[6]; // realPower = Integer.parseInt(parts[7]); // } // // public DataRecord(DataInputStream in) throws IOException { // fromStream(in); // } // // public String toString() { // return new StringBuilder().append("pulse: ").append(pulse).append(",\tpedal rpm: ").append(pedalRpm).append(",\tspeed: ").append(speed).append(",\tdistance: ").append(distance).append(",\tdest. power: ").append(destPower).append(",\tenergy: ").append(energy).append(",\ttime: ").append(time).append(",\treal power: ").append(realPower).toString(); // } // // public void toStream(DataOutputStream out) throws IOException { // out.writeInt(pulse); // out.writeInt(pedalRpm); // out.writeInt(speed); // out.writeInt(distance); // out.writeInt(destPower); // out.writeInt(energy); // out.writeUTF(time); // out.writeInt(realPower); // } // // public void fromStream(DataInputStream in) throws IOException { // pulse = in.readInt(); // pedalRpm = in.readInt(); // speed = in.readInt(); // distance = in.readInt(); // destPower = in.readInt(); // energy = in.readInt(); // time = in.readUTF(); // realPower = in.readInt(); // } // // // // getters and setters // // public int getPulse() { // return pulse; // } // // public int getPedalRpm() { // return pedalRpm; // } // // public int getSpeed() { // return speed; // } // // public int getDistance() { // return distance; // } // // public int getDestPower() { // return destPower; // } // // public int getEnergy() { // return energy; // } // // public String getTime() { // return time; // } // // public int getRealPower() { // return realPower; // } // } // Path: src/org/jergometer/JergometerTestConsole.java import org.jergometer.communication.*; import org.jergometer.model.DataRecord; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import gnu.io.UnsupportedCommOperationException; break; case 9: bikeConnector.close(); return; case 11: bikeConnector.reader.setPrintAvailable(KettlerBikeReader.PrintAvailable.characters); break; case 12: bikeConnector.reader.setPrintAvailable(KettlerBikeReader.PrintAvailable.decimals); break; default: System.out.println("* error: unknown command"); } } } catch (IOException e) { System.err.println("* Cannot connect to bike."); e.printStackTrace(); } } public void bikeAck() { System.err.println("* bikeAck received."); }
public void bikeData(DataRecord data) {
xylo/JErgometer
src/org/jergometer/JergometerConsole.java
// Path: src/org/jergometer/model/DataRecord.java // public class DataRecord { // protected int pulse; // protected int pedalRpm; // protected int speed; // protected int distance; // protected int destPower; // protected int energy; // protected String time; // protected int realPower; // // public DataRecord(int pulse, int pedalRpm, int speed, int distance, int destPower, int energy, String time, int realPower) { // this.pulse = pulse; // this.pedalRpm = pedalRpm; // this.speed = speed; // this.distance = distance; // this.destPower = destPower; // this.energy = energy; // this.time = time; // this.realPower = realPower; // } // // public DataRecord(String dataString) { // String[] parts = dataString.split("\\t"); // pulse = Integer.parseInt(parts[0]); // pedalRpm = Integer.parseInt(parts[1]); // speed = Integer.parseInt(parts[2]); // distance = Integer.parseInt(parts[3]); // destPower = Integer.parseInt(parts[4]); // energy = Integer.parseInt(parts[5]); // time = parts[6]; // realPower = Integer.parseInt(parts[7]); // } // // public DataRecord(DataInputStream in) throws IOException { // fromStream(in); // } // // public String toString() { // return new StringBuilder().append("pulse: ").append(pulse).append(",\tpedal rpm: ").append(pedalRpm).append(",\tspeed: ").append(speed).append(",\tdistance: ").append(distance).append(",\tdest. power: ").append(destPower).append(",\tenergy: ").append(energy).append(",\ttime: ").append(time).append(",\treal power: ").append(realPower).toString(); // } // // public void toStream(DataOutputStream out) throws IOException { // out.writeInt(pulse); // out.writeInt(pedalRpm); // out.writeInt(speed); // out.writeInt(distance); // out.writeInt(destPower); // out.writeInt(energy); // out.writeUTF(time); // out.writeInt(realPower); // } // // public void fromStream(DataInputStream in) throws IOException { // pulse = in.readInt(); // pedalRpm = in.readInt(); // speed = in.readInt(); // distance = in.readInt(); // destPower = in.readInt(); // energy = in.readInt(); // time = in.readUTF(); // realPower = in.readInt(); // } // // // // getters and setters // // public int getPulse() { // return pulse; // } // // public int getPedalRpm() { // return pedalRpm; // } // // public int getSpeed() { // return speed; // } // // public int getDistance() { // return distance; // } // // public int getDestPower() { // return destPower; // } // // public int getEnergy() { // return energy; // } // // public String getTime() { // return time; // } // // public int getRealPower() { // return realPower; // } // }
import org.jergometer.model.DataRecord; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Random;
package org.jergometer; /** * Console handler for JErgometer. * * @author Stefan Endrullis &lt;[email protected]&gt; */ public class JergometerConsole extends Thread { private Jergometer jergometer; private Random random = new Random(0); private int pulse = 80, pedalRpm = 70, speed = 50, distance = 0, destPower = 100, energy = 0, realPower = 100, time = 0, lastTime = 0; public JergometerConsole(Jergometer jergometer) { this.jergometer = jergometer; } @Override public void run() { try { BufferedReader r = new BufferedReader(new InputStreamReader(System.in)); String line; while ((line = r.readLine()) != null) { if (line.equals("train")) { // jergometer.getProgram().getProgramData().getDuration() + for (; time < 100; time++) { pulse += random.nextInt(3)-1; pedalRpm += random.nextInt(3)-1; speed += random.nextInt(3)-1; distance += 1; destPower += random.nextInt(3)-1; energy += random.nextInt(2); realPower += random.nextInt(3)-1;
// Path: src/org/jergometer/model/DataRecord.java // public class DataRecord { // protected int pulse; // protected int pedalRpm; // protected int speed; // protected int distance; // protected int destPower; // protected int energy; // protected String time; // protected int realPower; // // public DataRecord(int pulse, int pedalRpm, int speed, int distance, int destPower, int energy, String time, int realPower) { // this.pulse = pulse; // this.pedalRpm = pedalRpm; // this.speed = speed; // this.distance = distance; // this.destPower = destPower; // this.energy = energy; // this.time = time; // this.realPower = realPower; // } // // public DataRecord(String dataString) { // String[] parts = dataString.split("\\t"); // pulse = Integer.parseInt(parts[0]); // pedalRpm = Integer.parseInt(parts[1]); // speed = Integer.parseInt(parts[2]); // distance = Integer.parseInt(parts[3]); // destPower = Integer.parseInt(parts[4]); // energy = Integer.parseInt(parts[5]); // time = parts[6]; // realPower = Integer.parseInt(parts[7]); // } // // public DataRecord(DataInputStream in) throws IOException { // fromStream(in); // } // // public String toString() { // return new StringBuilder().append("pulse: ").append(pulse).append(",\tpedal rpm: ").append(pedalRpm).append(",\tspeed: ").append(speed).append(",\tdistance: ").append(distance).append(",\tdest. power: ").append(destPower).append(",\tenergy: ").append(energy).append(",\ttime: ").append(time).append(",\treal power: ").append(realPower).toString(); // } // // public void toStream(DataOutputStream out) throws IOException { // out.writeInt(pulse); // out.writeInt(pedalRpm); // out.writeInt(speed); // out.writeInt(distance); // out.writeInt(destPower); // out.writeInt(energy); // out.writeUTF(time); // out.writeInt(realPower); // } // // public void fromStream(DataInputStream in) throws IOException { // pulse = in.readInt(); // pedalRpm = in.readInt(); // speed = in.readInt(); // distance = in.readInt(); // destPower = in.readInt(); // energy = in.readInt(); // time = in.readUTF(); // realPower = in.readInt(); // } // // // // getters and setters // // public int getPulse() { // return pulse; // } // // public int getPedalRpm() { // return pedalRpm; // } // // public int getSpeed() { // return speed; // } // // public int getDistance() { // return distance; // } // // public int getDestPower() { // return destPower; // } // // public int getEnergy() { // return energy; // } // // public String getTime() { // return time; // } // // public int getRealPower() { // return realPower; // } // } // Path: src/org/jergometer/JergometerConsole.java import org.jergometer.model.DataRecord; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Random; package org.jergometer; /** * Console handler for JErgometer. * * @author Stefan Endrullis &lt;[email protected]&gt; */ public class JergometerConsole extends Thread { private Jergometer jergometer; private Random random = new Random(0); private int pulse = 80, pedalRpm = 70, speed = 50, distance = 0, destPower = 100, energy = 0, realPower = 100, time = 0, lastTime = 0; public JergometerConsole(Jergometer jergometer) { this.jergometer = jergometer; } @Override public void run() { try { BufferedReader r = new BufferedReader(new InputStreamReader(System.in)); String line; while ((line = r.readLine()) != null) { if (line.equals("train")) { // jergometer.getProgram().getProgramData().getDuration() + for (; time < 100; time++) { pulse += random.nextInt(3)-1; pedalRpm += random.nextInt(3)-1; speed += random.nextInt(3)-1; distance += 1; destPower += random.nextInt(3)-1; energy += random.nextInt(2); realPower += random.nextInt(3)-1;
jergometer.bikeData(new DataRecord(pulse, pedalRpm, speed, distance, destPower, energy, "" + time, realPower));
xylo/JErgometer
src/org/jergometer/model/BikeSession.java
// Path: src/de/endrullis/utils/VelocityUtils.java // public class VelocityUtils { // private static boolean initialized = false; // // public static void init() throws Exception { // if (initialized) return; // // // initialize Velocity // InputStream inputStream = StreamUtils.getInputStream("velocity.properties"); // Properties properties = new Properties(); // properties.load(inputStream); // Velocity.init(properties); // // initialized = true; // } // // // public static Template getTemplate(String name) throws Exception { // init(); // // InputStream resourceAsStream = VelocityUtils.class.getResourceAsStream("/" + name); // if (resourceAsStream == null) throw new ResourceNotFoundException("Resource " + name + " could not be found"); // // // get the template // return Velocity.getTemplate(name); // } // }
import de.endrullis.utils.VelocityUtils; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; import java.io.*; import java.sql.Time; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.GregorianCalendar;
statsTotal.duration++; if (record.pulse > 0) { statsTotal.pulseCount++; statsTotal.pulseSum += record.pulse; } statsTotal.powerSum += record.power; statsTotal.pedalRpmSum += record.pedalRpm; } needToBeSaved = true; } public void save(String dir) throws IOException { new File(dir).mkdirs(); String filename = getFileName(dir + "/", startTime); String filenameHRM = filename + ".hrm"; file = new File(getFileName(dir + "/", startTime)); DataOutputStream out = new DataOutputStream(new FileOutputStream(file)); toStream(out); out.close(); toHRM(filenameHRM); needToBeSaved = false; } private void toHRM(String filename) { VelocityContext context = new VelocityContext(); try {
// Path: src/de/endrullis/utils/VelocityUtils.java // public class VelocityUtils { // private static boolean initialized = false; // // public static void init() throws Exception { // if (initialized) return; // // // initialize Velocity // InputStream inputStream = StreamUtils.getInputStream("velocity.properties"); // Properties properties = new Properties(); // properties.load(inputStream); // Velocity.init(properties); // // initialized = true; // } // // // public static Template getTemplate(String name) throws Exception { // init(); // // InputStream resourceAsStream = VelocityUtils.class.getResourceAsStream("/" + name); // if (resourceAsStream == null) throw new ResourceNotFoundException("Resource " + name + " could not be found"); // // // get the template // return Velocity.getTemplate(name); // } // } // Path: src/org/jergometer/model/BikeSession.java import de.endrullis.utils.VelocityUtils; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; import java.io.*; import java.sql.Time; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.GregorianCalendar; statsTotal.duration++; if (record.pulse > 0) { statsTotal.pulseCount++; statsTotal.pulseSum += record.pulse; } statsTotal.powerSum += record.power; statsTotal.pedalRpmSum += record.pedalRpm; } needToBeSaved = true; } public void save(String dir) throws IOException { new File(dir).mkdirs(); String filename = getFileName(dir + "/", startTime); String filenameHRM = filename + ".hrm"; file = new File(getFileName(dir + "/", startTime)); DataOutputStream out = new DataOutputStream(new FileOutputStream(file)); toStream(out); out.close(); toHRM(filenameHRM); needToBeSaved = false; } private void toHRM(String filename) { VelocityContext context = new VelocityContext(); try {
Template template = VelocityUtils.getTemplate("org/jergometer/model/templates/hrm.template");
xylo/JErgometer
src/org/jergometer/model/BikeSessionFilter.java
// Path: src/org/jergometer/control/BikeProgram.java // public class BikeProgram extends HoldsFile { // private int power = 0; // private String programName; // private BikeProgramData programData; // private BikeSession session; // private SubProgram subProgram; // private Iterator<BikeProgramData.TimeEvent> eventIterator; // private BikeProgramData.TimeEvent nextEvent; // private int idleCounter = 0; // // public BikeProgram(File file, String programName, BikeProgramData programData) { // super(file); // this.programName = programName.replaceAll("\\\\", "/"); // this.programData = programData; // eventIterator = programData.getEvents().iterator(); // nextEvent = eventIterator.next(); // doActions(nextEvent.getActions()); // nextEvent = eventIterator.hasNext() ? eventIterator.next() : null; // } // // /** // * Adds the new data record to the session and returns true if user is not cycling anymore. // * // * @param dataRecord new data record // * @return true if user does not cycle anymore // */ // public UpdateStatus update(DataRecord dataRecord) { // if(session.update(dataRecord)) { // if(nextEvent != null && nextEvent.getTime() == session.getDuration()) { // doActions(nextEvent.getActions()); // nextEvent = eventIterator.hasNext() ? eventIterator.next() : null; // } else { // subProgram.update(dataRecord); // } // idleCounter = 0; // return UpdateStatus.cycle; // } else { // if (++idleCounter >= 4) { // return UpdateStatus.pulse; // } else { // return UpdateStatus.idle; // } // } // } // // private void doActions(ArrayList<BikeProgramData.Action> actions) { // BikeProgramData.Action currentAction; // // for (BikeProgramData.Action action : actions) { // doAction(action); // // currentAction = action; // } // } // // private void doAction(BikeProgramData.Action action) { // if(action.getType() == BikeProgramData.Action.Type.power) { // power = action.getValue(); // subProgram = new SubProgram.Power(session, power); // } // else if(action.getType() == BikeProgramData.Action.Type.pulse) { // int pulse = action.getValue(); // subProgram = new SubProgram.Pulse(session, power, pulse); // } // } // // public int getPower() { // power = subProgram.getPower(); // return power; // } // // public String getProgramAction() { // return subProgram.getActionName(); // } // // public String getProgramName() { // return programName; // } // // public BikeProgramData getProgramData() { // return programData; // } // // public BikeSession newSession() { // return session = new BikeSession(programName, programData.getDuration()); // } // // public BikeSession getSession() { // return session; // } // // public String toString() { // return programData.getName(); // } // // public void changeInteractively(int change) { // if (subProgram instanceof SubProgram.Power) { // subProgram = new SubProgram.Power(session, subProgram.getPower() + change*5); // } // if (subProgram instanceof SubProgram.Pulse) { // SubProgram.Pulse pulseProgram = (SubProgram.Pulse) subProgram; // subProgram = new SubProgram.Pulse(session, pulseProgram.getPower(), pulseProgram.getDestPulse() + change); // } // } // }
import org.jergometer.control.BikeProgram;
package org.jergometer.model; /** * Filter for bike sessions. */ public class BikeSessionFilter { public enum Type { off, program, programDir } private Type type = Type.off;
// Path: src/org/jergometer/control/BikeProgram.java // public class BikeProgram extends HoldsFile { // private int power = 0; // private String programName; // private BikeProgramData programData; // private BikeSession session; // private SubProgram subProgram; // private Iterator<BikeProgramData.TimeEvent> eventIterator; // private BikeProgramData.TimeEvent nextEvent; // private int idleCounter = 0; // // public BikeProgram(File file, String programName, BikeProgramData programData) { // super(file); // this.programName = programName.replaceAll("\\\\", "/"); // this.programData = programData; // eventIterator = programData.getEvents().iterator(); // nextEvent = eventIterator.next(); // doActions(nextEvent.getActions()); // nextEvent = eventIterator.hasNext() ? eventIterator.next() : null; // } // // /** // * Adds the new data record to the session and returns true if user is not cycling anymore. // * // * @param dataRecord new data record // * @return true if user does not cycle anymore // */ // public UpdateStatus update(DataRecord dataRecord) { // if(session.update(dataRecord)) { // if(nextEvent != null && nextEvent.getTime() == session.getDuration()) { // doActions(nextEvent.getActions()); // nextEvent = eventIterator.hasNext() ? eventIterator.next() : null; // } else { // subProgram.update(dataRecord); // } // idleCounter = 0; // return UpdateStatus.cycle; // } else { // if (++idleCounter >= 4) { // return UpdateStatus.pulse; // } else { // return UpdateStatus.idle; // } // } // } // // private void doActions(ArrayList<BikeProgramData.Action> actions) { // BikeProgramData.Action currentAction; // // for (BikeProgramData.Action action : actions) { // doAction(action); // // currentAction = action; // } // } // // private void doAction(BikeProgramData.Action action) { // if(action.getType() == BikeProgramData.Action.Type.power) { // power = action.getValue(); // subProgram = new SubProgram.Power(session, power); // } // else if(action.getType() == BikeProgramData.Action.Type.pulse) { // int pulse = action.getValue(); // subProgram = new SubProgram.Pulse(session, power, pulse); // } // } // // public int getPower() { // power = subProgram.getPower(); // return power; // } // // public String getProgramAction() { // return subProgram.getActionName(); // } // // public String getProgramName() { // return programName; // } // // public BikeProgramData getProgramData() { // return programData; // } // // public BikeSession newSession() { // return session = new BikeSession(programName, programData.getDuration()); // } // // public BikeSession getSession() { // return session; // } // // public String toString() { // return programData.getName(); // } // // public void changeInteractively(int change) { // if (subProgram instanceof SubProgram.Power) { // subProgram = new SubProgram.Power(session, subProgram.getPower() + change*5); // } // if (subProgram instanceof SubProgram.Pulse) { // SubProgram.Pulse pulseProgram = (SubProgram.Pulse) subProgram; // subProgram = new SubProgram.Pulse(session, pulseProgram.getPower(), pulseProgram.getDestPulse() + change); // } // } // } // Path: src/org/jergometer/model/BikeSessionFilter.java import org.jergometer.control.BikeProgram; package org.jergometer.model; /** * Filter for bike sessions. */ public class BikeSessionFilter { public enum Type { off, program, programDir } private Type type = Type.off;
private BikeProgram bikeProgram;
android-notes/SwissArmyKnife
saklib/src/main/java/com/wanjian/sak/layer/impl/VerticalMeasureView.java
// Path: sak-nop/src/main/java/com/wanjian/sak/converter/ISizeConverter.java // public abstract class ISizeConverter { // public static ISizeConverter CONVERTER; // // public abstract String desc(); // // public abstract Size convert(Context context, float length); // // public abstract int recovery(Context context, float length); // // } // // Path: saklib/src/main/java/com/wanjian/sak/layer/ISize.java // public interface ISize { // void onSizeConvertChange(ISizeConverter converter); // } // // Path: saklib/src/main/java/com/wanjian/sak/layer/Layer.java // public abstract class Layer implements EventListener { // private ViewRootImpl viewRootImpl; // private Config config; // private Application application; // private LayerRoot layerRoot; // private RenderNodeCompact renderNode; // private View rootView; // private boolean isEnable; // // public Layer() { // // } // // public RenderNodeCompact getRenderNode() { // return renderNode; // } // // public final void attach(Config config, ViewRootImpl viewRoot, View rootView, Application application, LayerRoot layerRoot) { // this.viewRootImpl = viewRoot; // this.config = config; // this.application = application; // this.layerRoot = layerRoot; // this.rootView = rootView; // renderNode = RenderNodeCompact.create(getClass().getName()); // onAttach(getRootView()); // } // // // // // private final Canvas requireCanvas() { // // return CanvasHolder.requireCanvasFor(viewRootImpl); // // } // // // // private final void releaseCanvas() { // // CanvasHolder.releaseCanvasFor(viewRootImpl); // // } // // protected void invalidate() { // // renderNode.setLeftTopRightBottom(0, 0, getRootView().getWidth(), getRootView().getHeight()); // // DisplayListCanvas displayListCanvas = renderNode.start(getRootView().getWidth(), getRootView().getHeight()); // // onDraw(displayListCanvas); // // renderNode.end(displayListCanvas); // View view = getRootView(); // if (view == null) { // return; // } // Canvas canvas = renderNode.beginRecording(view.getWidth(), view.getHeight()); // draw(canvas); // renderNode.endRecording(canvas); // layerRoot.invalidate(); // } // // private void draw(Canvas canvas) { // if (isEnable == false) { // canvas.drawColor(0); // return; // } // onDraw(canvas); // } // // public final boolean isEnable() { // return isEnable; // } // // public final void enable(boolean enable) { // isEnable = enable; // invalidate(); // onEnableChange(enable); // } // // protected void onEnableChange(boolean enable) { // } // // protected void onDraw(Canvas canvas) { // // } // // @Override // public final void beforeTraversal(View rootView) { // onBeforeTraversal(rootView); // } // // @Override // public final void afterTraversal(View rootView) { // onAfterTraversal(rootView); // } // // @Override // public final boolean beforeInputEvent(View rootView, InputEvent event) { // //rootView.invalidate(); // return onBeforeInputEvent(rootView, event); // } // // @Override // public final void afterInputEvent(View rootView, InputEvent event) { // //rootView.invalidate(); // onAfterInputEvent(rootView, event); // } // // protected View getRootView() { // return rootView; // } // // protected void onBeforeTraversal(View rootView) { // } // // protected void onAfterTraversal(View rootView) { // } // // protected boolean onBeforeInputEvent(View rootView, InputEvent event) { // return false; // } // // protected void onAfterInputEvent(View rootView, InputEvent event) { // } // // protected void onAttach(View rootView) { // // } // // protected Application getContext() { // return application; // } // } // // Path: saklib/src/main/java/com/wanjian/sak/utils/ScreenUtils.java // public class ScreenUtils { // // public static int dp2px(Context context, int dip) { // float density = context.getResources().getDisplayMetrics().density; // return (int) (dip * density + 0.5); // } // // public static int px2dp(Context context, float pxValue) { // final float scale = context.getResources().getDisplayMetrics().density; // return (int) (pxValue / scale + 0.5f); // } // // }
import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.view.InputEvent; import android.view.MotionEvent; import android.view.View; import com.wanjian.sak.converter.ISizeConverter; import com.wanjian.sak.layer.ISize; import com.wanjian.sak.layer.Layer; import com.wanjian.sak.utils.ScreenUtils;
package com.wanjian.sak.layer.impl; /** * Created by wanjian on 2016/11/10. */ public class VerticalMeasureView extends Layer implements ISize { protected Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); protected int m20DP; protected int maxHeight; protected int minHeight; private int width; private boolean consume; private float lastX, lastY; private Rect rect = new Rect(); @Override protected void onAttach(View rootView) { super.onAttach(rootView); init(); } private void init() { mPaint.setColor(Color.BLACK);
// Path: sak-nop/src/main/java/com/wanjian/sak/converter/ISizeConverter.java // public abstract class ISizeConverter { // public static ISizeConverter CONVERTER; // // public abstract String desc(); // // public abstract Size convert(Context context, float length); // // public abstract int recovery(Context context, float length); // // } // // Path: saklib/src/main/java/com/wanjian/sak/layer/ISize.java // public interface ISize { // void onSizeConvertChange(ISizeConverter converter); // } // // Path: saklib/src/main/java/com/wanjian/sak/layer/Layer.java // public abstract class Layer implements EventListener { // private ViewRootImpl viewRootImpl; // private Config config; // private Application application; // private LayerRoot layerRoot; // private RenderNodeCompact renderNode; // private View rootView; // private boolean isEnable; // // public Layer() { // // } // // public RenderNodeCompact getRenderNode() { // return renderNode; // } // // public final void attach(Config config, ViewRootImpl viewRoot, View rootView, Application application, LayerRoot layerRoot) { // this.viewRootImpl = viewRoot; // this.config = config; // this.application = application; // this.layerRoot = layerRoot; // this.rootView = rootView; // renderNode = RenderNodeCompact.create(getClass().getName()); // onAttach(getRootView()); // } // // // // // private final Canvas requireCanvas() { // // return CanvasHolder.requireCanvasFor(viewRootImpl); // // } // // // // private final void releaseCanvas() { // // CanvasHolder.releaseCanvasFor(viewRootImpl); // // } // // protected void invalidate() { // // renderNode.setLeftTopRightBottom(0, 0, getRootView().getWidth(), getRootView().getHeight()); // // DisplayListCanvas displayListCanvas = renderNode.start(getRootView().getWidth(), getRootView().getHeight()); // // onDraw(displayListCanvas); // // renderNode.end(displayListCanvas); // View view = getRootView(); // if (view == null) { // return; // } // Canvas canvas = renderNode.beginRecording(view.getWidth(), view.getHeight()); // draw(canvas); // renderNode.endRecording(canvas); // layerRoot.invalidate(); // } // // private void draw(Canvas canvas) { // if (isEnable == false) { // canvas.drawColor(0); // return; // } // onDraw(canvas); // } // // public final boolean isEnable() { // return isEnable; // } // // public final void enable(boolean enable) { // isEnable = enable; // invalidate(); // onEnableChange(enable); // } // // protected void onEnableChange(boolean enable) { // } // // protected void onDraw(Canvas canvas) { // // } // // @Override // public final void beforeTraversal(View rootView) { // onBeforeTraversal(rootView); // } // // @Override // public final void afterTraversal(View rootView) { // onAfterTraversal(rootView); // } // // @Override // public final boolean beforeInputEvent(View rootView, InputEvent event) { // //rootView.invalidate(); // return onBeforeInputEvent(rootView, event); // } // // @Override // public final void afterInputEvent(View rootView, InputEvent event) { // //rootView.invalidate(); // onAfterInputEvent(rootView, event); // } // // protected View getRootView() { // return rootView; // } // // protected void onBeforeTraversal(View rootView) { // } // // protected void onAfterTraversal(View rootView) { // } // // protected boolean onBeforeInputEvent(View rootView, InputEvent event) { // return false; // } // // protected void onAfterInputEvent(View rootView, InputEvent event) { // } // // protected void onAttach(View rootView) { // // } // // protected Application getContext() { // return application; // } // } // // Path: saklib/src/main/java/com/wanjian/sak/utils/ScreenUtils.java // public class ScreenUtils { // // public static int dp2px(Context context, int dip) { // float density = context.getResources().getDisplayMetrics().density; // return (int) (dip * density + 0.5); // } // // public static int px2dp(Context context, float pxValue) { // final float scale = context.getResources().getDisplayMetrics().density; // return (int) (pxValue / scale + 0.5f); // } // // } // Path: saklib/src/main/java/com/wanjian/sak/layer/impl/VerticalMeasureView.java import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.view.InputEvent; import android.view.MotionEvent; import android.view.View; import com.wanjian.sak.converter.ISizeConverter; import com.wanjian.sak.layer.ISize; import com.wanjian.sak.layer.Layer; import com.wanjian.sak.utils.ScreenUtils; package com.wanjian.sak.layer.impl; /** * Created by wanjian on 2016/11/10. */ public class VerticalMeasureView extends Layer implements ISize { protected Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); protected int m20DP; protected int maxHeight; protected int minHeight; private int width; private boolean consume; private float lastX, lastY; private Rect rect = new Rect(); @Override protected void onAttach(View rootView) { super.onAttach(rootView); init(); } private void init() { mPaint.setColor(Color.BLACK);
m20DP = ScreenUtils.dp2px(getContext(), 20);
android-notes/SwissArmyKnife
saklib/src/main/java/com/wanjian/sak/layer/impl/HorizontalMeasureView.java
// Path: sak-nop/src/main/java/com/wanjian/sak/converter/ISizeConverter.java // public abstract class ISizeConverter { // public static ISizeConverter CONVERTER; // // public abstract String desc(); // // public abstract Size convert(Context context, float length); // // public abstract int recovery(Context context, float length); // // } // // Path: saklib/src/main/java/com/wanjian/sak/layer/ISize.java // public interface ISize { // void onSizeConvertChange(ISizeConverter converter); // } // // Path: saklib/src/main/java/com/wanjian/sak/layer/Layer.java // public abstract class Layer implements EventListener { // private ViewRootImpl viewRootImpl; // private Config config; // private Application application; // private LayerRoot layerRoot; // private RenderNodeCompact renderNode; // private View rootView; // private boolean isEnable; // // public Layer() { // // } // // public RenderNodeCompact getRenderNode() { // return renderNode; // } // // public final void attach(Config config, ViewRootImpl viewRoot, View rootView, Application application, LayerRoot layerRoot) { // this.viewRootImpl = viewRoot; // this.config = config; // this.application = application; // this.layerRoot = layerRoot; // this.rootView = rootView; // renderNode = RenderNodeCompact.create(getClass().getName()); // onAttach(getRootView()); // } // // // // // private final Canvas requireCanvas() { // // return CanvasHolder.requireCanvasFor(viewRootImpl); // // } // // // // private final void releaseCanvas() { // // CanvasHolder.releaseCanvasFor(viewRootImpl); // // } // // protected void invalidate() { // // renderNode.setLeftTopRightBottom(0, 0, getRootView().getWidth(), getRootView().getHeight()); // // DisplayListCanvas displayListCanvas = renderNode.start(getRootView().getWidth(), getRootView().getHeight()); // // onDraw(displayListCanvas); // // renderNode.end(displayListCanvas); // View view = getRootView(); // if (view == null) { // return; // } // Canvas canvas = renderNode.beginRecording(view.getWidth(), view.getHeight()); // draw(canvas); // renderNode.endRecording(canvas); // layerRoot.invalidate(); // } // // private void draw(Canvas canvas) { // if (isEnable == false) { // canvas.drawColor(0); // return; // } // onDraw(canvas); // } // // public final boolean isEnable() { // return isEnable; // } // // public final void enable(boolean enable) { // isEnable = enable; // invalidate(); // onEnableChange(enable); // } // // protected void onEnableChange(boolean enable) { // } // // protected void onDraw(Canvas canvas) { // // } // // @Override // public final void beforeTraversal(View rootView) { // onBeforeTraversal(rootView); // } // // @Override // public final void afterTraversal(View rootView) { // onAfterTraversal(rootView); // } // // @Override // public final boolean beforeInputEvent(View rootView, InputEvent event) { // //rootView.invalidate(); // return onBeforeInputEvent(rootView, event); // } // // @Override // public final void afterInputEvent(View rootView, InputEvent event) { // //rootView.invalidate(); // onAfterInputEvent(rootView, event); // } // // protected View getRootView() { // return rootView; // } // // protected void onBeforeTraversal(View rootView) { // } // // protected void onAfterTraversal(View rootView) { // } // // protected boolean onBeforeInputEvent(View rootView, InputEvent event) { // return false; // } // // protected void onAfterInputEvent(View rootView, InputEvent event) { // } // // protected void onAttach(View rootView) { // // } // // protected Application getContext() { // return application; // } // } // // Path: saklib/src/main/java/com/wanjian/sak/utils/ScreenUtils.java // public class ScreenUtils { // // public static int dp2px(Context context, int dip) { // float density = context.getResources().getDisplayMetrics().density; // return (int) (dip * density + 0.5); // } // // public static int px2dp(Context context, float pxValue) { // final float scale = context.getResources().getDisplayMetrics().density; // return (int) (pxValue / scale + 0.5f); // } // // }
import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.view.InputEvent; import android.view.MotionEvent; import android.view.View; import com.wanjian.sak.converter.ISizeConverter; import com.wanjian.sak.layer.ISize; import com.wanjian.sak.layer.Layer; import com.wanjian.sak.utils.ScreenUtils;
package com.wanjian.sak.layer.impl; /** * Created by wanjian on 2016/11/10. */ public class HorizontalMeasureView extends Layer implements ISize { protected Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); protected int m20DP; protected int maxHeight; protected int minHeight; private int height; private boolean consume; private float lastX, lastY; private Rect rect = new Rect(); @Override protected void onAttach(View rootView) { super.onAttach(rootView); init(); } private void init() { mPaint.setColor(Color.BLACK);
// Path: sak-nop/src/main/java/com/wanjian/sak/converter/ISizeConverter.java // public abstract class ISizeConverter { // public static ISizeConverter CONVERTER; // // public abstract String desc(); // // public abstract Size convert(Context context, float length); // // public abstract int recovery(Context context, float length); // // } // // Path: saklib/src/main/java/com/wanjian/sak/layer/ISize.java // public interface ISize { // void onSizeConvertChange(ISizeConverter converter); // } // // Path: saklib/src/main/java/com/wanjian/sak/layer/Layer.java // public abstract class Layer implements EventListener { // private ViewRootImpl viewRootImpl; // private Config config; // private Application application; // private LayerRoot layerRoot; // private RenderNodeCompact renderNode; // private View rootView; // private boolean isEnable; // // public Layer() { // // } // // public RenderNodeCompact getRenderNode() { // return renderNode; // } // // public final void attach(Config config, ViewRootImpl viewRoot, View rootView, Application application, LayerRoot layerRoot) { // this.viewRootImpl = viewRoot; // this.config = config; // this.application = application; // this.layerRoot = layerRoot; // this.rootView = rootView; // renderNode = RenderNodeCompact.create(getClass().getName()); // onAttach(getRootView()); // } // // // // // private final Canvas requireCanvas() { // // return CanvasHolder.requireCanvasFor(viewRootImpl); // // } // // // // private final void releaseCanvas() { // // CanvasHolder.releaseCanvasFor(viewRootImpl); // // } // // protected void invalidate() { // // renderNode.setLeftTopRightBottom(0, 0, getRootView().getWidth(), getRootView().getHeight()); // // DisplayListCanvas displayListCanvas = renderNode.start(getRootView().getWidth(), getRootView().getHeight()); // // onDraw(displayListCanvas); // // renderNode.end(displayListCanvas); // View view = getRootView(); // if (view == null) { // return; // } // Canvas canvas = renderNode.beginRecording(view.getWidth(), view.getHeight()); // draw(canvas); // renderNode.endRecording(canvas); // layerRoot.invalidate(); // } // // private void draw(Canvas canvas) { // if (isEnable == false) { // canvas.drawColor(0); // return; // } // onDraw(canvas); // } // // public final boolean isEnable() { // return isEnable; // } // // public final void enable(boolean enable) { // isEnable = enable; // invalidate(); // onEnableChange(enable); // } // // protected void onEnableChange(boolean enable) { // } // // protected void onDraw(Canvas canvas) { // // } // // @Override // public final void beforeTraversal(View rootView) { // onBeforeTraversal(rootView); // } // // @Override // public final void afterTraversal(View rootView) { // onAfterTraversal(rootView); // } // // @Override // public final boolean beforeInputEvent(View rootView, InputEvent event) { // //rootView.invalidate(); // return onBeforeInputEvent(rootView, event); // } // // @Override // public final void afterInputEvent(View rootView, InputEvent event) { // //rootView.invalidate(); // onAfterInputEvent(rootView, event); // } // // protected View getRootView() { // return rootView; // } // // protected void onBeforeTraversal(View rootView) { // } // // protected void onAfterTraversal(View rootView) { // } // // protected boolean onBeforeInputEvent(View rootView, InputEvent event) { // return false; // } // // protected void onAfterInputEvent(View rootView, InputEvent event) { // } // // protected void onAttach(View rootView) { // // } // // protected Application getContext() { // return application; // } // } // // Path: saklib/src/main/java/com/wanjian/sak/utils/ScreenUtils.java // public class ScreenUtils { // // public static int dp2px(Context context, int dip) { // float density = context.getResources().getDisplayMetrics().density; // return (int) (dip * density + 0.5); // } // // public static int px2dp(Context context, float pxValue) { // final float scale = context.getResources().getDisplayMetrics().density; // return (int) (pxValue / scale + 0.5f); // } // // } // Path: saklib/src/main/java/com/wanjian/sak/layer/impl/HorizontalMeasureView.java import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.view.InputEvent; import android.view.MotionEvent; import android.view.View; import com.wanjian.sak.converter.ISizeConverter; import com.wanjian.sak.layer.ISize; import com.wanjian.sak.layer.Layer; import com.wanjian.sak.utils.ScreenUtils; package com.wanjian.sak.layer.impl; /** * Created by wanjian on 2016/11/10. */ public class HorizontalMeasureView extends Layer implements ISize { protected Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); protected int m20DP; protected int maxHeight; protected int minHeight; private int height; private boolean consume; private float lastX, lastY; private Rect rect = new Rect(); @Override protected void onAttach(View rootView) { super.onAttach(rootView); init(); } private void init() { mPaint.setColor(Color.BLACK);
m20DP = ScreenUtils.dp2px(getContext(), 20);
android-notes/SwissArmyKnife
saklib/src/main/java/com/wanjian/sak/system/canvas/compact/SoftCanvas.java
// Path: systemlib/src/main/java/android/view/ViewRootImpl.java // public final class ViewRootImpl implements ViewParent { // // public View getView() { // return null; // } // // // @Override // public void requestLayout() { // // } // // @Override // public boolean isLayoutRequested() { // return false; // } // // @Override // public void requestTransparentRegion(View child) { // // } // // @Override // public void invalidateChild(View child, Rect r) { // // } // // @Override // public ViewParent invalidateChildInParent(int[] location, Rect r) { // return null; // } // // @Override // public ViewParent getParent() { // return null; // } // // @Override // public void requestChildFocus(View child, View focused) { // // } // // @Override // public void recomputeViewAttributes(View child) { // // } // // @Override // public void clearChildFocus(View child) { // // } // // @Override // public boolean getChildVisibleRect(View child, Rect r, Point offset) { // return false; // } // // @Override // public View focusSearch(View v, int direction) { // return null; // } // // @Override // public View keyboardNavigationClusterSearch(View currentCluster, int direction) { // return null; // } // // @Override // public void bringChildToFront(View child) { // // } // // @Override // public void focusableViewAvailable(View v) { // // } // // @Override // public boolean showContextMenuForChild(View originalView) { // return false; // } // // @Override // public boolean showContextMenuForChild(View originalView, float x, float y) { // return false; // } // // @Override // public void createContextMenu(ContextMenu menu) { // // } // // @Override // public ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback) { // return null; // } // // @Override // public ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback, int type) { // return null; // } // // @Override // public void childDrawableStateChanged(View child) { // // } // // @Override // public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) { // // } // // @Override // public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) { // return false; // } // // @Override // public boolean requestSendAccessibilityEvent(View child, AccessibilityEvent event) { // return false; // } // // @Override // public void childHasTransientStateChanged(View child, boolean hasTransientState) { // // } // // @Override // public void requestFitSystemWindows() { // // } // // @Override // public ViewParent getParentForAccessibility() { // return null; // } // // @Override // public void notifySubtreeAccessibilityStateChanged(View child, View source, int changeType) { // // } // // @Override // public boolean canResolveLayoutDirection() { // return false; // } // // @Override // public boolean isLayoutDirectionResolved() { // return false; // } // // @Override // public int getLayoutDirection() { // return 0; // } // // @Override // public boolean canResolveTextDirection() { // return false; // } // // @Override // public boolean isTextDirectionResolved() { // return false; // } // // @Override // public int getTextDirection() { // return 0; // } // // @Override // public boolean canResolveTextAlignment() { // return false; // } // // @Override // public boolean isTextAlignmentResolved() { // return false; // } // // @Override // public int getTextAlignment() { // return 0; // } // // @Override // public boolean onStartNestedScroll(View child, View target, int nestedScrollAxes) { // return false; // } // // @Override // public void onNestedScrollAccepted(View child, View target, int nestedScrollAxes) { // // } // // @Override // public void onStopNestedScroll(View target) { // // } // // @Override // public void onNestedScroll(View target, int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed) { // // } // // @Override // public void onNestedPreScroll(View target, int dx, int dy, int[] consumed) { // // } // // @Override // public boolean onNestedFling(View target, float velocityX, float velocityY, boolean consumed) { // return false; // } // // @Override // public boolean onNestedPreFling(View target, float velocityX, float velocityY) { // return false; // } // // @Override // public boolean onNestedPrePerformAccessibilityAction(View target, int action, Bundle arguments) { // return false; // } // }
import android.graphics.Canvas; import android.graphics.Rect; import android.view.Surface; import android.view.View; import android.view.ViewRootImpl; import java.lang.reflect.Field;
package com.wanjian.sak.system.canvas.compact; class SoftCanvas extends CanvasCompact { private int count; private Rect rect = new Rect(); private Canvas canvas; private Surface surface;
// Path: systemlib/src/main/java/android/view/ViewRootImpl.java // public final class ViewRootImpl implements ViewParent { // // public View getView() { // return null; // } // // // @Override // public void requestLayout() { // // } // // @Override // public boolean isLayoutRequested() { // return false; // } // // @Override // public void requestTransparentRegion(View child) { // // } // // @Override // public void invalidateChild(View child, Rect r) { // // } // // @Override // public ViewParent invalidateChildInParent(int[] location, Rect r) { // return null; // } // // @Override // public ViewParent getParent() { // return null; // } // // @Override // public void requestChildFocus(View child, View focused) { // // } // // @Override // public void recomputeViewAttributes(View child) { // // } // // @Override // public void clearChildFocus(View child) { // // } // // @Override // public boolean getChildVisibleRect(View child, Rect r, Point offset) { // return false; // } // // @Override // public View focusSearch(View v, int direction) { // return null; // } // // @Override // public View keyboardNavigationClusterSearch(View currentCluster, int direction) { // return null; // } // // @Override // public void bringChildToFront(View child) { // // } // // @Override // public void focusableViewAvailable(View v) { // // } // // @Override // public boolean showContextMenuForChild(View originalView) { // return false; // } // // @Override // public boolean showContextMenuForChild(View originalView, float x, float y) { // return false; // } // // @Override // public void createContextMenu(ContextMenu menu) { // // } // // @Override // public ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback) { // return null; // } // // @Override // public ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback, int type) { // return null; // } // // @Override // public void childDrawableStateChanged(View child) { // // } // // @Override // public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) { // // } // // @Override // public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) { // return false; // } // // @Override // public boolean requestSendAccessibilityEvent(View child, AccessibilityEvent event) { // return false; // } // // @Override // public void childHasTransientStateChanged(View child, boolean hasTransientState) { // // } // // @Override // public void requestFitSystemWindows() { // // } // // @Override // public ViewParent getParentForAccessibility() { // return null; // } // // @Override // public void notifySubtreeAccessibilityStateChanged(View child, View source, int changeType) { // // } // // @Override // public boolean canResolveLayoutDirection() { // return false; // } // // @Override // public boolean isLayoutDirectionResolved() { // return false; // } // // @Override // public int getLayoutDirection() { // return 0; // } // // @Override // public boolean canResolveTextDirection() { // return false; // } // // @Override // public boolean isTextDirectionResolved() { // return false; // } // // @Override // public int getTextDirection() { // return 0; // } // // @Override // public boolean canResolveTextAlignment() { // return false; // } // // @Override // public boolean isTextAlignmentResolved() { // return false; // } // // @Override // public int getTextAlignment() { // return 0; // } // // @Override // public boolean onStartNestedScroll(View child, View target, int nestedScrollAxes) { // return false; // } // // @Override // public void onNestedScrollAccepted(View child, View target, int nestedScrollAxes) { // // } // // @Override // public void onStopNestedScroll(View target) { // // } // // @Override // public void onNestedScroll(View target, int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed) { // // } // // @Override // public void onNestedPreScroll(View target, int dx, int dy, int[] consumed) { // // } // // @Override // public boolean onNestedFling(View target, float velocityX, float velocityY, boolean consumed) { // return false; // } // // @Override // public boolean onNestedPreFling(View target, float velocityX, float velocityY) { // return false; // } // // @Override // public boolean onNestedPrePerformAccessibilityAction(View target, int action, Bundle arguments) { // return false; // } // } // Path: saklib/src/main/java/com/wanjian/sak/system/canvas/compact/SoftCanvas.java import android.graphics.Canvas; import android.graphics.Rect; import android.view.Surface; import android.view.View; import android.view.ViewRootImpl; import java.lang.reflect.Field; package com.wanjian.sak.system.canvas.compact; class SoftCanvas extends CanvasCompact { private int count; private Rect rect = new Rect(); private Canvas canvas; private Surface surface;
SoftCanvas(ViewRootImpl viewRootImpl) {
android-notes/SwissArmyKnife
saklib/src/main/java/com/wanjian/sak/layer/impl/TranslationLayerView.java
// Path: sak-nop/src/main/java/com/wanjian/sak/converter/ISizeConverter.java // public abstract class ISizeConverter { // public static ISizeConverter CONVERTER; // // public abstract String desc(); // // public abstract Size convert(Context context, float length); // // public abstract int recovery(Context context, float length); // // } // // Path: saklib/src/main/java/com/wanjian/sak/layer/ISize.java // public interface ISize { // void onSizeConvertChange(ISizeConverter converter); // } // // Path: saklib/src/main/java/com/wanjian/sak/layer/Layer.java // public abstract class Layer implements EventListener { // private ViewRootImpl viewRootImpl; // private Config config; // private Application application; // private LayerRoot layerRoot; // private RenderNodeCompact renderNode; // private View rootView; // private boolean isEnable; // // public Layer() { // // } // // public RenderNodeCompact getRenderNode() { // return renderNode; // } // // public final void attach(Config config, ViewRootImpl viewRoot, View rootView, Application application, LayerRoot layerRoot) { // this.viewRootImpl = viewRoot; // this.config = config; // this.application = application; // this.layerRoot = layerRoot; // this.rootView = rootView; // renderNode = RenderNodeCompact.create(getClass().getName()); // onAttach(getRootView()); // } // // // // // private final Canvas requireCanvas() { // // return CanvasHolder.requireCanvasFor(viewRootImpl); // // } // // // // private final void releaseCanvas() { // // CanvasHolder.releaseCanvasFor(viewRootImpl); // // } // // protected void invalidate() { // // renderNode.setLeftTopRightBottom(0, 0, getRootView().getWidth(), getRootView().getHeight()); // // DisplayListCanvas displayListCanvas = renderNode.start(getRootView().getWidth(), getRootView().getHeight()); // // onDraw(displayListCanvas); // // renderNode.end(displayListCanvas); // View view = getRootView(); // if (view == null) { // return; // } // Canvas canvas = renderNode.beginRecording(view.getWidth(), view.getHeight()); // draw(canvas); // renderNode.endRecording(canvas); // layerRoot.invalidate(); // } // // private void draw(Canvas canvas) { // if (isEnable == false) { // canvas.drawColor(0); // return; // } // onDraw(canvas); // } // // public final boolean isEnable() { // return isEnable; // } // // public final void enable(boolean enable) { // isEnable = enable; // invalidate(); // onEnableChange(enable); // } // // protected void onEnableChange(boolean enable) { // } // // protected void onDraw(Canvas canvas) { // // } // // @Override // public final void beforeTraversal(View rootView) { // onBeforeTraversal(rootView); // } // // @Override // public final void afterTraversal(View rootView) { // onAfterTraversal(rootView); // } // // @Override // public final boolean beforeInputEvent(View rootView, InputEvent event) { // //rootView.invalidate(); // return onBeforeInputEvent(rootView, event); // } // // @Override // public final void afterInputEvent(View rootView, InputEvent event) { // //rootView.invalidate(); // onAfterInputEvent(rootView, event); // } // // protected View getRootView() { // return rootView; // } // // protected void onBeforeTraversal(View rootView) { // } // // protected void onAfterTraversal(View rootView) { // } // // protected boolean onBeforeInputEvent(View rootView, InputEvent event) { // return false; // } // // protected void onAfterInputEvent(View rootView, InputEvent event) { // } // // protected void onAttach(View rootView) { // // } // // protected Application getContext() { // return application; // } // } // // Path: saklib/src/main/java/com/wanjian/sak/utils/ScreenUtils.java // public class ScreenUtils { // // public static int dp2px(Context context, int dip) { // float density = context.getResources().getDisplayMetrics().density; // return (int) (dip * density + 0.5); // } // // public static int px2dp(Context context, float pxValue) { // final float scale = context.getResources().getDisplayMetrics().density; // return (int) (pxValue / scale + 0.5f); // } // // }
import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.support.v4.view.GestureDetectorCompat; import android.view.GestureDetector; import android.view.InputEvent; import android.view.MotionEvent; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewGroup; import com.wanjian.sak.converter.ISizeConverter; import com.wanjian.sak.layer.ISize; import com.wanjian.sak.layer.Layer; import com.wanjian.sak.utils.ScreenUtils; import static android.view.View.VISIBLE;
package com.wanjian.sak.layer.impl; public class TranslationLayerView extends Layer implements ISize { private int mTxtSize; private int[] mLocation = new int[2]; private Paint mPaint;
// Path: sak-nop/src/main/java/com/wanjian/sak/converter/ISizeConverter.java // public abstract class ISizeConverter { // public static ISizeConverter CONVERTER; // // public abstract String desc(); // // public abstract Size convert(Context context, float length); // // public abstract int recovery(Context context, float length); // // } // // Path: saklib/src/main/java/com/wanjian/sak/layer/ISize.java // public interface ISize { // void onSizeConvertChange(ISizeConverter converter); // } // // Path: saklib/src/main/java/com/wanjian/sak/layer/Layer.java // public abstract class Layer implements EventListener { // private ViewRootImpl viewRootImpl; // private Config config; // private Application application; // private LayerRoot layerRoot; // private RenderNodeCompact renderNode; // private View rootView; // private boolean isEnable; // // public Layer() { // // } // // public RenderNodeCompact getRenderNode() { // return renderNode; // } // // public final void attach(Config config, ViewRootImpl viewRoot, View rootView, Application application, LayerRoot layerRoot) { // this.viewRootImpl = viewRoot; // this.config = config; // this.application = application; // this.layerRoot = layerRoot; // this.rootView = rootView; // renderNode = RenderNodeCompact.create(getClass().getName()); // onAttach(getRootView()); // } // // // // // private final Canvas requireCanvas() { // // return CanvasHolder.requireCanvasFor(viewRootImpl); // // } // // // // private final void releaseCanvas() { // // CanvasHolder.releaseCanvasFor(viewRootImpl); // // } // // protected void invalidate() { // // renderNode.setLeftTopRightBottom(0, 0, getRootView().getWidth(), getRootView().getHeight()); // // DisplayListCanvas displayListCanvas = renderNode.start(getRootView().getWidth(), getRootView().getHeight()); // // onDraw(displayListCanvas); // // renderNode.end(displayListCanvas); // View view = getRootView(); // if (view == null) { // return; // } // Canvas canvas = renderNode.beginRecording(view.getWidth(), view.getHeight()); // draw(canvas); // renderNode.endRecording(canvas); // layerRoot.invalidate(); // } // // private void draw(Canvas canvas) { // if (isEnable == false) { // canvas.drawColor(0); // return; // } // onDraw(canvas); // } // // public final boolean isEnable() { // return isEnable; // } // // public final void enable(boolean enable) { // isEnable = enable; // invalidate(); // onEnableChange(enable); // } // // protected void onEnableChange(boolean enable) { // } // // protected void onDraw(Canvas canvas) { // // } // // @Override // public final void beforeTraversal(View rootView) { // onBeforeTraversal(rootView); // } // // @Override // public final void afterTraversal(View rootView) { // onAfterTraversal(rootView); // } // // @Override // public final boolean beforeInputEvent(View rootView, InputEvent event) { // //rootView.invalidate(); // return onBeforeInputEvent(rootView, event); // } // // @Override // public final void afterInputEvent(View rootView, InputEvent event) { // //rootView.invalidate(); // onAfterInputEvent(rootView, event); // } // // protected View getRootView() { // return rootView; // } // // protected void onBeforeTraversal(View rootView) { // } // // protected void onAfterTraversal(View rootView) { // } // // protected boolean onBeforeInputEvent(View rootView, InputEvent event) { // return false; // } // // protected void onAfterInputEvent(View rootView, InputEvent event) { // } // // protected void onAttach(View rootView) { // // } // // protected Application getContext() { // return application; // } // } // // Path: saklib/src/main/java/com/wanjian/sak/utils/ScreenUtils.java // public class ScreenUtils { // // public static int dp2px(Context context, int dip) { // float density = context.getResources().getDisplayMetrics().density; // return (int) (dip * density + 0.5); // } // // public static int px2dp(Context context, float pxValue) { // final float scale = context.getResources().getDisplayMetrics().density; // return (int) (pxValue / scale + 0.5f); // } // // } // Path: saklib/src/main/java/com/wanjian/sak/layer/impl/TranslationLayerView.java import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.support.v4.view.GestureDetectorCompat; import android.view.GestureDetector; import android.view.InputEvent; import android.view.MotionEvent; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewGroup; import com.wanjian.sak.converter.ISizeConverter; import com.wanjian.sak.layer.ISize; import com.wanjian.sak.layer.Layer; import com.wanjian.sak.utils.ScreenUtils; import static android.view.View.VISIBLE; package com.wanjian.sak.layer.impl; public class TranslationLayerView extends Layer implements ISize { private int mTxtSize; private int[] mLocation = new int[2]; private Paint mPaint;
private ISizeConverter mSizeConverter;
android-notes/SwissArmyKnife
sak-nop/src/main/java/com/wanjian/sak/config/Config.java
// Path: sak-nop/src/main/java/com/wanjian/sak/converter/ISizeConverter.java // public abstract class ISizeConverter { // public static ISizeConverter CONVERTER; // // public abstract String desc(); // // public abstract Size convert(Context context, float length); // // public abstract int recovery(Context context, float length); // // } // // Path: saklib/src/main/java/com/wanjian/sak/filter/ViewFilter.java // public abstract class ViewFilter { // public static ViewFilter FILTER = new ViewFilter() { // @Override // protected boolean apply(View view) { // return view.getVisibility() == View.VISIBLE; // } // }; // // // public final boolean filter(View view) { // return apply(view); // } // // protected abstract boolean apply(View view); // // @Override // public int hashCode() { // return getClass().hashCode(); // } // // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // return obj.getClass() == getClass(); // } // } // // Path: sak-nop/src/main/java/com/wanjian/sak/layer/AbsLayer.java // public abstract class AbsLayer extends FrameLayout { // // public AbsLayer(Context context) { // super(context); // } // // public void attachConfig(Config config) { // } // // public abstract String description(); // // public abstract Drawable icon(); // // public final void enable(boolean enable) { // } // // protected void onStateChange(boolean isEnable) { // // } // // public final boolean isEnable() { // return false; // } // // protected boolean isClipDraw() { // return false; // } // // protected int getStartRange() { // return 0; // } // // protected int getEndRange() { // return 0; // } // // public final void uiUpdate(Canvas canvas, View view) { // // } // // protected void onUiUpdate(Canvas canvas, View rootView) { // // } // // protected void onAttached(View rootView) { // } // // // protected void onDetached(View rootView) { // } // // protected int[] getLocationAndSize(View view) { // return null; // } // // protected int dp2px(int dip) { // return 0; // } // // protected int px2dp(float pxValue) { // return 0; // } // // protected ISizeConverter getSizeConverter() { // return null; // } // // protected ViewFilter getViewFilter() { // return null; // } // // protected void showWindow(View view, WindowManager.LayoutParams params) { // // } // // protected void updateWindow(View view, WindowManager.LayoutParams params) { // } // // protected void removeWindow(View view) { // } // // public ViewGroup.LayoutParams getLayoutParams(FrameLayout.LayoutParams params) { // return null; // } // // }
import android.content.Context; import com.wanjian.sak.converter.ISizeConverter; import com.wanjian.sak.filter.ViewFilter; import com.wanjian.sak.layer.AbsLayer; import java.util.List;
package com.wanjian.sak.config; /** * Created by wanjian on 2017/2/20. */ public class Config { public List<AbsLayer> getLayerViews() { return null; }
// Path: sak-nop/src/main/java/com/wanjian/sak/converter/ISizeConverter.java // public abstract class ISizeConverter { // public static ISizeConverter CONVERTER; // // public abstract String desc(); // // public abstract Size convert(Context context, float length); // // public abstract int recovery(Context context, float length); // // } // // Path: saklib/src/main/java/com/wanjian/sak/filter/ViewFilter.java // public abstract class ViewFilter { // public static ViewFilter FILTER = new ViewFilter() { // @Override // protected boolean apply(View view) { // return view.getVisibility() == View.VISIBLE; // } // }; // // // public final boolean filter(View view) { // return apply(view); // } // // protected abstract boolean apply(View view); // // @Override // public int hashCode() { // return getClass().hashCode(); // } // // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // return obj.getClass() == getClass(); // } // } // // Path: sak-nop/src/main/java/com/wanjian/sak/layer/AbsLayer.java // public abstract class AbsLayer extends FrameLayout { // // public AbsLayer(Context context) { // super(context); // } // // public void attachConfig(Config config) { // } // // public abstract String description(); // // public abstract Drawable icon(); // // public final void enable(boolean enable) { // } // // protected void onStateChange(boolean isEnable) { // // } // // public final boolean isEnable() { // return false; // } // // protected boolean isClipDraw() { // return false; // } // // protected int getStartRange() { // return 0; // } // // protected int getEndRange() { // return 0; // } // // public final void uiUpdate(Canvas canvas, View view) { // // } // // protected void onUiUpdate(Canvas canvas, View rootView) { // // } // // protected void onAttached(View rootView) { // } // // // protected void onDetached(View rootView) { // } // // protected int[] getLocationAndSize(View view) { // return null; // } // // protected int dp2px(int dip) { // return 0; // } // // protected int px2dp(float pxValue) { // return 0; // } // // protected ISizeConverter getSizeConverter() { // return null; // } // // protected ViewFilter getViewFilter() { // return null; // } // // protected void showWindow(View view, WindowManager.LayoutParams params) { // // } // // protected void updateWindow(View view, WindowManager.LayoutParams params) { // } // // protected void removeWindow(View view) { // } // // public ViewGroup.LayoutParams getLayoutParams(FrameLayout.LayoutParams params) { // return null; // } // // } // Path: sak-nop/src/main/java/com/wanjian/sak/config/Config.java import android.content.Context; import com.wanjian.sak.converter.ISizeConverter; import com.wanjian.sak.filter.ViewFilter; import com.wanjian.sak.layer.AbsLayer; import java.util.List; package com.wanjian.sak.config; /** * Created by wanjian on 2017/2/20. */ public class Config { public List<AbsLayer> getLayerViews() { return null; }
public List<ISizeConverter> getSizeConverters() {
android-notes/SwissArmyKnife
sak-nop/src/main/java/com/wanjian/sak/config/Config.java
// Path: sak-nop/src/main/java/com/wanjian/sak/converter/ISizeConverter.java // public abstract class ISizeConverter { // public static ISizeConverter CONVERTER; // // public abstract String desc(); // // public abstract Size convert(Context context, float length); // // public abstract int recovery(Context context, float length); // // } // // Path: saklib/src/main/java/com/wanjian/sak/filter/ViewFilter.java // public abstract class ViewFilter { // public static ViewFilter FILTER = new ViewFilter() { // @Override // protected boolean apply(View view) { // return view.getVisibility() == View.VISIBLE; // } // }; // // // public final boolean filter(View view) { // return apply(view); // } // // protected abstract boolean apply(View view); // // @Override // public int hashCode() { // return getClass().hashCode(); // } // // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // return obj.getClass() == getClass(); // } // } // // Path: sak-nop/src/main/java/com/wanjian/sak/layer/AbsLayer.java // public abstract class AbsLayer extends FrameLayout { // // public AbsLayer(Context context) { // super(context); // } // // public void attachConfig(Config config) { // } // // public abstract String description(); // // public abstract Drawable icon(); // // public final void enable(boolean enable) { // } // // protected void onStateChange(boolean isEnable) { // // } // // public final boolean isEnable() { // return false; // } // // protected boolean isClipDraw() { // return false; // } // // protected int getStartRange() { // return 0; // } // // protected int getEndRange() { // return 0; // } // // public final void uiUpdate(Canvas canvas, View view) { // // } // // protected void onUiUpdate(Canvas canvas, View rootView) { // // } // // protected void onAttached(View rootView) { // } // // // protected void onDetached(View rootView) { // } // // protected int[] getLocationAndSize(View view) { // return null; // } // // protected int dp2px(int dip) { // return 0; // } // // protected int px2dp(float pxValue) { // return 0; // } // // protected ISizeConverter getSizeConverter() { // return null; // } // // protected ViewFilter getViewFilter() { // return null; // } // // protected void showWindow(View view, WindowManager.LayoutParams params) { // // } // // protected void updateWindow(View view, WindowManager.LayoutParams params) { // } // // protected void removeWindow(View view) { // } // // public ViewGroup.LayoutParams getLayoutParams(FrameLayout.LayoutParams params) { // return null; // } // // }
import android.content.Context; import com.wanjian.sak.converter.ISizeConverter; import com.wanjian.sak.filter.ViewFilter; import com.wanjian.sak.layer.AbsLayer; import java.util.List;
} public boolean isClipDraw() { return false; } public void setClipDraw(boolean clipDraw) { } public int getMinRange() { return 0; } public int getMaxRange() { return 0; } public static class Build { public Build(Context context) { } public Build addSizeConverter(ISizeConverter sizeConverter) { return this; } public Build addLayerView(AbsLayer layerView) { return this; }
// Path: sak-nop/src/main/java/com/wanjian/sak/converter/ISizeConverter.java // public abstract class ISizeConverter { // public static ISizeConverter CONVERTER; // // public abstract String desc(); // // public abstract Size convert(Context context, float length); // // public abstract int recovery(Context context, float length); // // } // // Path: saklib/src/main/java/com/wanjian/sak/filter/ViewFilter.java // public abstract class ViewFilter { // public static ViewFilter FILTER = new ViewFilter() { // @Override // protected boolean apply(View view) { // return view.getVisibility() == View.VISIBLE; // } // }; // // // public final boolean filter(View view) { // return apply(view); // } // // protected abstract boolean apply(View view); // // @Override // public int hashCode() { // return getClass().hashCode(); // } // // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // return obj.getClass() == getClass(); // } // } // // Path: sak-nop/src/main/java/com/wanjian/sak/layer/AbsLayer.java // public abstract class AbsLayer extends FrameLayout { // // public AbsLayer(Context context) { // super(context); // } // // public void attachConfig(Config config) { // } // // public abstract String description(); // // public abstract Drawable icon(); // // public final void enable(boolean enable) { // } // // protected void onStateChange(boolean isEnable) { // // } // // public final boolean isEnable() { // return false; // } // // protected boolean isClipDraw() { // return false; // } // // protected int getStartRange() { // return 0; // } // // protected int getEndRange() { // return 0; // } // // public final void uiUpdate(Canvas canvas, View view) { // // } // // protected void onUiUpdate(Canvas canvas, View rootView) { // // } // // protected void onAttached(View rootView) { // } // // // protected void onDetached(View rootView) { // } // // protected int[] getLocationAndSize(View view) { // return null; // } // // protected int dp2px(int dip) { // return 0; // } // // protected int px2dp(float pxValue) { // return 0; // } // // protected ISizeConverter getSizeConverter() { // return null; // } // // protected ViewFilter getViewFilter() { // return null; // } // // protected void showWindow(View view, WindowManager.LayoutParams params) { // // } // // protected void updateWindow(View view, WindowManager.LayoutParams params) { // } // // protected void removeWindow(View view) { // } // // public ViewGroup.LayoutParams getLayoutParams(FrameLayout.LayoutParams params) { // return null; // } // // } // Path: sak-nop/src/main/java/com/wanjian/sak/config/Config.java import android.content.Context; import com.wanjian.sak.converter.ISizeConverter; import com.wanjian.sak.filter.ViewFilter; import com.wanjian.sak.layer.AbsLayer; import java.util.List; } public boolean isClipDraw() { return false; } public void setClipDraw(boolean clipDraw) { } public int getMinRange() { return 0; } public int getMaxRange() { return 0; } public static class Build { public Build(Context context) { } public Build addSizeConverter(ISizeConverter sizeConverter) { return this; } public Build addLayerView(AbsLayer layerView) { return this; }
public Build viewFilter(ViewFilter viewFilter) {
android-notes/SwissArmyKnife
systemlib/src/main/java/android/view/GLES20RecordingCanvas.java
// Path: systemlib/src/main/java/android/util/Pools.java // public final class Pools { // // /** // * Interface for managing a pool of objects. // * // * @param <T> The pooled type. // */ // public static interface Pool<T> { // // /** // * @return An instance from the pool if such, null otherwise. // */ // public T acquire(); // // /** // * Release an instance to the pool. // * // * @param instance The instance to release. // * @return Whether the instance was put in the pool. // * @throws IllegalStateException If the instance is already in the pool. // */ // public boolean release(T instance); // } // // private Pools() { // /* do nothing - hiding constructor */ // } // // /** // * Simple (non-synchronized) pool of objects. // * // * @param <T> The pooled type. // */ // public static class SimplePool<T> implements Pool<T> { // private final Object[] mPool; // // private int mPoolSize; // // /** // * Creates a new instance. // * // * @param maxPoolSize The max pool size. // * @throws IllegalArgumentException If the max pool size is less than zero. // */ // public SimplePool(int maxPoolSize) { // if (maxPoolSize <= 0) { // throw new IllegalArgumentException("The max pool size must be > 0"); // } // mPool = new Object[maxPoolSize]; // } // // @Override // @SuppressWarnings("unchecked") // public T acquire() { // if (mPoolSize > 0) { // final int lastPooledIndex = mPoolSize - 1; // T instance = (T) mPool[lastPooledIndex]; // mPool[lastPooledIndex] = null; // mPoolSize--; // return instance; // } // return null; // } // // @Override // public boolean release(T instance) { // if (isInPool(instance)) { // throw new IllegalStateException("Already in the pool!"); // } // if (mPoolSize < mPool.length) { // mPool[mPoolSize] = instance; // mPoolSize++; // return true; // } // return false; // } // // private boolean isInPool(T instance) { // for (int i = 0; i < mPoolSize; i++) { // if (mPool[i] == instance) { // return true; // } // } // return false; // } // } // // /** // * Synchronized pool of objects. // * // * @param <T> The pooled type. // */ // public static class SynchronizedPool<T> extends SimplePool<T> { // private final Object mLock; // // /** // * Creates a new instance. // * // * @param maxPoolSize The max pool size. // * @param lock an optional custom object to synchronize on // * @throws IllegalArgumentException If the max pool size is less than zero. // */ // public SynchronizedPool(int maxPoolSize, Object lock) { // super(maxPoolSize); // mLock = lock; // } // // /** // * @see #SynchronizedPool(int, Object) // */ // public SynchronizedPool(int maxPoolSize) { // this(maxPoolSize, new Object()); // } // // @Override // public T acquire() { // synchronized (mLock) { // return super.acquire(); // } // } // // @Override // public boolean release(T element) { // synchronized (mLock) { // return super.release(element); // } // } // } // }
import android.util.Pools;
package android.view; class GLES20RecordingCanvas { // The recording canvas pool should be large enough to handle a deeply nested // view hierarchy because display lists are generated recursively. private static final int POOL_LIMIT = 25; //android 5.0,5.1
// Path: systemlib/src/main/java/android/util/Pools.java // public final class Pools { // // /** // * Interface for managing a pool of objects. // * // * @param <T> The pooled type. // */ // public static interface Pool<T> { // // /** // * @return An instance from the pool if such, null otherwise. // */ // public T acquire(); // // /** // * Release an instance to the pool. // * // * @param instance The instance to release. // * @return Whether the instance was put in the pool. // * @throws IllegalStateException If the instance is already in the pool. // */ // public boolean release(T instance); // } // // private Pools() { // /* do nothing - hiding constructor */ // } // // /** // * Simple (non-synchronized) pool of objects. // * // * @param <T> The pooled type. // */ // public static class SimplePool<T> implements Pool<T> { // private final Object[] mPool; // // private int mPoolSize; // // /** // * Creates a new instance. // * // * @param maxPoolSize The max pool size. // * @throws IllegalArgumentException If the max pool size is less than zero. // */ // public SimplePool(int maxPoolSize) { // if (maxPoolSize <= 0) { // throw new IllegalArgumentException("The max pool size must be > 0"); // } // mPool = new Object[maxPoolSize]; // } // // @Override // @SuppressWarnings("unchecked") // public T acquire() { // if (mPoolSize > 0) { // final int lastPooledIndex = mPoolSize - 1; // T instance = (T) mPool[lastPooledIndex]; // mPool[lastPooledIndex] = null; // mPoolSize--; // return instance; // } // return null; // } // // @Override // public boolean release(T instance) { // if (isInPool(instance)) { // throw new IllegalStateException("Already in the pool!"); // } // if (mPoolSize < mPool.length) { // mPool[mPoolSize] = instance; // mPoolSize++; // return true; // } // return false; // } // // private boolean isInPool(T instance) { // for (int i = 0; i < mPoolSize; i++) { // if (mPool[i] == instance) { // return true; // } // } // return false; // } // } // // /** // * Synchronized pool of objects. // * // * @param <T> The pooled type. // */ // public static class SynchronizedPool<T> extends SimplePool<T> { // private final Object mLock; // // /** // * Creates a new instance. // * // * @param maxPoolSize The max pool size. // * @param lock an optional custom object to synchronize on // * @throws IllegalArgumentException If the max pool size is less than zero. // */ // public SynchronizedPool(int maxPoolSize, Object lock) { // super(maxPoolSize); // mLock = lock; // } // // /** // * @see #SynchronizedPool(int, Object) // */ // public SynchronizedPool(int maxPoolSize) { // this(maxPoolSize, new Object()); // } // // @Override // public T acquire() { // synchronized (mLock) { // return super.acquire(); // } // } // // @Override // public boolean release(T element) { // synchronized (mLock) { // return super.release(element); // } // } // } // } // Path: systemlib/src/main/java/android/view/GLES20RecordingCanvas.java import android.util.Pools; package android.view; class GLES20RecordingCanvas { // The recording canvas pool should be large enough to handle a deeply nested // view hierarchy because display lists are generated recursively. private static final int POOL_LIMIT = 25; //android 5.0,5.1
private static final Pools.SynchronizedPool<GLES20RecordingCanvas> sPool =
android-notes/SwissArmyKnife
saklib/src/main/java/com/wanjian/sak/system/rendernode/RenderNodeV29Impl.java
// Path: systemlib/src/main/java/android/graphics/RecordingCanvas.java // public class RecordingCanvas extends Canvas { // private static final int POOL_LIMIT = 25; // private static final Pools.SynchronizedPool<RecordingCanvas> sPool = // new Pools.SynchronizedPool<>(POOL_LIMIT); // // // public void enableZ() { // } // // public void disableZ() { // } // // public void drawRenderNode(RenderNode renderNode) { // } // } // // Path: systemlib/src/main/java/android/graphics/RenderNode.java // public class RenderNode { // public RenderNode(String name) { // // } // // public boolean setLeftTopRightBottom(int left, int top, int right, int bottom) { // return false; // } // // public boolean setAlpha(float alpha) { // return false; // } // // public boolean setHasOverlappingRendering(boolean hasOverlappingRendering) { // return false; // } // // public boolean setClipToBounds(boolean clipToBounds) { // return false; // } // // // public RecordingCanvas beginRecording(int width, int height) { // return null; // } // // public RecordingCanvas beginRecording() { // return null; // } // // // public void endRecording() { // } // // public boolean hasDisplayList() { // throw new IllegalStateException(); // } // }
import android.graphics.Canvas; import android.graphics.RecordingCanvas; import android.graphics.RenderNode; import java.lang.reflect.Method;
package com.wanjian.sak.system.rendernode; public class RenderNodeV29Impl extends RenderNodeCompact { private RenderNode renderNode; public RenderNodeV29Impl(String name) { renderNode = new RenderNode(name); } @Override public void drawRenderNode(Canvas canvas) {
// Path: systemlib/src/main/java/android/graphics/RecordingCanvas.java // public class RecordingCanvas extends Canvas { // private static final int POOL_LIMIT = 25; // private static final Pools.SynchronizedPool<RecordingCanvas> sPool = // new Pools.SynchronizedPool<>(POOL_LIMIT); // // // public void enableZ() { // } // // public void disableZ() { // } // // public void drawRenderNode(RenderNode renderNode) { // } // } // // Path: systemlib/src/main/java/android/graphics/RenderNode.java // public class RenderNode { // public RenderNode(String name) { // // } // // public boolean setLeftTopRightBottom(int left, int top, int right, int bottom) { // return false; // } // // public boolean setAlpha(float alpha) { // return false; // } // // public boolean setHasOverlappingRendering(boolean hasOverlappingRendering) { // return false; // } // // public boolean setClipToBounds(boolean clipToBounds) { // return false; // } // // // public RecordingCanvas beginRecording(int width, int height) { // return null; // } // // public RecordingCanvas beginRecording() { // return null; // } // // // public void endRecording() { // } // // public boolean hasDisplayList() { // throw new IllegalStateException(); // } // } // Path: saklib/src/main/java/com/wanjian/sak/system/rendernode/RenderNodeV29Impl.java import android.graphics.Canvas; import android.graphics.RecordingCanvas; import android.graphics.RenderNode; import java.lang.reflect.Method; package com.wanjian.sak.system.rendernode; public class RenderNodeV29Impl extends RenderNodeCompact { private RenderNode renderNode; public RenderNodeV29Impl(String name) { renderNode = new RenderNode(name); } @Override public void drawRenderNode(Canvas canvas) {
((RecordingCanvas) canvas).drawRenderNode(renderNode);
android-notes/SwissArmyKnife
saklib/src/main/java/com/wanjian/sak/layer/impl/FragmentNameLayer.java
// Path: saklib/src/main/java/com/wanjian/sak/layer/IClip.java // public interface IClip { // void onClipChange(boolean clip); // } // // Path: saklib/src/main/java/com/wanjian/sak/layer/IRange.java // public interface IRange { // void onStartRangeChange(int start); // void onEndRangeChange(int start); // } // // Path: saklib/src/main/java/com/wanjian/sak/utils/Utils.java // public class Utils { // public static ViewRootImpl[] diff(ViewRootImpl[] views1, ViewRootImpl[] views2) { // List<ViewRootImpl> list1 = views1 == null ? new ArrayList<ViewRootImpl>() : Arrays.asList(views1); // List<ViewRootImpl> list2 = views2 == null ? new ArrayList<ViewRootImpl>() : Arrays.asList(views2); // List<ViewRootImpl> result = new ArrayList<>(32); // // for (ViewRootImpl view : list1) { // if (list2.contains(view) == false) { // result.add(view); // } // } // ViewRootImpl[] array = new ViewRootImpl[result.size()]; // result.toArray(array); // return array; // } // // public static Activity findAct(View view) { // List<WeakReference<Activity>> references = RunningActivityFetcher.fetch(); // if (references == null) { // return null; // } // for (WeakReference<Activity> act : references) { // Activity activity = act.get(); // if (activity == null) { // continue; // } // if (view == activity.getWindow().getDecorView().getRootView()) { // return activity; // } // } // return null; // } // // }
import android.app.Activity; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Region; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.view.View; import android.view.ViewGroup; import com.wanjian.sak.layer.IClip; import com.wanjian.sak.layer.IRange; import com.wanjian.sak.utils.Utils; import java.util.List;
package com.wanjian.sak.layer.impl; public class FragmentNameLayer extends ActivityNameLayerView implements IRange, IClip { private int mStartLayer; private int mEndLayer = 100;// TODO: 2020/7/7 private FragmentActivity mActivity; private Paint mBagPaint = new Paint(); private boolean isClip = true; @Override protected void onAttach(View rootView) { super.onAttach(rootView); mBagPaint.setColor(Color.argb(63, 255, 0, 255));
// Path: saklib/src/main/java/com/wanjian/sak/layer/IClip.java // public interface IClip { // void onClipChange(boolean clip); // } // // Path: saklib/src/main/java/com/wanjian/sak/layer/IRange.java // public interface IRange { // void onStartRangeChange(int start); // void onEndRangeChange(int start); // } // // Path: saklib/src/main/java/com/wanjian/sak/utils/Utils.java // public class Utils { // public static ViewRootImpl[] diff(ViewRootImpl[] views1, ViewRootImpl[] views2) { // List<ViewRootImpl> list1 = views1 == null ? new ArrayList<ViewRootImpl>() : Arrays.asList(views1); // List<ViewRootImpl> list2 = views2 == null ? new ArrayList<ViewRootImpl>() : Arrays.asList(views2); // List<ViewRootImpl> result = new ArrayList<>(32); // // for (ViewRootImpl view : list1) { // if (list2.contains(view) == false) { // result.add(view); // } // } // ViewRootImpl[] array = new ViewRootImpl[result.size()]; // result.toArray(array); // return array; // } // // public static Activity findAct(View view) { // List<WeakReference<Activity>> references = RunningActivityFetcher.fetch(); // if (references == null) { // return null; // } // for (WeakReference<Activity> act : references) { // Activity activity = act.get(); // if (activity == null) { // continue; // } // if (view == activity.getWindow().getDecorView().getRootView()) { // return activity; // } // } // return null; // } // // } // Path: saklib/src/main/java/com/wanjian/sak/layer/impl/FragmentNameLayer.java import android.app.Activity; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Region; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.view.View; import android.view.ViewGroup; import com.wanjian.sak.layer.IClip; import com.wanjian.sak.layer.IRange; import com.wanjian.sak.utils.Utils; import java.util.List; package com.wanjian.sak.layer.impl; public class FragmentNameLayer extends ActivityNameLayerView implements IRange, IClip { private int mStartLayer; private int mEndLayer = 100;// TODO: 2020/7/7 private FragmentActivity mActivity; private Paint mBagPaint = new Paint(); private boolean isClip = true; @Override protected void onAttach(View rootView) { super.onAttach(rootView); mBagPaint.setColor(Color.argb(63, 255, 0, 255));
Activity activity = Utils.findAct(rootView);
android-notes/SwissArmyKnife
saklib/src/main/java/com/wanjian/sak/system/canvas/compact/HardwareCanvasV24Impl.java
// Path: systemlib/src/main/java/android/view/ThreadedRenderer.java // public abstract class ThreadedRenderer extends HardwareRenderer { // private int mInsetTop, mInsetLeft; // public void notifyFramePending() {} // } // // Path: systemlib/src/main/java/android/view/ViewRootImpl.java // public final class ViewRootImpl implements ViewParent { // // public View getView() { // return null; // } // // // @Override // public void requestLayout() { // // } // // @Override // public boolean isLayoutRequested() { // return false; // } // // @Override // public void requestTransparentRegion(View child) { // // } // // @Override // public void invalidateChild(View child, Rect r) { // // } // // @Override // public ViewParent invalidateChildInParent(int[] location, Rect r) { // return null; // } // // @Override // public ViewParent getParent() { // return null; // } // // @Override // public void requestChildFocus(View child, View focused) { // // } // // @Override // public void recomputeViewAttributes(View child) { // // } // // @Override // public void clearChildFocus(View child) { // // } // // @Override // public boolean getChildVisibleRect(View child, Rect r, Point offset) { // return false; // } // // @Override // public View focusSearch(View v, int direction) { // return null; // } // // @Override // public View keyboardNavigationClusterSearch(View currentCluster, int direction) { // return null; // } // // @Override // public void bringChildToFront(View child) { // // } // // @Override // public void focusableViewAvailable(View v) { // // } // // @Override // public boolean showContextMenuForChild(View originalView) { // return false; // } // // @Override // public boolean showContextMenuForChild(View originalView, float x, float y) { // return false; // } // // @Override // public void createContextMenu(ContextMenu menu) { // // } // // @Override // public ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback) { // return null; // } // // @Override // public ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback, int type) { // return null; // } // // @Override // public void childDrawableStateChanged(View child) { // // } // // @Override // public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) { // // } // // @Override // public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) { // return false; // } // // @Override // public boolean requestSendAccessibilityEvent(View child, AccessibilityEvent event) { // return false; // } // // @Override // public void childHasTransientStateChanged(View child, boolean hasTransientState) { // // } // // @Override // public void requestFitSystemWindows() { // // } // // @Override // public ViewParent getParentForAccessibility() { // return null; // } // // @Override // public void notifySubtreeAccessibilityStateChanged(View child, View source, int changeType) { // // } // // @Override // public boolean canResolveLayoutDirection() { // return false; // } // // @Override // public boolean isLayoutDirectionResolved() { // return false; // } // // @Override // public int getLayoutDirection() { // return 0; // } // // @Override // public boolean canResolveTextDirection() { // return false; // } // // @Override // public boolean isTextDirectionResolved() { // return false; // } // // @Override // public int getTextDirection() { // return 0; // } // // @Override // public boolean canResolveTextAlignment() { // return false; // } // // @Override // public boolean isTextAlignmentResolved() { // return false; // } // // @Override // public int getTextAlignment() { // return 0; // } // // @Override // public boolean onStartNestedScroll(View child, View target, int nestedScrollAxes) { // return false; // } // // @Override // public void onNestedScrollAccepted(View child, View target, int nestedScrollAxes) { // // } // // @Override // public void onStopNestedScroll(View target) { // // } // // @Override // public void onNestedScroll(View target, int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed) { // // } // // @Override // public void onNestedPreScroll(View target, int dx, int dy, int[] consumed) { // // } // // @Override // public boolean onNestedFling(View target, float velocityX, float velocityY, boolean consumed) { // return false; // } // // @Override // public boolean onNestedPreFling(View target, float velocityX, float velocityY) { // return false; // } // // @Override // public boolean onNestedPrePerformAccessibilityAction(View target, int action, Bundle arguments) { // return false; // } // }
import android.view.ThreadedRenderer; import android.view.View; import android.view.ViewRootImpl; import java.lang.reflect.Method;
package com.wanjian.sak.system.canvas.compact; public class HardwareCanvasV24Impl extends HardwareCanvasV23Impl { HardwareCanvasV24Impl(ViewRootImpl viewRootImpl) { super(viewRootImpl); }
// Path: systemlib/src/main/java/android/view/ThreadedRenderer.java // public abstract class ThreadedRenderer extends HardwareRenderer { // private int mInsetTop, mInsetLeft; // public void notifyFramePending() {} // } // // Path: systemlib/src/main/java/android/view/ViewRootImpl.java // public final class ViewRootImpl implements ViewParent { // // public View getView() { // return null; // } // // // @Override // public void requestLayout() { // // } // // @Override // public boolean isLayoutRequested() { // return false; // } // // @Override // public void requestTransparentRegion(View child) { // // } // // @Override // public void invalidateChild(View child, Rect r) { // // } // // @Override // public ViewParent invalidateChildInParent(int[] location, Rect r) { // return null; // } // // @Override // public ViewParent getParent() { // return null; // } // // @Override // public void requestChildFocus(View child, View focused) { // // } // // @Override // public void recomputeViewAttributes(View child) { // // } // // @Override // public void clearChildFocus(View child) { // // } // // @Override // public boolean getChildVisibleRect(View child, Rect r, Point offset) { // return false; // } // // @Override // public View focusSearch(View v, int direction) { // return null; // } // // @Override // public View keyboardNavigationClusterSearch(View currentCluster, int direction) { // return null; // } // // @Override // public void bringChildToFront(View child) { // // } // // @Override // public void focusableViewAvailable(View v) { // // } // // @Override // public boolean showContextMenuForChild(View originalView) { // return false; // } // // @Override // public boolean showContextMenuForChild(View originalView, float x, float y) { // return false; // } // // @Override // public void createContextMenu(ContextMenu menu) { // // } // // @Override // public ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback) { // return null; // } // // @Override // public ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback, int type) { // return null; // } // // @Override // public void childDrawableStateChanged(View child) { // // } // // @Override // public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) { // // } // // @Override // public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) { // return false; // } // // @Override // public boolean requestSendAccessibilityEvent(View child, AccessibilityEvent event) { // return false; // } // // @Override // public void childHasTransientStateChanged(View child, boolean hasTransientState) { // // } // // @Override // public void requestFitSystemWindows() { // // } // // @Override // public ViewParent getParentForAccessibility() { // return null; // } // // @Override // public void notifySubtreeAccessibilityStateChanged(View child, View source, int changeType) { // // } // // @Override // public boolean canResolveLayoutDirection() { // return false; // } // // @Override // public boolean isLayoutDirectionResolved() { // return false; // } // // @Override // public int getLayoutDirection() { // return 0; // } // // @Override // public boolean canResolveTextDirection() { // return false; // } // // @Override // public boolean isTextDirectionResolved() { // return false; // } // // @Override // public int getTextDirection() { // return 0; // } // // @Override // public boolean canResolveTextAlignment() { // return false; // } // // @Override // public boolean isTextAlignmentResolved() { // return false; // } // // @Override // public int getTextAlignment() { // return 0; // } // // @Override // public boolean onStartNestedScroll(View child, View target, int nestedScrollAxes) { // return false; // } // // @Override // public void onNestedScrollAccepted(View child, View target, int nestedScrollAxes) { // // } // // @Override // public void onStopNestedScroll(View target) { // // } // // @Override // public void onNestedScroll(View target, int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed) { // // } // // @Override // public void onNestedPreScroll(View target, int dx, int dy, int[] consumed) { // // } // // @Override // public boolean onNestedFling(View target, float velocityX, float velocityY, boolean consumed) { // return false; // } // // @Override // public boolean onNestedPreFling(View target, float velocityX, float velocityY) { // return false; // } // // @Override // public boolean onNestedPrePerformAccessibilityAction(View target, int action, Bundle arguments) { // return false; // } // } // Path: saklib/src/main/java/com/wanjian/sak/system/canvas/compact/HardwareCanvasV24Impl.java import android.view.ThreadedRenderer; import android.view.View; import android.view.ViewRootImpl; import java.lang.reflect.Method; package com.wanjian.sak.system.canvas.compact; public class HardwareCanvasV24Impl extends HardwareCanvasV23Impl { HardwareCanvasV24Impl(ViewRootImpl viewRootImpl) { super(viewRootImpl); }
protected boolean isThreadRendererEnable(ThreadedRenderer threadRenderer) {
android-notes/SwissArmyKnife
sak-nop/src/main/java/com/wanjian/sak/layer/AbsLayer.java
// Path: saklib/src/main/java/com/wanjian/sak/config/Config.java // public class Config { // // private int minRange; // private int maxRange; // // private List<AbsLayer> mLayerViews = new ArrayList<>(); // private List<ISizeConverter> mSizeConverterList = new ArrayList<>(); // private int startRange; // private int endRange; // private boolean clipDraw; // List<Item>mLayerList; // private Config(Build build) { // // mLayerViews.addAll(build.mDefaultLayerViews); // // mLayerViews.addAll(build.mCustomerLayerViews); // // ViewFilter.FILTER = build.mViewFilter; // mSizeConverterList.addAll(build.mSizeConverterList); // // minRange = build.min; // maxRange = build.max; // clipDraw = build.clipDraw; // mLayerList = build.mLayerList; // } // // public List<Item> getLayerList() { // return mLayerList; // } // // // public List<AbsLayer> getLayerViews() { // // return mLayerViews; // // } // // public List<ISizeConverter> getSizeConverters() { // if (mSizeConverterList == null || mSizeConverterList.isEmpty()) { // return Arrays.<ISizeConverter>asList(new OriginSizeConverter()); // } // return mSizeConverterList; // } // // public int getStartRange() { // return startRange; // } // // public void setStartRange(int startRange) { // this.startRange = startRange; // } // // public int getEndRange() { // return endRange; // } // // public void setEndRange(int endRange) { // this.endRange = endRange; // } // // public boolean isClipDraw() { // return clipDraw; // } // // public void setClipDraw(boolean clipDraw) { // this.clipDraw = clipDraw; // } // // public int getMinRange() { // return minRange; // } // // public int getMaxRange() { // return maxRange; // } // // public static class Build { // Context mContext; // List<ISizeConverter> mSizeConverterList = new ArrayList<>(); // ViewFilter mViewFilter; // List<Item>mLayerList=new ArrayList<>(); // int min = 0; // int max = 50; // boolean clipDraw = true; // // public Build(Context context) { // Check.isNull(context, "context"); // mContext = context.getApplicationContext(); // // // mSizeConverterList.add(new Px2DpSizeConverter()); // mSizeConverterList.add(new OriginSizeConverter()); // mSizeConverterList.add(new Px2SpSizeConverter()); // mViewFilter = ViewFilter.FILTER; // } // // public Build addSizeConverter(ISizeConverter sizeConverter) { // Check.isNull(sizeConverter, "sizeConverter"); // mSizeConverterList.add(sizeConverter); // return this; // } // // // public Build addLayerView(AbsLayer layerView) { // // Check.isNull(layerView, "layerView"); // //// mDefaultLayerViews.clear(); // //// mCustomerLayerViews.add(layerView); // // return this; // // } // // public Build viewFilter(ViewFilter viewFilter) { // Check.isNull(viewFilter, "viewFilter"); // mViewFilter = viewFilter; // return this; // } // // public Build range(int min, int max) { // if (min < 0) { // throw new IllegalArgumentException(); // } // if (max < min) { // throw new IllegalArgumentException(); // } // this.min = min; // this.max = max; // return this; // } // // public Build clipDraw(boolean clip) { // clipDraw = clip; // return this; // } // // public Build addLayer(Class<? extends Layer> clz, Drawable icon, String iconName) { // mLayerList.add(new Item(clz,icon,iconName)); // return this; // } // public Config build() { // return new Config(this); // } // } // } // // Path: sak-nop/src/main/java/com/wanjian/sak/converter/ISizeConverter.java // public abstract class ISizeConverter { // public static ISizeConverter CONVERTER; // // public abstract String desc(); // // public abstract Size convert(Context context, float length); // // public abstract int recovery(Context context, float length); // // } // // Path: saklib/src/main/java/com/wanjian/sak/filter/ViewFilter.java // public abstract class ViewFilter { // public static ViewFilter FILTER = new ViewFilter() { // @Override // protected boolean apply(View view) { // return view.getVisibility() == View.VISIBLE; // } // }; // // // public final boolean filter(View view) { // return apply(view); // } // // protected abstract boolean apply(View view); // // @Override // public int hashCode() { // return getClass().hashCode(); // } // // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // return obj.getClass() == getClass(); // } // }
import android.content.Context; import android.graphics.Canvas; import android.graphics.drawable.Drawable; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.FrameLayout; import com.wanjian.sak.config.Config; import com.wanjian.sak.converter.ISizeConverter; import com.wanjian.sak.filter.ViewFilter;
package com.wanjian.sak.layer; /** * Created by wanjian on 2017/3/9. */ public abstract class AbsLayer extends FrameLayout { public AbsLayer(Context context) { super(context); }
// Path: saklib/src/main/java/com/wanjian/sak/config/Config.java // public class Config { // // private int minRange; // private int maxRange; // // private List<AbsLayer> mLayerViews = new ArrayList<>(); // private List<ISizeConverter> mSizeConverterList = new ArrayList<>(); // private int startRange; // private int endRange; // private boolean clipDraw; // List<Item>mLayerList; // private Config(Build build) { // // mLayerViews.addAll(build.mDefaultLayerViews); // // mLayerViews.addAll(build.mCustomerLayerViews); // // ViewFilter.FILTER = build.mViewFilter; // mSizeConverterList.addAll(build.mSizeConverterList); // // minRange = build.min; // maxRange = build.max; // clipDraw = build.clipDraw; // mLayerList = build.mLayerList; // } // // public List<Item> getLayerList() { // return mLayerList; // } // // // public List<AbsLayer> getLayerViews() { // // return mLayerViews; // // } // // public List<ISizeConverter> getSizeConverters() { // if (mSizeConverterList == null || mSizeConverterList.isEmpty()) { // return Arrays.<ISizeConverter>asList(new OriginSizeConverter()); // } // return mSizeConverterList; // } // // public int getStartRange() { // return startRange; // } // // public void setStartRange(int startRange) { // this.startRange = startRange; // } // // public int getEndRange() { // return endRange; // } // // public void setEndRange(int endRange) { // this.endRange = endRange; // } // // public boolean isClipDraw() { // return clipDraw; // } // // public void setClipDraw(boolean clipDraw) { // this.clipDraw = clipDraw; // } // // public int getMinRange() { // return minRange; // } // // public int getMaxRange() { // return maxRange; // } // // public static class Build { // Context mContext; // List<ISizeConverter> mSizeConverterList = new ArrayList<>(); // ViewFilter mViewFilter; // List<Item>mLayerList=new ArrayList<>(); // int min = 0; // int max = 50; // boolean clipDraw = true; // // public Build(Context context) { // Check.isNull(context, "context"); // mContext = context.getApplicationContext(); // // // mSizeConverterList.add(new Px2DpSizeConverter()); // mSizeConverterList.add(new OriginSizeConverter()); // mSizeConverterList.add(new Px2SpSizeConverter()); // mViewFilter = ViewFilter.FILTER; // } // // public Build addSizeConverter(ISizeConverter sizeConverter) { // Check.isNull(sizeConverter, "sizeConverter"); // mSizeConverterList.add(sizeConverter); // return this; // } // // // public Build addLayerView(AbsLayer layerView) { // // Check.isNull(layerView, "layerView"); // //// mDefaultLayerViews.clear(); // //// mCustomerLayerViews.add(layerView); // // return this; // // } // // public Build viewFilter(ViewFilter viewFilter) { // Check.isNull(viewFilter, "viewFilter"); // mViewFilter = viewFilter; // return this; // } // // public Build range(int min, int max) { // if (min < 0) { // throw new IllegalArgumentException(); // } // if (max < min) { // throw new IllegalArgumentException(); // } // this.min = min; // this.max = max; // return this; // } // // public Build clipDraw(boolean clip) { // clipDraw = clip; // return this; // } // // public Build addLayer(Class<? extends Layer> clz, Drawable icon, String iconName) { // mLayerList.add(new Item(clz,icon,iconName)); // return this; // } // public Config build() { // return new Config(this); // } // } // } // // Path: sak-nop/src/main/java/com/wanjian/sak/converter/ISizeConverter.java // public abstract class ISizeConverter { // public static ISizeConverter CONVERTER; // // public abstract String desc(); // // public abstract Size convert(Context context, float length); // // public abstract int recovery(Context context, float length); // // } // // Path: saklib/src/main/java/com/wanjian/sak/filter/ViewFilter.java // public abstract class ViewFilter { // public static ViewFilter FILTER = new ViewFilter() { // @Override // protected boolean apply(View view) { // return view.getVisibility() == View.VISIBLE; // } // }; // // // public final boolean filter(View view) { // return apply(view); // } // // protected abstract boolean apply(View view); // // @Override // public int hashCode() { // return getClass().hashCode(); // } // // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // return obj.getClass() == getClass(); // } // } // Path: sak-nop/src/main/java/com/wanjian/sak/layer/AbsLayer.java import android.content.Context; import android.graphics.Canvas; import android.graphics.drawable.Drawable; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.FrameLayout; import com.wanjian.sak.config.Config; import com.wanjian.sak.converter.ISizeConverter; import com.wanjian.sak.filter.ViewFilter; package com.wanjian.sak.layer; /** * Created by wanjian on 2017/3/9. */ public abstract class AbsLayer extends FrameLayout { public AbsLayer(Context context) { super(context); }
public void attachConfig(Config config) {
android-notes/SwissArmyKnife
sak-nop/src/main/java/com/wanjian/sak/layer/AbsLayer.java
// Path: saklib/src/main/java/com/wanjian/sak/config/Config.java // public class Config { // // private int minRange; // private int maxRange; // // private List<AbsLayer> mLayerViews = new ArrayList<>(); // private List<ISizeConverter> mSizeConverterList = new ArrayList<>(); // private int startRange; // private int endRange; // private boolean clipDraw; // List<Item>mLayerList; // private Config(Build build) { // // mLayerViews.addAll(build.mDefaultLayerViews); // // mLayerViews.addAll(build.mCustomerLayerViews); // // ViewFilter.FILTER = build.mViewFilter; // mSizeConverterList.addAll(build.mSizeConverterList); // // minRange = build.min; // maxRange = build.max; // clipDraw = build.clipDraw; // mLayerList = build.mLayerList; // } // // public List<Item> getLayerList() { // return mLayerList; // } // // // public List<AbsLayer> getLayerViews() { // // return mLayerViews; // // } // // public List<ISizeConverter> getSizeConverters() { // if (mSizeConverterList == null || mSizeConverterList.isEmpty()) { // return Arrays.<ISizeConverter>asList(new OriginSizeConverter()); // } // return mSizeConverterList; // } // // public int getStartRange() { // return startRange; // } // // public void setStartRange(int startRange) { // this.startRange = startRange; // } // // public int getEndRange() { // return endRange; // } // // public void setEndRange(int endRange) { // this.endRange = endRange; // } // // public boolean isClipDraw() { // return clipDraw; // } // // public void setClipDraw(boolean clipDraw) { // this.clipDraw = clipDraw; // } // // public int getMinRange() { // return minRange; // } // // public int getMaxRange() { // return maxRange; // } // // public static class Build { // Context mContext; // List<ISizeConverter> mSizeConverterList = new ArrayList<>(); // ViewFilter mViewFilter; // List<Item>mLayerList=new ArrayList<>(); // int min = 0; // int max = 50; // boolean clipDraw = true; // // public Build(Context context) { // Check.isNull(context, "context"); // mContext = context.getApplicationContext(); // // // mSizeConverterList.add(new Px2DpSizeConverter()); // mSizeConverterList.add(new OriginSizeConverter()); // mSizeConverterList.add(new Px2SpSizeConverter()); // mViewFilter = ViewFilter.FILTER; // } // // public Build addSizeConverter(ISizeConverter sizeConverter) { // Check.isNull(sizeConverter, "sizeConverter"); // mSizeConverterList.add(sizeConverter); // return this; // } // // // public Build addLayerView(AbsLayer layerView) { // // Check.isNull(layerView, "layerView"); // //// mDefaultLayerViews.clear(); // //// mCustomerLayerViews.add(layerView); // // return this; // // } // // public Build viewFilter(ViewFilter viewFilter) { // Check.isNull(viewFilter, "viewFilter"); // mViewFilter = viewFilter; // return this; // } // // public Build range(int min, int max) { // if (min < 0) { // throw new IllegalArgumentException(); // } // if (max < min) { // throw new IllegalArgumentException(); // } // this.min = min; // this.max = max; // return this; // } // // public Build clipDraw(boolean clip) { // clipDraw = clip; // return this; // } // // public Build addLayer(Class<? extends Layer> clz, Drawable icon, String iconName) { // mLayerList.add(new Item(clz,icon,iconName)); // return this; // } // public Config build() { // return new Config(this); // } // } // } // // Path: sak-nop/src/main/java/com/wanjian/sak/converter/ISizeConverter.java // public abstract class ISizeConverter { // public static ISizeConverter CONVERTER; // // public abstract String desc(); // // public abstract Size convert(Context context, float length); // // public abstract int recovery(Context context, float length); // // } // // Path: saklib/src/main/java/com/wanjian/sak/filter/ViewFilter.java // public abstract class ViewFilter { // public static ViewFilter FILTER = new ViewFilter() { // @Override // protected boolean apply(View view) { // return view.getVisibility() == View.VISIBLE; // } // }; // // // public final boolean filter(View view) { // return apply(view); // } // // protected abstract boolean apply(View view); // // @Override // public int hashCode() { // return getClass().hashCode(); // } // // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // return obj.getClass() == getClass(); // } // }
import android.content.Context; import android.graphics.Canvas; import android.graphics.drawable.Drawable; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.FrameLayout; import com.wanjian.sak.config.Config; import com.wanjian.sak.converter.ISizeConverter; import com.wanjian.sak.filter.ViewFilter;
return 0; } public final void uiUpdate(Canvas canvas, View view) { } protected void onUiUpdate(Canvas canvas, View rootView) { } protected void onAttached(View rootView) { } protected void onDetached(View rootView) { } protected int[] getLocationAndSize(View view) { return null; } protected int dp2px(int dip) { return 0; } protected int px2dp(float pxValue) { return 0; }
// Path: saklib/src/main/java/com/wanjian/sak/config/Config.java // public class Config { // // private int minRange; // private int maxRange; // // private List<AbsLayer> mLayerViews = new ArrayList<>(); // private List<ISizeConverter> mSizeConverterList = new ArrayList<>(); // private int startRange; // private int endRange; // private boolean clipDraw; // List<Item>mLayerList; // private Config(Build build) { // // mLayerViews.addAll(build.mDefaultLayerViews); // // mLayerViews.addAll(build.mCustomerLayerViews); // // ViewFilter.FILTER = build.mViewFilter; // mSizeConverterList.addAll(build.mSizeConverterList); // // minRange = build.min; // maxRange = build.max; // clipDraw = build.clipDraw; // mLayerList = build.mLayerList; // } // // public List<Item> getLayerList() { // return mLayerList; // } // // // public List<AbsLayer> getLayerViews() { // // return mLayerViews; // // } // // public List<ISizeConverter> getSizeConverters() { // if (mSizeConverterList == null || mSizeConverterList.isEmpty()) { // return Arrays.<ISizeConverter>asList(new OriginSizeConverter()); // } // return mSizeConverterList; // } // // public int getStartRange() { // return startRange; // } // // public void setStartRange(int startRange) { // this.startRange = startRange; // } // // public int getEndRange() { // return endRange; // } // // public void setEndRange(int endRange) { // this.endRange = endRange; // } // // public boolean isClipDraw() { // return clipDraw; // } // // public void setClipDraw(boolean clipDraw) { // this.clipDraw = clipDraw; // } // // public int getMinRange() { // return minRange; // } // // public int getMaxRange() { // return maxRange; // } // // public static class Build { // Context mContext; // List<ISizeConverter> mSizeConverterList = new ArrayList<>(); // ViewFilter mViewFilter; // List<Item>mLayerList=new ArrayList<>(); // int min = 0; // int max = 50; // boolean clipDraw = true; // // public Build(Context context) { // Check.isNull(context, "context"); // mContext = context.getApplicationContext(); // // // mSizeConverterList.add(new Px2DpSizeConverter()); // mSizeConverterList.add(new OriginSizeConverter()); // mSizeConverterList.add(new Px2SpSizeConverter()); // mViewFilter = ViewFilter.FILTER; // } // // public Build addSizeConverter(ISizeConverter sizeConverter) { // Check.isNull(sizeConverter, "sizeConverter"); // mSizeConverterList.add(sizeConverter); // return this; // } // // // public Build addLayerView(AbsLayer layerView) { // // Check.isNull(layerView, "layerView"); // //// mDefaultLayerViews.clear(); // //// mCustomerLayerViews.add(layerView); // // return this; // // } // // public Build viewFilter(ViewFilter viewFilter) { // Check.isNull(viewFilter, "viewFilter"); // mViewFilter = viewFilter; // return this; // } // // public Build range(int min, int max) { // if (min < 0) { // throw new IllegalArgumentException(); // } // if (max < min) { // throw new IllegalArgumentException(); // } // this.min = min; // this.max = max; // return this; // } // // public Build clipDraw(boolean clip) { // clipDraw = clip; // return this; // } // // public Build addLayer(Class<? extends Layer> clz, Drawable icon, String iconName) { // mLayerList.add(new Item(clz,icon,iconName)); // return this; // } // public Config build() { // return new Config(this); // } // } // } // // Path: sak-nop/src/main/java/com/wanjian/sak/converter/ISizeConverter.java // public abstract class ISizeConverter { // public static ISizeConverter CONVERTER; // // public abstract String desc(); // // public abstract Size convert(Context context, float length); // // public abstract int recovery(Context context, float length); // // } // // Path: saklib/src/main/java/com/wanjian/sak/filter/ViewFilter.java // public abstract class ViewFilter { // public static ViewFilter FILTER = new ViewFilter() { // @Override // protected boolean apply(View view) { // return view.getVisibility() == View.VISIBLE; // } // }; // // // public final boolean filter(View view) { // return apply(view); // } // // protected abstract boolean apply(View view); // // @Override // public int hashCode() { // return getClass().hashCode(); // } // // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // return obj.getClass() == getClass(); // } // } // Path: sak-nop/src/main/java/com/wanjian/sak/layer/AbsLayer.java import android.content.Context; import android.graphics.Canvas; import android.graphics.drawable.Drawable; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.FrameLayout; import com.wanjian.sak.config.Config; import com.wanjian.sak.converter.ISizeConverter; import com.wanjian.sak.filter.ViewFilter; return 0; } public final void uiUpdate(Canvas canvas, View view) { } protected void onUiUpdate(Canvas canvas, View rootView) { } protected void onAttached(View rootView) { } protected void onDetached(View rootView) { } protected int[] getLocationAndSize(View view) { return null; } protected int dp2px(int dip) { return 0; } protected int px2dp(float pxValue) { return 0; }
protected ISizeConverter getSizeConverter() {
android-notes/SwissArmyKnife
sak-nop/src/main/java/com/wanjian/sak/layer/AbsLayer.java
// Path: saklib/src/main/java/com/wanjian/sak/config/Config.java // public class Config { // // private int minRange; // private int maxRange; // // private List<AbsLayer> mLayerViews = new ArrayList<>(); // private List<ISizeConverter> mSizeConverterList = new ArrayList<>(); // private int startRange; // private int endRange; // private boolean clipDraw; // List<Item>mLayerList; // private Config(Build build) { // // mLayerViews.addAll(build.mDefaultLayerViews); // // mLayerViews.addAll(build.mCustomerLayerViews); // // ViewFilter.FILTER = build.mViewFilter; // mSizeConverterList.addAll(build.mSizeConverterList); // // minRange = build.min; // maxRange = build.max; // clipDraw = build.clipDraw; // mLayerList = build.mLayerList; // } // // public List<Item> getLayerList() { // return mLayerList; // } // // // public List<AbsLayer> getLayerViews() { // // return mLayerViews; // // } // // public List<ISizeConverter> getSizeConverters() { // if (mSizeConverterList == null || mSizeConverterList.isEmpty()) { // return Arrays.<ISizeConverter>asList(new OriginSizeConverter()); // } // return mSizeConverterList; // } // // public int getStartRange() { // return startRange; // } // // public void setStartRange(int startRange) { // this.startRange = startRange; // } // // public int getEndRange() { // return endRange; // } // // public void setEndRange(int endRange) { // this.endRange = endRange; // } // // public boolean isClipDraw() { // return clipDraw; // } // // public void setClipDraw(boolean clipDraw) { // this.clipDraw = clipDraw; // } // // public int getMinRange() { // return minRange; // } // // public int getMaxRange() { // return maxRange; // } // // public static class Build { // Context mContext; // List<ISizeConverter> mSizeConverterList = new ArrayList<>(); // ViewFilter mViewFilter; // List<Item>mLayerList=new ArrayList<>(); // int min = 0; // int max = 50; // boolean clipDraw = true; // // public Build(Context context) { // Check.isNull(context, "context"); // mContext = context.getApplicationContext(); // // // mSizeConverterList.add(new Px2DpSizeConverter()); // mSizeConverterList.add(new OriginSizeConverter()); // mSizeConverterList.add(new Px2SpSizeConverter()); // mViewFilter = ViewFilter.FILTER; // } // // public Build addSizeConverter(ISizeConverter sizeConverter) { // Check.isNull(sizeConverter, "sizeConverter"); // mSizeConverterList.add(sizeConverter); // return this; // } // // // public Build addLayerView(AbsLayer layerView) { // // Check.isNull(layerView, "layerView"); // //// mDefaultLayerViews.clear(); // //// mCustomerLayerViews.add(layerView); // // return this; // // } // // public Build viewFilter(ViewFilter viewFilter) { // Check.isNull(viewFilter, "viewFilter"); // mViewFilter = viewFilter; // return this; // } // // public Build range(int min, int max) { // if (min < 0) { // throw new IllegalArgumentException(); // } // if (max < min) { // throw new IllegalArgumentException(); // } // this.min = min; // this.max = max; // return this; // } // // public Build clipDraw(boolean clip) { // clipDraw = clip; // return this; // } // // public Build addLayer(Class<? extends Layer> clz, Drawable icon, String iconName) { // mLayerList.add(new Item(clz,icon,iconName)); // return this; // } // public Config build() { // return new Config(this); // } // } // } // // Path: sak-nop/src/main/java/com/wanjian/sak/converter/ISizeConverter.java // public abstract class ISizeConverter { // public static ISizeConverter CONVERTER; // // public abstract String desc(); // // public abstract Size convert(Context context, float length); // // public abstract int recovery(Context context, float length); // // } // // Path: saklib/src/main/java/com/wanjian/sak/filter/ViewFilter.java // public abstract class ViewFilter { // public static ViewFilter FILTER = new ViewFilter() { // @Override // protected boolean apply(View view) { // return view.getVisibility() == View.VISIBLE; // } // }; // // // public final boolean filter(View view) { // return apply(view); // } // // protected abstract boolean apply(View view); // // @Override // public int hashCode() { // return getClass().hashCode(); // } // // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // return obj.getClass() == getClass(); // } // }
import android.content.Context; import android.graphics.Canvas; import android.graphics.drawable.Drawable; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.FrameLayout; import com.wanjian.sak.config.Config; import com.wanjian.sak.converter.ISizeConverter; import com.wanjian.sak.filter.ViewFilter;
} protected void onUiUpdate(Canvas canvas, View rootView) { } protected void onAttached(View rootView) { } protected void onDetached(View rootView) { } protected int[] getLocationAndSize(View view) { return null; } protected int dp2px(int dip) { return 0; } protected int px2dp(float pxValue) { return 0; } protected ISizeConverter getSizeConverter() { return null; }
// Path: saklib/src/main/java/com/wanjian/sak/config/Config.java // public class Config { // // private int minRange; // private int maxRange; // // private List<AbsLayer> mLayerViews = new ArrayList<>(); // private List<ISizeConverter> mSizeConverterList = new ArrayList<>(); // private int startRange; // private int endRange; // private boolean clipDraw; // List<Item>mLayerList; // private Config(Build build) { // // mLayerViews.addAll(build.mDefaultLayerViews); // // mLayerViews.addAll(build.mCustomerLayerViews); // // ViewFilter.FILTER = build.mViewFilter; // mSizeConverterList.addAll(build.mSizeConverterList); // // minRange = build.min; // maxRange = build.max; // clipDraw = build.clipDraw; // mLayerList = build.mLayerList; // } // // public List<Item> getLayerList() { // return mLayerList; // } // // // public List<AbsLayer> getLayerViews() { // // return mLayerViews; // // } // // public List<ISizeConverter> getSizeConverters() { // if (mSizeConverterList == null || mSizeConverterList.isEmpty()) { // return Arrays.<ISizeConverter>asList(new OriginSizeConverter()); // } // return mSizeConverterList; // } // // public int getStartRange() { // return startRange; // } // // public void setStartRange(int startRange) { // this.startRange = startRange; // } // // public int getEndRange() { // return endRange; // } // // public void setEndRange(int endRange) { // this.endRange = endRange; // } // // public boolean isClipDraw() { // return clipDraw; // } // // public void setClipDraw(boolean clipDraw) { // this.clipDraw = clipDraw; // } // // public int getMinRange() { // return minRange; // } // // public int getMaxRange() { // return maxRange; // } // // public static class Build { // Context mContext; // List<ISizeConverter> mSizeConverterList = new ArrayList<>(); // ViewFilter mViewFilter; // List<Item>mLayerList=new ArrayList<>(); // int min = 0; // int max = 50; // boolean clipDraw = true; // // public Build(Context context) { // Check.isNull(context, "context"); // mContext = context.getApplicationContext(); // // // mSizeConverterList.add(new Px2DpSizeConverter()); // mSizeConverterList.add(new OriginSizeConverter()); // mSizeConverterList.add(new Px2SpSizeConverter()); // mViewFilter = ViewFilter.FILTER; // } // // public Build addSizeConverter(ISizeConverter sizeConverter) { // Check.isNull(sizeConverter, "sizeConverter"); // mSizeConverterList.add(sizeConverter); // return this; // } // // // public Build addLayerView(AbsLayer layerView) { // // Check.isNull(layerView, "layerView"); // //// mDefaultLayerViews.clear(); // //// mCustomerLayerViews.add(layerView); // // return this; // // } // // public Build viewFilter(ViewFilter viewFilter) { // Check.isNull(viewFilter, "viewFilter"); // mViewFilter = viewFilter; // return this; // } // // public Build range(int min, int max) { // if (min < 0) { // throw new IllegalArgumentException(); // } // if (max < min) { // throw new IllegalArgumentException(); // } // this.min = min; // this.max = max; // return this; // } // // public Build clipDraw(boolean clip) { // clipDraw = clip; // return this; // } // // public Build addLayer(Class<? extends Layer> clz, Drawable icon, String iconName) { // mLayerList.add(new Item(clz,icon,iconName)); // return this; // } // public Config build() { // return new Config(this); // } // } // } // // Path: sak-nop/src/main/java/com/wanjian/sak/converter/ISizeConverter.java // public abstract class ISizeConverter { // public static ISizeConverter CONVERTER; // // public abstract String desc(); // // public abstract Size convert(Context context, float length); // // public abstract int recovery(Context context, float length); // // } // // Path: saklib/src/main/java/com/wanjian/sak/filter/ViewFilter.java // public abstract class ViewFilter { // public static ViewFilter FILTER = new ViewFilter() { // @Override // protected boolean apply(View view) { // return view.getVisibility() == View.VISIBLE; // } // }; // // // public final boolean filter(View view) { // return apply(view); // } // // protected abstract boolean apply(View view); // // @Override // public int hashCode() { // return getClass().hashCode(); // } // // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // return obj.getClass() == getClass(); // } // } // Path: sak-nop/src/main/java/com/wanjian/sak/layer/AbsLayer.java import android.content.Context; import android.graphics.Canvas; import android.graphics.drawable.Drawable; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.FrameLayout; import com.wanjian.sak.config.Config; import com.wanjian.sak.converter.ISizeConverter; import com.wanjian.sak.filter.ViewFilter; } protected void onUiUpdate(Canvas canvas, View rootView) { } protected void onAttached(View rootView) { } protected void onDetached(View rootView) { } protected int[] getLocationAndSize(View view) { return null; } protected int dp2px(int dip) { return 0; } protected int px2dp(float pxValue) { return 0; } protected ISizeConverter getSizeConverter() { return null; }
protected ViewFilter getViewFilter() {
android-notes/SwissArmyKnife
saklib/src/main/java/com/wanjian/sak/layer/impl/PaddingLayer.java
// Path: sak-nop/src/main/java/com/wanjian/sak/converter/ISizeConverter.java // public abstract class ISizeConverter { // public static ISizeConverter CONVERTER; // // public abstract String desc(); // // public abstract Size convert(Context context, float length); // // public abstract int recovery(Context context, float length); // // } // // Path: saklib/src/main/java/com/wanjian/sak/layer/ISize.java // public interface ISize { // void onSizeConvertChange(ISizeConverter converter); // } // // Path: saklib/src/main/java/com/wanjian/sak/utils/ScreenUtils.java // public class ScreenUtils { // // public static int dp2px(Context context, int dip) { // float density = context.getResources().getDisplayMetrics().density; // return (int) (dip * density + 0.5); // } // // public static int px2dp(Context context, float pxValue) { // final float scale = context.getResources().getDisplayMetrics().density; // return (int) (pxValue / scale + 0.5f); // } // // }
import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.view.View; import com.wanjian.sak.R; import com.wanjian.sak.converter.ISizeConverter; import com.wanjian.sak.layer.ISize; import com.wanjian.sak.utils.ScreenUtils; import java.text.DecimalFormat;
package com.wanjian.sak.layer.impl; /** * Created by wanjian on 2016/10/23. */ public class PaddingLayer extends ViewLayer implements ISize { private Paint mTextPaint; private Paint mBgPaint; private Paint mPaddingPaint; private int mTxtColor = 0xFF000000; private int mBgColor = 0x88FFFFFF; private int mPaddingColor = 0x3300FF0D; private Rect mRect = new Rect(); private DecimalFormat mFormat = new DecimalFormat("#.###"); @Override protected void onAttach(View rootView) { super.onAttach(rootView); mTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
// Path: sak-nop/src/main/java/com/wanjian/sak/converter/ISizeConverter.java // public abstract class ISizeConverter { // public static ISizeConverter CONVERTER; // // public abstract String desc(); // // public abstract Size convert(Context context, float length); // // public abstract int recovery(Context context, float length); // // } // // Path: saklib/src/main/java/com/wanjian/sak/layer/ISize.java // public interface ISize { // void onSizeConvertChange(ISizeConverter converter); // } // // Path: saklib/src/main/java/com/wanjian/sak/utils/ScreenUtils.java // public class ScreenUtils { // // public static int dp2px(Context context, int dip) { // float density = context.getResources().getDisplayMetrics().density; // return (int) (dip * density + 0.5); // } // // public static int px2dp(Context context, float pxValue) { // final float scale = context.getResources().getDisplayMetrics().density; // return (int) (pxValue / scale + 0.5f); // } // // } // Path: saklib/src/main/java/com/wanjian/sak/layer/impl/PaddingLayer.java import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.view.View; import com.wanjian.sak.R; import com.wanjian.sak.converter.ISizeConverter; import com.wanjian.sak.layer.ISize; import com.wanjian.sak.utils.ScreenUtils; import java.text.DecimalFormat; package com.wanjian.sak.layer.impl; /** * Created by wanjian on 2016/10/23. */ public class PaddingLayer extends ViewLayer implements ISize { private Paint mTextPaint; private Paint mBgPaint; private Paint mPaddingPaint; private int mTxtColor = 0xFF000000; private int mBgColor = 0x88FFFFFF; private int mPaddingColor = 0x3300FF0D; private Rect mRect = new Rect(); private DecimalFormat mFormat = new DecimalFormat("#.###"); @Override protected void onAttach(View rootView) { super.onAttach(rootView); mTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mTextPaint.setTextSize(ScreenUtils.dp2px(getContext(), 10));
android-notes/SwissArmyKnife
saklib/src/main/java/com/wanjian/sak/layer/impl/PaddingLayer.java
// Path: sak-nop/src/main/java/com/wanjian/sak/converter/ISizeConverter.java // public abstract class ISizeConverter { // public static ISizeConverter CONVERTER; // // public abstract String desc(); // // public abstract Size convert(Context context, float length); // // public abstract int recovery(Context context, float length); // // } // // Path: saklib/src/main/java/com/wanjian/sak/layer/ISize.java // public interface ISize { // void onSizeConvertChange(ISizeConverter converter); // } // // Path: saklib/src/main/java/com/wanjian/sak/utils/ScreenUtils.java // public class ScreenUtils { // // public static int dp2px(Context context, int dip) { // float density = context.getResources().getDisplayMetrics().density; // return (int) (dip * density + 0.5); // } // // public static int px2dp(Context context, float pxValue) { // final float scale = context.getResources().getDisplayMetrics().density; // return (int) (pxValue / scale + 0.5f); // } // // }
import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.view.View; import com.wanjian.sak.R; import com.wanjian.sak.converter.ISizeConverter; import com.wanjian.sak.layer.ISize; import com.wanjian.sak.utils.ScreenUtils; import java.text.DecimalFormat;
private Rect mRect = new Rect(); private DecimalFormat mFormat = new DecimalFormat("#.###"); @Override protected void onAttach(View rootView) { super.onAttach(rootView); mTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mTextPaint.setTextSize(ScreenUtils.dp2px(getContext(), 10)); mTextPaint.setColor(mTxtColor); mBgPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mBgPaint.setColor(mBgColor); mPaddingPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mPaddingPaint.setColor(mPaddingColor); } protected void onDraw(Canvas canvas, View view) { int l = view.getPaddingLeft(); int t = view.getPaddingTop(); int r = view.getPaddingRight(); int b = view.getPaddingBottom(); int w = view.getWidth(); int h = view.getHeight(); canvas.drawRect(0, 0, l, h, mPaddingPaint); canvas.drawRect(0, 0, w, t, mPaddingPaint); canvas.drawRect(w - r, 0, w, h, mPaddingPaint); canvas.drawRect(0, h - b, w, h, mPaddingPaint);
// Path: sak-nop/src/main/java/com/wanjian/sak/converter/ISizeConverter.java // public abstract class ISizeConverter { // public static ISizeConverter CONVERTER; // // public abstract String desc(); // // public abstract Size convert(Context context, float length); // // public abstract int recovery(Context context, float length); // // } // // Path: saklib/src/main/java/com/wanjian/sak/layer/ISize.java // public interface ISize { // void onSizeConvertChange(ISizeConverter converter); // } // // Path: saklib/src/main/java/com/wanjian/sak/utils/ScreenUtils.java // public class ScreenUtils { // // public static int dp2px(Context context, int dip) { // float density = context.getResources().getDisplayMetrics().density; // return (int) (dip * density + 0.5); // } // // public static int px2dp(Context context, float pxValue) { // final float scale = context.getResources().getDisplayMetrics().density; // return (int) (pxValue / scale + 0.5f); // } // // } // Path: saklib/src/main/java/com/wanjian/sak/layer/impl/PaddingLayer.java import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.view.View; import com.wanjian.sak.R; import com.wanjian.sak.converter.ISizeConverter; import com.wanjian.sak.layer.ISize; import com.wanjian.sak.utils.ScreenUtils; import java.text.DecimalFormat; private Rect mRect = new Rect(); private DecimalFormat mFormat = new DecimalFormat("#.###"); @Override protected void onAttach(View rootView) { super.onAttach(rootView); mTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mTextPaint.setTextSize(ScreenUtils.dp2px(getContext(), 10)); mTextPaint.setColor(mTxtColor); mBgPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mBgPaint.setColor(mBgColor); mPaddingPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mPaddingPaint.setColor(mPaddingColor); } protected void onDraw(Canvas canvas, View view) { int l = view.getPaddingLeft(); int t = view.getPaddingTop(); int r = view.getPaddingRight(); int b = view.getPaddingBottom(); int w = view.getWidth(); int h = view.getHeight(); canvas.drawRect(0, 0, l, h, mPaddingPaint); canvas.drawRect(0, 0, w, t, mPaddingPaint); canvas.drawRect(w - r, 0, w, h, mPaddingPaint); canvas.drawRect(0, h - b, w, h, mPaddingPaint);
ISizeConverter converter = getSizeConverter();
android-notes/SwissArmyKnife
app/src/main/java/com/wanjian/sak/demo/SegmentFragment.java
// Path: app/src/main/java/com/wanjian/sak/demo/a/fragment/with/a/very/very/very/longname/that/fragment/name/auto/scale/size/ContentFragment.java // public class ContentFragment extends Fragment { // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // TextView textView = new TextView(container.getContext()); // int color = ((int) (Math.random() * Integer.MAX_VALUE)) | 0xFF000000; // textView.setBackgroundColor(color); // textView.setText(Integer.toHexString(color)); // return textView; // } // // @Override // public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { // super.onViewCreated(view, savedInstanceState); // } // }
import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.wanjian.sak.demo.a.fragment.with.a.very.very.very.longname.that.fragment.name.auto.scale.size.ContentFragment;
package com.wanjian.sak.demo; public class SegmentFragment extends Fragment { @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.segment_fragment, container, false); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); view.setBackgroundColor(((int) (Math.random() * Integer.MAX_VALUE)) | 0xFF000000);
// Path: app/src/main/java/com/wanjian/sak/demo/a/fragment/with/a/very/very/very/longname/that/fragment/name/auto/scale/size/ContentFragment.java // public class ContentFragment extends Fragment { // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // TextView textView = new TextView(container.getContext()); // int color = ((int) (Math.random() * Integer.MAX_VALUE)) | 0xFF000000; // textView.setBackgroundColor(color); // textView.setText(Integer.toHexString(color)); // return textView; // } // // @Override // public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { // super.onViewCreated(view, savedInstanceState); // } // } // Path: app/src/main/java/com/wanjian/sak/demo/SegmentFragment.java import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.wanjian.sak.demo.a.fragment.with.a.very.very.very.longname.that.fragment.name.auto.scale.size.ContentFragment; package com.wanjian.sak.demo; public class SegmentFragment extends Fragment { @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.segment_fragment, container, false); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); view.setBackgroundColor(((int) (Math.random() * Integer.MAX_VALUE)) | 0xFF000000);
getChildFragmentManager().beginTransaction().replace(R.id.container, new ContentFragment()).commit();
android-notes/SwissArmyKnife
saklib/src/main/java/com/wanjian/sak/layer/impl/BorderLayer.java
// Path: saklib/src/main/java/com/wanjian/sak/utils/ScreenUtils.java // public class ScreenUtils { // // public static int dp2px(Context context, int dip) { // float density = context.getResources().getDisplayMetrics().density; // return (int) (dip * density + 0.5); // } // // public static int px2dp(Context context, float pxValue) { // final float scale = context.getResources().getDisplayMetrics().density; // return (int) (pxValue / scale + 0.5f); // } // // }
import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.drawable.Drawable; import android.view.View; import com.wanjian.sak.R; import com.wanjian.sak.utils.ScreenUtils;
package com.wanjian.sak.layer.impl; /** * Created by wanjian on 2016/10/24. */ public class BorderLayer extends ViewLayer { private Paint mBorderPaint; private Paint mCornerPaint; private int mCornerW; private int w; private int h; @Override protected void onAttach(View rootView) { super.onAttach(rootView); mBorderPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mBorderPaint.setStyle(Paint.Style.STROKE); mBorderPaint.setColor(getBorderColor()); mCornerPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mCornerPaint.setStyle(Paint.Style.STROKE);
// Path: saklib/src/main/java/com/wanjian/sak/utils/ScreenUtils.java // public class ScreenUtils { // // public static int dp2px(Context context, int dip) { // float density = context.getResources().getDisplayMetrics().density; // return (int) (dip * density + 0.5); // } // // public static int px2dp(Context context, float pxValue) { // final float scale = context.getResources().getDisplayMetrics().density; // return (int) (pxValue / scale + 0.5f); // } // // } // Path: saklib/src/main/java/com/wanjian/sak/layer/impl/BorderLayer.java import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.drawable.Drawable; import android.view.View; import com.wanjian.sak.R; import com.wanjian.sak.utils.ScreenUtils; package com.wanjian.sak.layer.impl; /** * Created by wanjian on 2016/10/24. */ public class BorderLayer extends ViewLayer { private Paint mBorderPaint; private Paint mCornerPaint; private int mCornerW; private int w; private int h; @Override protected void onAttach(View rootView) { super.onAttach(rootView); mBorderPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mBorderPaint.setStyle(Paint.Style.STROKE); mBorderPaint.setColor(getBorderColor()); mCornerPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mCornerPaint.setStyle(Paint.Style.STROKE);
mCornerPaint.setStrokeWidth(ScreenUtils.dp2px(getContext(), 1));
android-notes/SwissArmyKnife
saklib/src/main/java/com/wanjian/sak/system/canvaspool/CanvasPoolCompact.java
// Path: systemlib/src/main/java/android/graphics/RecordingCanvas.java // public class RecordingCanvas extends Canvas { // private static final int POOL_LIMIT = 25; // private static final Pools.SynchronizedPool<RecordingCanvas> sPool = // new Pools.SynchronizedPool<>(POOL_LIMIT); // // // public void enableZ() { // } // // public void disableZ() { // } // // public void drawRenderNode(RenderNode renderNode) { // } // } // // Path: systemlib/src/main/java/android/util/Pools.java // public final class Pools { // // /** // * Interface for managing a pool of objects. // * // * @param <T> The pooled type. // */ // public static interface Pool<T> { // // /** // * @return An instance from the pool if such, null otherwise. // */ // public T acquire(); // // /** // * Release an instance to the pool. // * // * @param instance The instance to release. // * @return Whether the instance was put in the pool. // * @throws IllegalStateException If the instance is already in the pool. // */ // public boolean release(T instance); // } // // private Pools() { // /* do nothing - hiding constructor */ // } // // /** // * Simple (non-synchronized) pool of objects. // * // * @param <T> The pooled type. // */ // public static class SimplePool<T> implements Pool<T> { // private final Object[] mPool; // // private int mPoolSize; // // /** // * Creates a new instance. // * // * @param maxPoolSize The max pool size. // * @throws IllegalArgumentException If the max pool size is less than zero. // */ // public SimplePool(int maxPoolSize) { // if (maxPoolSize <= 0) { // throw new IllegalArgumentException("The max pool size must be > 0"); // } // mPool = new Object[maxPoolSize]; // } // // @Override // @SuppressWarnings("unchecked") // public T acquire() { // if (mPoolSize > 0) { // final int lastPooledIndex = mPoolSize - 1; // T instance = (T) mPool[lastPooledIndex]; // mPool[lastPooledIndex] = null; // mPoolSize--; // return instance; // } // return null; // } // // @Override // public boolean release(T instance) { // if (isInPool(instance)) { // throw new IllegalStateException("Already in the pool!"); // } // if (mPoolSize < mPool.length) { // mPool[mPoolSize] = instance; // mPoolSize++; // return true; // } // return false; // } // // private boolean isInPool(T instance) { // for (int i = 0; i < mPoolSize; i++) { // if (mPool[i] == instance) { // return true; // } // } // return false; // } // } // // /** // * Synchronized pool of objects. // * // * @param <T> The pooled type. // */ // public static class SynchronizedPool<T> extends SimplePool<T> { // private final Object mLock; // // /** // * Creates a new instance. // * // * @param maxPoolSize The max pool size. // * @param lock an optional custom object to synchronize on // * @throws IllegalArgumentException If the max pool size is less than zero. // */ // public SynchronizedPool(int maxPoolSize, Object lock) { // super(maxPoolSize); // mLock = lock; // } // // /** // * @see #SynchronizedPool(int, Object) // */ // public SynchronizedPool(int maxPoolSize) { // this(maxPoolSize, new Object()); // } // // @Override // public T acquire() { // synchronized (mLock) { // return super.acquire(); // } // } // // @Override // public boolean release(T element) { // synchronized (mLock) { // return super.release(element); // } // } // } // } // // Path: systemlib/src/main/java/android/view/DisplayListCanvas.java // public class DisplayListCanvas extends Canvas { // // private static final int POOL_LIMIT = 25; // //android 6.0,7.0,7.1,8.0,8.1,9.0 // private static final Pools.SynchronizedPool<DisplayListCanvas> sPool = // new Pools.SynchronizedPool<DisplayListCanvas>(POOL_LIMIT); // // public void onPreDraw(Rect dirty) { // } // // public void insertReorderBarrier() { // } // // public void insertInorderBarrier() { // } // // public void drawRenderNode(RenderNode renderNode) { // } // }
import android.graphics.Canvas; import android.graphics.RecordingCanvas; import android.os.Build; import android.util.Pools; import android.view.DisplayListCanvas; import java.lang.ref.WeakReference; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Iterator; import java.util.List;
package com.wanjian.sak.system.canvaspool; public class CanvasPoolCompact { private static CanvasPoolCompact sInstance = new CanvasPoolCompact(); public static CanvasPoolCompact get() { return sInstance; } private List<WeakReference<CanvasRecycleListener>> listeners = new ArrayList<>(); private CanvasPoolCompact() { Class clz; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
// Path: systemlib/src/main/java/android/graphics/RecordingCanvas.java // public class RecordingCanvas extends Canvas { // private static final int POOL_LIMIT = 25; // private static final Pools.SynchronizedPool<RecordingCanvas> sPool = // new Pools.SynchronizedPool<>(POOL_LIMIT); // // // public void enableZ() { // } // // public void disableZ() { // } // // public void drawRenderNode(RenderNode renderNode) { // } // } // // Path: systemlib/src/main/java/android/util/Pools.java // public final class Pools { // // /** // * Interface for managing a pool of objects. // * // * @param <T> The pooled type. // */ // public static interface Pool<T> { // // /** // * @return An instance from the pool if such, null otherwise. // */ // public T acquire(); // // /** // * Release an instance to the pool. // * // * @param instance The instance to release. // * @return Whether the instance was put in the pool. // * @throws IllegalStateException If the instance is already in the pool. // */ // public boolean release(T instance); // } // // private Pools() { // /* do nothing - hiding constructor */ // } // // /** // * Simple (non-synchronized) pool of objects. // * // * @param <T> The pooled type. // */ // public static class SimplePool<T> implements Pool<T> { // private final Object[] mPool; // // private int mPoolSize; // // /** // * Creates a new instance. // * // * @param maxPoolSize The max pool size. // * @throws IllegalArgumentException If the max pool size is less than zero. // */ // public SimplePool(int maxPoolSize) { // if (maxPoolSize <= 0) { // throw new IllegalArgumentException("The max pool size must be > 0"); // } // mPool = new Object[maxPoolSize]; // } // // @Override // @SuppressWarnings("unchecked") // public T acquire() { // if (mPoolSize > 0) { // final int lastPooledIndex = mPoolSize - 1; // T instance = (T) mPool[lastPooledIndex]; // mPool[lastPooledIndex] = null; // mPoolSize--; // return instance; // } // return null; // } // // @Override // public boolean release(T instance) { // if (isInPool(instance)) { // throw new IllegalStateException("Already in the pool!"); // } // if (mPoolSize < mPool.length) { // mPool[mPoolSize] = instance; // mPoolSize++; // return true; // } // return false; // } // // private boolean isInPool(T instance) { // for (int i = 0; i < mPoolSize; i++) { // if (mPool[i] == instance) { // return true; // } // } // return false; // } // } // // /** // * Synchronized pool of objects. // * // * @param <T> The pooled type. // */ // public static class SynchronizedPool<T> extends SimplePool<T> { // private final Object mLock; // // /** // * Creates a new instance. // * // * @param maxPoolSize The max pool size. // * @param lock an optional custom object to synchronize on // * @throws IllegalArgumentException If the max pool size is less than zero. // */ // public SynchronizedPool(int maxPoolSize, Object lock) { // super(maxPoolSize); // mLock = lock; // } // // /** // * @see #SynchronizedPool(int, Object) // */ // public SynchronizedPool(int maxPoolSize) { // this(maxPoolSize, new Object()); // } // // @Override // public T acquire() { // synchronized (mLock) { // return super.acquire(); // } // } // // @Override // public boolean release(T element) { // synchronized (mLock) { // return super.release(element); // } // } // } // } // // Path: systemlib/src/main/java/android/view/DisplayListCanvas.java // public class DisplayListCanvas extends Canvas { // // private static final int POOL_LIMIT = 25; // //android 6.0,7.0,7.1,8.0,8.1,9.0 // private static final Pools.SynchronizedPool<DisplayListCanvas> sPool = // new Pools.SynchronizedPool<DisplayListCanvas>(POOL_LIMIT); // // public void onPreDraw(Rect dirty) { // } // // public void insertReorderBarrier() { // } // // public void insertInorderBarrier() { // } // // public void drawRenderNode(RenderNode renderNode) { // } // } // Path: saklib/src/main/java/com/wanjian/sak/system/canvaspool/CanvasPoolCompact.java import android.graphics.Canvas; import android.graphics.RecordingCanvas; import android.os.Build; import android.util.Pools; import android.view.DisplayListCanvas; import java.lang.ref.WeakReference; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Iterator; import java.util.List; package com.wanjian.sak.system.canvaspool; public class CanvasPoolCompact { private static CanvasPoolCompact sInstance = new CanvasPoolCompact(); public static CanvasPoolCompact get() { return sInstance; } private List<WeakReference<CanvasRecycleListener>> listeners = new ArrayList<>(); private CanvasPoolCompact() { Class clz; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
clz = RecordingCanvas.class;
android-notes/SwissArmyKnife
saklib/src/main/java/com/wanjian/sak/system/canvaspool/CanvasPoolCompact.java
// Path: systemlib/src/main/java/android/graphics/RecordingCanvas.java // public class RecordingCanvas extends Canvas { // private static final int POOL_LIMIT = 25; // private static final Pools.SynchronizedPool<RecordingCanvas> sPool = // new Pools.SynchronizedPool<>(POOL_LIMIT); // // // public void enableZ() { // } // // public void disableZ() { // } // // public void drawRenderNode(RenderNode renderNode) { // } // } // // Path: systemlib/src/main/java/android/util/Pools.java // public final class Pools { // // /** // * Interface for managing a pool of objects. // * // * @param <T> The pooled type. // */ // public static interface Pool<T> { // // /** // * @return An instance from the pool if such, null otherwise. // */ // public T acquire(); // // /** // * Release an instance to the pool. // * // * @param instance The instance to release. // * @return Whether the instance was put in the pool. // * @throws IllegalStateException If the instance is already in the pool. // */ // public boolean release(T instance); // } // // private Pools() { // /* do nothing - hiding constructor */ // } // // /** // * Simple (non-synchronized) pool of objects. // * // * @param <T> The pooled type. // */ // public static class SimplePool<T> implements Pool<T> { // private final Object[] mPool; // // private int mPoolSize; // // /** // * Creates a new instance. // * // * @param maxPoolSize The max pool size. // * @throws IllegalArgumentException If the max pool size is less than zero. // */ // public SimplePool(int maxPoolSize) { // if (maxPoolSize <= 0) { // throw new IllegalArgumentException("The max pool size must be > 0"); // } // mPool = new Object[maxPoolSize]; // } // // @Override // @SuppressWarnings("unchecked") // public T acquire() { // if (mPoolSize > 0) { // final int lastPooledIndex = mPoolSize - 1; // T instance = (T) mPool[lastPooledIndex]; // mPool[lastPooledIndex] = null; // mPoolSize--; // return instance; // } // return null; // } // // @Override // public boolean release(T instance) { // if (isInPool(instance)) { // throw new IllegalStateException("Already in the pool!"); // } // if (mPoolSize < mPool.length) { // mPool[mPoolSize] = instance; // mPoolSize++; // return true; // } // return false; // } // // private boolean isInPool(T instance) { // for (int i = 0; i < mPoolSize; i++) { // if (mPool[i] == instance) { // return true; // } // } // return false; // } // } // // /** // * Synchronized pool of objects. // * // * @param <T> The pooled type. // */ // public static class SynchronizedPool<T> extends SimplePool<T> { // private final Object mLock; // // /** // * Creates a new instance. // * // * @param maxPoolSize The max pool size. // * @param lock an optional custom object to synchronize on // * @throws IllegalArgumentException If the max pool size is less than zero. // */ // public SynchronizedPool(int maxPoolSize, Object lock) { // super(maxPoolSize); // mLock = lock; // } // // /** // * @see #SynchronizedPool(int, Object) // */ // public SynchronizedPool(int maxPoolSize) { // this(maxPoolSize, new Object()); // } // // @Override // public T acquire() { // synchronized (mLock) { // return super.acquire(); // } // } // // @Override // public boolean release(T element) { // synchronized (mLock) { // return super.release(element); // } // } // } // } // // Path: systemlib/src/main/java/android/view/DisplayListCanvas.java // public class DisplayListCanvas extends Canvas { // // private static final int POOL_LIMIT = 25; // //android 6.0,7.0,7.1,8.0,8.1,9.0 // private static final Pools.SynchronizedPool<DisplayListCanvas> sPool = // new Pools.SynchronizedPool<DisplayListCanvas>(POOL_LIMIT); // // public void onPreDraw(Rect dirty) { // } // // public void insertReorderBarrier() { // } // // public void insertInorderBarrier() { // } // // public void drawRenderNode(RenderNode renderNode) { // } // }
import android.graphics.Canvas; import android.graphics.RecordingCanvas; import android.os.Build; import android.util.Pools; import android.view.DisplayListCanvas; import java.lang.ref.WeakReference; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Iterator; import java.util.List;
package com.wanjian.sak.system.canvaspool; public class CanvasPoolCompact { private static CanvasPoolCompact sInstance = new CanvasPoolCompact(); public static CanvasPoolCompact get() { return sInstance; } private List<WeakReference<CanvasRecycleListener>> listeners = new ArrayList<>(); private CanvasPoolCompact() { Class clz; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { clz = RecordingCanvas.class; } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// Path: systemlib/src/main/java/android/graphics/RecordingCanvas.java // public class RecordingCanvas extends Canvas { // private static final int POOL_LIMIT = 25; // private static final Pools.SynchronizedPool<RecordingCanvas> sPool = // new Pools.SynchronizedPool<>(POOL_LIMIT); // // // public void enableZ() { // } // // public void disableZ() { // } // // public void drawRenderNode(RenderNode renderNode) { // } // } // // Path: systemlib/src/main/java/android/util/Pools.java // public final class Pools { // // /** // * Interface for managing a pool of objects. // * // * @param <T> The pooled type. // */ // public static interface Pool<T> { // // /** // * @return An instance from the pool if such, null otherwise. // */ // public T acquire(); // // /** // * Release an instance to the pool. // * // * @param instance The instance to release. // * @return Whether the instance was put in the pool. // * @throws IllegalStateException If the instance is already in the pool. // */ // public boolean release(T instance); // } // // private Pools() { // /* do nothing - hiding constructor */ // } // // /** // * Simple (non-synchronized) pool of objects. // * // * @param <T> The pooled type. // */ // public static class SimplePool<T> implements Pool<T> { // private final Object[] mPool; // // private int mPoolSize; // // /** // * Creates a new instance. // * // * @param maxPoolSize The max pool size. // * @throws IllegalArgumentException If the max pool size is less than zero. // */ // public SimplePool(int maxPoolSize) { // if (maxPoolSize <= 0) { // throw new IllegalArgumentException("The max pool size must be > 0"); // } // mPool = new Object[maxPoolSize]; // } // // @Override // @SuppressWarnings("unchecked") // public T acquire() { // if (mPoolSize > 0) { // final int lastPooledIndex = mPoolSize - 1; // T instance = (T) mPool[lastPooledIndex]; // mPool[lastPooledIndex] = null; // mPoolSize--; // return instance; // } // return null; // } // // @Override // public boolean release(T instance) { // if (isInPool(instance)) { // throw new IllegalStateException("Already in the pool!"); // } // if (mPoolSize < mPool.length) { // mPool[mPoolSize] = instance; // mPoolSize++; // return true; // } // return false; // } // // private boolean isInPool(T instance) { // for (int i = 0; i < mPoolSize; i++) { // if (mPool[i] == instance) { // return true; // } // } // return false; // } // } // // /** // * Synchronized pool of objects. // * // * @param <T> The pooled type. // */ // public static class SynchronizedPool<T> extends SimplePool<T> { // private final Object mLock; // // /** // * Creates a new instance. // * // * @param maxPoolSize The max pool size. // * @param lock an optional custom object to synchronize on // * @throws IllegalArgumentException If the max pool size is less than zero. // */ // public SynchronizedPool(int maxPoolSize, Object lock) { // super(maxPoolSize); // mLock = lock; // } // // /** // * @see #SynchronizedPool(int, Object) // */ // public SynchronizedPool(int maxPoolSize) { // this(maxPoolSize, new Object()); // } // // @Override // public T acquire() { // synchronized (mLock) { // return super.acquire(); // } // } // // @Override // public boolean release(T element) { // synchronized (mLock) { // return super.release(element); // } // } // } // } // // Path: systemlib/src/main/java/android/view/DisplayListCanvas.java // public class DisplayListCanvas extends Canvas { // // private static final int POOL_LIMIT = 25; // //android 6.0,7.0,7.1,8.0,8.1,9.0 // private static final Pools.SynchronizedPool<DisplayListCanvas> sPool = // new Pools.SynchronizedPool<DisplayListCanvas>(POOL_LIMIT); // // public void onPreDraw(Rect dirty) { // } // // public void insertReorderBarrier() { // } // // public void insertInorderBarrier() { // } // // public void drawRenderNode(RenderNode renderNode) { // } // } // Path: saklib/src/main/java/com/wanjian/sak/system/canvaspool/CanvasPoolCompact.java import android.graphics.Canvas; import android.graphics.RecordingCanvas; import android.os.Build; import android.util.Pools; import android.view.DisplayListCanvas; import java.lang.ref.WeakReference; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Iterator; import java.util.List; package com.wanjian.sak.system.canvaspool; public class CanvasPoolCompact { private static CanvasPoolCompact sInstance = new CanvasPoolCompact(); public static CanvasPoolCompact get() { return sInstance; } private List<WeakReference<CanvasRecycleListener>> listeners = new ArrayList<>(); private CanvasPoolCompact() { Class clz; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { clz = RecordingCanvas.class; } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
clz = DisplayListCanvas.class;
android-notes/SwissArmyKnife
saklib/src/main/java/com/wanjian/sak/system/canvaspool/CanvasPoolCompact.java
// Path: systemlib/src/main/java/android/graphics/RecordingCanvas.java // public class RecordingCanvas extends Canvas { // private static final int POOL_LIMIT = 25; // private static final Pools.SynchronizedPool<RecordingCanvas> sPool = // new Pools.SynchronizedPool<>(POOL_LIMIT); // // // public void enableZ() { // } // // public void disableZ() { // } // // public void drawRenderNode(RenderNode renderNode) { // } // } // // Path: systemlib/src/main/java/android/util/Pools.java // public final class Pools { // // /** // * Interface for managing a pool of objects. // * // * @param <T> The pooled type. // */ // public static interface Pool<T> { // // /** // * @return An instance from the pool if such, null otherwise. // */ // public T acquire(); // // /** // * Release an instance to the pool. // * // * @param instance The instance to release. // * @return Whether the instance was put in the pool. // * @throws IllegalStateException If the instance is already in the pool. // */ // public boolean release(T instance); // } // // private Pools() { // /* do nothing - hiding constructor */ // } // // /** // * Simple (non-synchronized) pool of objects. // * // * @param <T> The pooled type. // */ // public static class SimplePool<T> implements Pool<T> { // private final Object[] mPool; // // private int mPoolSize; // // /** // * Creates a new instance. // * // * @param maxPoolSize The max pool size. // * @throws IllegalArgumentException If the max pool size is less than zero. // */ // public SimplePool(int maxPoolSize) { // if (maxPoolSize <= 0) { // throw new IllegalArgumentException("The max pool size must be > 0"); // } // mPool = new Object[maxPoolSize]; // } // // @Override // @SuppressWarnings("unchecked") // public T acquire() { // if (mPoolSize > 0) { // final int lastPooledIndex = mPoolSize - 1; // T instance = (T) mPool[lastPooledIndex]; // mPool[lastPooledIndex] = null; // mPoolSize--; // return instance; // } // return null; // } // // @Override // public boolean release(T instance) { // if (isInPool(instance)) { // throw new IllegalStateException("Already in the pool!"); // } // if (mPoolSize < mPool.length) { // mPool[mPoolSize] = instance; // mPoolSize++; // return true; // } // return false; // } // // private boolean isInPool(T instance) { // for (int i = 0; i < mPoolSize; i++) { // if (mPool[i] == instance) { // return true; // } // } // return false; // } // } // // /** // * Synchronized pool of objects. // * // * @param <T> The pooled type. // */ // public static class SynchronizedPool<T> extends SimplePool<T> { // private final Object mLock; // // /** // * Creates a new instance. // * // * @param maxPoolSize The max pool size. // * @param lock an optional custom object to synchronize on // * @throws IllegalArgumentException If the max pool size is less than zero. // */ // public SynchronizedPool(int maxPoolSize, Object lock) { // super(maxPoolSize); // mLock = lock; // } // // /** // * @see #SynchronizedPool(int, Object) // */ // public SynchronizedPool(int maxPoolSize) { // this(maxPoolSize, new Object()); // } // // @Override // public T acquire() { // synchronized (mLock) { // return super.acquire(); // } // } // // @Override // public boolean release(T element) { // synchronized (mLock) { // return super.release(element); // } // } // } // } // // Path: systemlib/src/main/java/android/view/DisplayListCanvas.java // public class DisplayListCanvas extends Canvas { // // private static final int POOL_LIMIT = 25; // //android 6.0,7.0,7.1,8.0,8.1,9.0 // private static final Pools.SynchronizedPool<DisplayListCanvas> sPool = // new Pools.SynchronizedPool<DisplayListCanvas>(POOL_LIMIT); // // public void onPreDraw(Rect dirty) { // } // // public void insertReorderBarrier() { // } // // public void insertInorderBarrier() { // } // // public void drawRenderNode(RenderNode renderNode) { // } // }
import android.graphics.Canvas; import android.graphics.RecordingCanvas; import android.os.Build; import android.util.Pools; import android.view.DisplayListCanvas; import java.lang.ref.WeakReference; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Iterator; import java.util.List;
package com.wanjian.sak.system.canvaspool; public class CanvasPoolCompact { private static CanvasPoolCompact sInstance = new CanvasPoolCompact(); public static CanvasPoolCompact get() { return sInstance; } private List<WeakReference<CanvasRecycleListener>> listeners = new ArrayList<>(); private CanvasPoolCompact() { Class clz; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { clz = RecordingCanvas.class; } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { clz = DisplayListCanvas.class; } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { try { clz = Class.forName("android.view.GLES20RecordingCanvas"); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } else { throw new RuntimeException(); }
// Path: systemlib/src/main/java/android/graphics/RecordingCanvas.java // public class RecordingCanvas extends Canvas { // private static final int POOL_LIMIT = 25; // private static final Pools.SynchronizedPool<RecordingCanvas> sPool = // new Pools.SynchronizedPool<>(POOL_LIMIT); // // // public void enableZ() { // } // // public void disableZ() { // } // // public void drawRenderNode(RenderNode renderNode) { // } // } // // Path: systemlib/src/main/java/android/util/Pools.java // public final class Pools { // // /** // * Interface for managing a pool of objects. // * // * @param <T> The pooled type. // */ // public static interface Pool<T> { // // /** // * @return An instance from the pool if such, null otherwise. // */ // public T acquire(); // // /** // * Release an instance to the pool. // * // * @param instance The instance to release. // * @return Whether the instance was put in the pool. // * @throws IllegalStateException If the instance is already in the pool. // */ // public boolean release(T instance); // } // // private Pools() { // /* do nothing - hiding constructor */ // } // // /** // * Simple (non-synchronized) pool of objects. // * // * @param <T> The pooled type. // */ // public static class SimplePool<T> implements Pool<T> { // private final Object[] mPool; // // private int mPoolSize; // // /** // * Creates a new instance. // * // * @param maxPoolSize The max pool size. // * @throws IllegalArgumentException If the max pool size is less than zero. // */ // public SimplePool(int maxPoolSize) { // if (maxPoolSize <= 0) { // throw new IllegalArgumentException("The max pool size must be > 0"); // } // mPool = new Object[maxPoolSize]; // } // // @Override // @SuppressWarnings("unchecked") // public T acquire() { // if (mPoolSize > 0) { // final int lastPooledIndex = mPoolSize - 1; // T instance = (T) mPool[lastPooledIndex]; // mPool[lastPooledIndex] = null; // mPoolSize--; // return instance; // } // return null; // } // // @Override // public boolean release(T instance) { // if (isInPool(instance)) { // throw new IllegalStateException("Already in the pool!"); // } // if (mPoolSize < mPool.length) { // mPool[mPoolSize] = instance; // mPoolSize++; // return true; // } // return false; // } // // private boolean isInPool(T instance) { // for (int i = 0; i < mPoolSize; i++) { // if (mPool[i] == instance) { // return true; // } // } // return false; // } // } // // /** // * Synchronized pool of objects. // * // * @param <T> The pooled type. // */ // public static class SynchronizedPool<T> extends SimplePool<T> { // private final Object mLock; // // /** // * Creates a new instance. // * // * @param maxPoolSize The max pool size. // * @param lock an optional custom object to synchronize on // * @throws IllegalArgumentException If the max pool size is less than zero. // */ // public SynchronizedPool(int maxPoolSize, Object lock) { // super(maxPoolSize); // mLock = lock; // } // // /** // * @see #SynchronizedPool(int, Object) // */ // public SynchronizedPool(int maxPoolSize) { // this(maxPoolSize, new Object()); // } // // @Override // public T acquire() { // synchronized (mLock) { // return super.acquire(); // } // } // // @Override // public boolean release(T element) { // synchronized (mLock) { // return super.release(element); // } // } // } // } // // Path: systemlib/src/main/java/android/view/DisplayListCanvas.java // public class DisplayListCanvas extends Canvas { // // private static final int POOL_LIMIT = 25; // //android 6.0,7.0,7.1,8.0,8.1,9.0 // private static final Pools.SynchronizedPool<DisplayListCanvas> sPool = // new Pools.SynchronizedPool<DisplayListCanvas>(POOL_LIMIT); // // public void onPreDraw(Rect dirty) { // } // // public void insertReorderBarrier() { // } // // public void insertInorderBarrier() { // } // // public void drawRenderNode(RenderNode renderNode) { // } // } // Path: saklib/src/main/java/com/wanjian/sak/system/canvaspool/CanvasPoolCompact.java import android.graphics.Canvas; import android.graphics.RecordingCanvas; import android.os.Build; import android.util.Pools; import android.view.DisplayListCanvas; import java.lang.ref.WeakReference; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Iterator; import java.util.List; package com.wanjian.sak.system.canvaspool; public class CanvasPoolCompact { private static CanvasPoolCompact sInstance = new CanvasPoolCompact(); public static CanvasPoolCompact get() { return sInstance; } private List<WeakReference<CanvasRecycleListener>> listeners = new ArrayList<>(); private CanvasPoolCompact() { Class clz; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { clz = RecordingCanvas.class; } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { clz = DisplayListCanvas.class; } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { try { clz = Class.forName("android.view.GLES20RecordingCanvas"); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } else { throw new RuntimeException(); }
final Pools.SynchronizedPool origin;
android-notes/SwissArmyKnife
saklib/src/main/java/com/wanjian/sak/layer/impl/MarginLayer.java
// Path: sak-nop/src/main/java/com/wanjian/sak/converter/ISizeConverter.java // public abstract class ISizeConverter { // public static ISizeConverter CONVERTER; // // public abstract String desc(); // // public abstract Size convert(Context context, float length); // // public abstract int recovery(Context context, float length); // // } // // Path: saklib/src/main/java/com/wanjian/sak/layer/ISize.java // public interface ISize { // void onSizeConvertChange(ISizeConverter converter); // } // // Path: saklib/src/main/java/com/wanjian/sak/utils/ScreenUtils.java // public class ScreenUtils { // // public static int dp2px(Context context, int dip) { // float density = context.getResources().getDisplayMetrics().density; // return (int) (dip * density + 0.5); // } // // public static int px2dp(Context context, float pxValue) { // final float scale = context.getResources().getDisplayMetrics().density; // return (int) (pxValue / scale + 0.5f); // } // // }
import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Rect; import android.view.View; import android.view.ViewGroup; import com.wanjian.sak.converter.ISizeConverter; import com.wanjian.sak.layer.ISize; import com.wanjian.sak.utils.ScreenUtils; import java.text.DecimalFormat;
package com.wanjian.sak.layer.impl; /** * Created by wanjian on 2016/10/23. */ public class MarginLayer extends ViewLayer implements ISize { private Paint mTextPaint; private Paint mBgPaint; private Paint mMarginPaint; private int mTxtColor = 0xFF000000; private int mBgColor = 0x88FFFFFF; private int mMarginColor = 0x33FF0008; private Rect mRect = new Rect(); private DecimalFormat mFormat = new DecimalFormat("#.###"); @Override protected void onAttach(View rootView) { super.onAttach(rootView); mTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
// Path: sak-nop/src/main/java/com/wanjian/sak/converter/ISizeConverter.java // public abstract class ISizeConverter { // public static ISizeConverter CONVERTER; // // public abstract String desc(); // // public abstract Size convert(Context context, float length); // // public abstract int recovery(Context context, float length); // // } // // Path: saklib/src/main/java/com/wanjian/sak/layer/ISize.java // public interface ISize { // void onSizeConvertChange(ISizeConverter converter); // } // // Path: saklib/src/main/java/com/wanjian/sak/utils/ScreenUtils.java // public class ScreenUtils { // // public static int dp2px(Context context, int dip) { // float density = context.getResources().getDisplayMetrics().density; // return (int) (dip * density + 0.5); // } // // public static int px2dp(Context context, float pxValue) { // final float scale = context.getResources().getDisplayMetrics().density; // return (int) (pxValue / scale + 0.5f); // } // // } // Path: saklib/src/main/java/com/wanjian/sak/layer/impl/MarginLayer.java import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Rect; import android.view.View; import android.view.ViewGroup; import com.wanjian.sak.converter.ISizeConverter; import com.wanjian.sak.layer.ISize; import com.wanjian.sak.utils.ScreenUtils; import java.text.DecimalFormat; package com.wanjian.sak.layer.impl; /** * Created by wanjian on 2016/10/23. */ public class MarginLayer extends ViewLayer implements ISize { private Paint mTextPaint; private Paint mBgPaint; private Paint mMarginPaint; private int mTxtColor = 0xFF000000; private int mBgColor = 0x88FFFFFF; private int mMarginColor = 0x33FF0008; private Rect mRect = new Rect(); private DecimalFormat mFormat = new DecimalFormat("#.###"); @Override protected void onAttach(View rootView) { super.onAttach(rootView); mTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mTextPaint.setTextSize(ScreenUtils.dp2px(getContext(), 10));
android-notes/SwissArmyKnife
saklib/src/main/java/com/wanjian/sak/layer/impl/MarginLayer.java
// Path: sak-nop/src/main/java/com/wanjian/sak/converter/ISizeConverter.java // public abstract class ISizeConverter { // public static ISizeConverter CONVERTER; // // public abstract String desc(); // // public abstract Size convert(Context context, float length); // // public abstract int recovery(Context context, float length); // // } // // Path: saklib/src/main/java/com/wanjian/sak/layer/ISize.java // public interface ISize { // void onSizeConvertChange(ISizeConverter converter); // } // // Path: saklib/src/main/java/com/wanjian/sak/utils/ScreenUtils.java // public class ScreenUtils { // // public static int dp2px(Context context, int dip) { // float density = context.getResources().getDisplayMetrics().density; // return (int) (dip * density + 0.5); // } // // public static int px2dp(Context context, float pxValue) { // final float scale = context.getResources().getDisplayMetrics().density; // return (int) (pxValue / scale + 0.5f); // } // // }
import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Rect; import android.view.View; import android.view.ViewGroup; import com.wanjian.sak.converter.ISizeConverter; import com.wanjian.sak.layer.ISize; import com.wanjian.sak.utils.ScreenUtils; import java.text.DecimalFormat;
} int childCount = ((ViewGroup) view).getChildCount(); for (int i = 0; i < childCount; i++) { canvas.save(); drawMargin(canvas, ((ViewGroup) view).getChildAt(i)); canvas.restore(); } } private void drawMargin(Canvas canvas, View view) { ViewGroup.LayoutParams params = view.getLayoutParams(); if (!(params instanceof ViewGroup.MarginLayoutParams)) { return; }//画 外边距 int w = view.getWidth(); int h = view.getHeight(); ViewGroup.MarginLayoutParams marginLayoutParams = ((ViewGroup.MarginLayoutParams) params); canvas.translate(view.getX(), view.getY()); int l = -marginLayoutParams.leftMargin; int t = -marginLayoutParams.topMargin; int r = w + marginLayoutParams.rightMargin; int b = h + marginLayoutParams.bottomMargin; canvas.drawRect(l, 0, 0, h, mMarginPaint);//left canvas.drawRect(w, 0, r, h, mMarginPaint);//right canvas.drawRect(0, t, w, 0, mMarginPaint); canvas.drawRect(0, h, w, b, mMarginPaint);
// Path: sak-nop/src/main/java/com/wanjian/sak/converter/ISizeConverter.java // public abstract class ISizeConverter { // public static ISizeConverter CONVERTER; // // public abstract String desc(); // // public abstract Size convert(Context context, float length); // // public abstract int recovery(Context context, float length); // // } // // Path: saklib/src/main/java/com/wanjian/sak/layer/ISize.java // public interface ISize { // void onSizeConvertChange(ISizeConverter converter); // } // // Path: saklib/src/main/java/com/wanjian/sak/utils/ScreenUtils.java // public class ScreenUtils { // // public static int dp2px(Context context, int dip) { // float density = context.getResources().getDisplayMetrics().density; // return (int) (dip * density + 0.5); // } // // public static int px2dp(Context context, float pxValue) { // final float scale = context.getResources().getDisplayMetrics().density; // return (int) (pxValue / scale + 0.5f); // } // // } // Path: saklib/src/main/java/com/wanjian/sak/layer/impl/MarginLayer.java import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Rect; import android.view.View; import android.view.ViewGroup; import com.wanjian.sak.converter.ISizeConverter; import com.wanjian.sak.layer.ISize; import com.wanjian.sak.utils.ScreenUtils; import java.text.DecimalFormat; } int childCount = ((ViewGroup) view).getChildCount(); for (int i = 0; i < childCount; i++) { canvas.save(); drawMargin(canvas, ((ViewGroup) view).getChildAt(i)); canvas.restore(); } } private void drawMargin(Canvas canvas, View view) { ViewGroup.LayoutParams params = view.getLayoutParams(); if (!(params instanceof ViewGroup.MarginLayoutParams)) { return; }//画 外边距 int w = view.getWidth(); int h = view.getHeight(); ViewGroup.MarginLayoutParams marginLayoutParams = ((ViewGroup.MarginLayoutParams) params); canvas.translate(view.getX(), view.getY()); int l = -marginLayoutParams.leftMargin; int t = -marginLayoutParams.topMargin; int r = w + marginLayoutParams.rightMargin; int b = h + marginLayoutParams.bottomMargin; canvas.drawRect(l, 0, 0, h, mMarginPaint);//left canvas.drawRect(w, 0, r, h, mMarginPaint);//right canvas.drawRect(0, t, w, 0, mMarginPaint); canvas.drawRect(0, h, w, b, mMarginPaint);
ISizeConverter converter = getSizeConverter();
android-notes/SwissArmyKnife
systemlib/src/main/java/android/graphics/RecordingCanvas.java
// Path: systemlib/src/main/java/android/util/Pools.java // public final class Pools { // // /** // * Interface for managing a pool of objects. // * // * @param <T> The pooled type. // */ // public static interface Pool<T> { // // /** // * @return An instance from the pool if such, null otherwise. // */ // public T acquire(); // // /** // * Release an instance to the pool. // * // * @param instance The instance to release. // * @return Whether the instance was put in the pool. // * @throws IllegalStateException If the instance is already in the pool. // */ // public boolean release(T instance); // } // // private Pools() { // /* do nothing - hiding constructor */ // } // // /** // * Simple (non-synchronized) pool of objects. // * // * @param <T> The pooled type. // */ // public static class SimplePool<T> implements Pool<T> { // private final Object[] mPool; // // private int mPoolSize; // // /** // * Creates a new instance. // * // * @param maxPoolSize The max pool size. // * @throws IllegalArgumentException If the max pool size is less than zero. // */ // public SimplePool(int maxPoolSize) { // if (maxPoolSize <= 0) { // throw new IllegalArgumentException("The max pool size must be > 0"); // } // mPool = new Object[maxPoolSize]; // } // // @Override // @SuppressWarnings("unchecked") // public T acquire() { // if (mPoolSize > 0) { // final int lastPooledIndex = mPoolSize - 1; // T instance = (T) mPool[lastPooledIndex]; // mPool[lastPooledIndex] = null; // mPoolSize--; // return instance; // } // return null; // } // // @Override // public boolean release(T instance) { // if (isInPool(instance)) { // throw new IllegalStateException("Already in the pool!"); // } // if (mPoolSize < mPool.length) { // mPool[mPoolSize] = instance; // mPoolSize++; // return true; // } // return false; // } // // private boolean isInPool(T instance) { // for (int i = 0; i < mPoolSize; i++) { // if (mPool[i] == instance) { // return true; // } // } // return false; // } // } // // /** // * Synchronized pool of objects. // * // * @param <T> The pooled type. // */ // public static class SynchronizedPool<T> extends SimplePool<T> { // private final Object mLock; // // /** // * Creates a new instance. // * // * @param maxPoolSize The max pool size. // * @param lock an optional custom object to synchronize on // * @throws IllegalArgumentException If the max pool size is less than zero. // */ // public SynchronizedPool(int maxPoolSize, Object lock) { // super(maxPoolSize); // mLock = lock; // } // // /** // * @see #SynchronizedPool(int, Object) // */ // public SynchronizedPool(int maxPoolSize) { // this(maxPoolSize, new Object()); // } // // @Override // public T acquire() { // synchronized (mLock) { // return super.acquire(); // } // } // // @Override // public boolean release(T element) { // synchronized (mLock) { // return super.release(element); // } // } // } // }
import android.util.Pools;
package android.graphics; public class RecordingCanvas extends Canvas { private static final int POOL_LIMIT = 25;
// Path: systemlib/src/main/java/android/util/Pools.java // public final class Pools { // // /** // * Interface for managing a pool of objects. // * // * @param <T> The pooled type. // */ // public static interface Pool<T> { // // /** // * @return An instance from the pool if such, null otherwise. // */ // public T acquire(); // // /** // * Release an instance to the pool. // * // * @param instance The instance to release. // * @return Whether the instance was put in the pool. // * @throws IllegalStateException If the instance is already in the pool. // */ // public boolean release(T instance); // } // // private Pools() { // /* do nothing - hiding constructor */ // } // // /** // * Simple (non-synchronized) pool of objects. // * // * @param <T> The pooled type. // */ // public static class SimplePool<T> implements Pool<T> { // private final Object[] mPool; // // private int mPoolSize; // // /** // * Creates a new instance. // * // * @param maxPoolSize The max pool size. // * @throws IllegalArgumentException If the max pool size is less than zero. // */ // public SimplePool(int maxPoolSize) { // if (maxPoolSize <= 0) { // throw new IllegalArgumentException("The max pool size must be > 0"); // } // mPool = new Object[maxPoolSize]; // } // // @Override // @SuppressWarnings("unchecked") // public T acquire() { // if (mPoolSize > 0) { // final int lastPooledIndex = mPoolSize - 1; // T instance = (T) mPool[lastPooledIndex]; // mPool[lastPooledIndex] = null; // mPoolSize--; // return instance; // } // return null; // } // // @Override // public boolean release(T instance) { // if (isInPool(instance)) { // throw new IllegalStateException("Already in the pool!"); // } // if (mPoolSize < mPool.length) { // mPool[mPoolSize] = instance; // mPoolSize++; // return true; // } // return false; // } // // private boolean isInPool(T instance) { // for (int i = 0; i < mPoolSize; i++) { // if (mPool[i] == instance) { // return true; // } // } // return false; // } // } // // /** // * Synchronized pool of objects. // * // * @param <T> The pooled type. // */ // public static class SynchronizedPool<T> extends SimplePool<T> { // private final Object mLock; // // /** // * Creates a new instance. // * // * @param maxPoolSize The max pool size. // * @param lock an optional custom object to synchronize on // * @throws IllegalArgumentException If the max pool size is less than zero. // */ // public SynchronizedPool(int maxPoolSize, Object lock) { // super(maxPoolSize); // mLock = lock; // } // // /** // * @see #SynchronizedPool(int, Object) // */ // public SynchronizedPool(int maxPoolSize) { // this(maxPoolSize, new Object()); // } // // @Override // public T acquire() { // synchronized (mLock) { // return super.acquire(); // } // } // // @Override // public boolean release(T element) { // synchronized (mLock) { // return super.release(element); // } // } // } // } // Path: systemlib/src/main/java/android/graphics/RecordingCanvas.java import android.util.Pools; package android.graphics; public class RecordingCanvas extends Canvas { private static final int POOL_LIMIT = 25;
private static final Pools.SynchronizedPool<RecordingCanvas> sPool =
android-notes/SwissArmyKnife
saklib/src/main/java/com/wanjian/sak/layer/impl/GridLayer.java
// Path: saklib/src/main/java/com/wanjian/sak/layer/Layer.java // public abstract class Layer implements EventListener { // private ViewRootImpl viewRootImpl; // private Config config; // private Application application; // private LayerRoot layerRoot; // private RenderNodeCompact renderNode; // private View rootView; // private boolean isEnable; // // public Layer() { // // } // // public RenderNodeCompact getRenderNode() { // return renderNode; // } // // public final void attach(Config config, ViewRootImpl viewRoot, View rootView, Application application, LayerRoot layerRoot) { // this.viewRootImpl = viewRoot; // this.config = config; // this.application = application; // this.layerRoot = layerRoot; // this.rootView = rootView; // renderNode = RenderNodeCompact.create(getClass().getName()); // onAttach(getRootView()); // } // // // // // private final Canvas requireCanvas() { // // return CanvasHolder.requireCanvasFor(viewRootImpl); // // } // // // // private final void releaseCanvas() { // // CanvasHolder.releaseCanvasFor(viewRootImpl); // // } // // protected void invalidate() { // // renderNode.setLeftTopRightBottom(0, 0, getRootView().getWidth(), getRootView().getHeight()); // // DisplayListCanvas displayListCanvas = renderNode.start(getRootView().getWidth(), getRootView().getHeight()); // // onDraw(displayListCanvas); // // renderNode.end(displayListCanvas); // View view = getRootView(); // if (view == null) { // return; // } // Canvas canvas = renderNode.beginRecording(view.getWidth(), view.getHeight()); // draw(canvas); // renderNode.endRecording(canvas); // layerRoot.invalidate(); // } // // private void draw(Canvas canvas) { // if (isEnable == false) { // canvas.drawColor(0); // return; // } // onDraw(canvas); // } // // public final boolean isEnable() { // return isEnable; // } // // public final void enable(boolean enable) { // isEnable = enable; // invalidate(); // onEnableChange(enable); // } // // protected void onEnableChange(boolean enable) { // } // // protected void onDraw(Canvas canvas) { // // } // // @Override // public final void beforeTraversal(View rootView) { // onBeforeTraversal(rootView); // } // // @Override // public final void afterTraversal(View rootView) { // onAfterTraversal(rootView); // } // // @Override // public final boolean beforeInputEvent(View rootView, InputEvent event) { // //rootView.invalidate(); // return onBeforeInputEvent(rootView, event); // } // // @Override // public final void afterInputEvent(View rootView, InputEvent event) { // //rootView.invalidate(); // onAfterInputEvent(rootView, event); // } // // protected View getRootView() { // return rootView; // } // // protected void onBeforeTraversal(View rootView) { // } // // protected void onAfterTraversal(View rootView) { // } // // protected boolean onBeforeInputEvent(View rootView, InputEvent event) { // return false; // } // // protected void onAfterInputEvent(View rootView, InputEvent event) { // } // // protected void onAttach(View rootView) { // // } // // protected Application getContext() { // return application; // } // } // // Path: saklib/src/main/java/com/wanjian/sak/utils/ScreenUtils.java // public class ScreenUtils { // // public static int dp2px(Context context, int dip) { // float density = context.getResources().getDisplayMetrics().density; // return (int) (dip * density + 0.5); // } // // public static int px2dp(Context context, float pxValue) { // final float scale = context.getResources().getDisplayMetrics().density; // return (int) (pxValue / scale + 0.5f); // } // // }
import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.drawable.Drawable; import android.view.View; import com.wanjian.sak.R; import com.wanjian.sak.layer.Layer; import com.wanjian.sak.utils.ScreenUtils;
} @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); int w = getRootView().getWidth(); int h = getRootView().getHeight(); int space = space(); for (int i = space; i < w; i += space) { canvas.drawLine(i, 0, i, h, mPaint); } for (int i = space; i < h; i += space) { canvas.drawLine(0, i, w, i, mPaint); } } @Override protected void onAfterTraversal(View rootView) { invalidate(); } protected int color() { return 0x55000000; } protected int space() {
// Path: saklib/src/main/java/com/wanjian/sak/layer/Layer.java // public abstract class Layer implements EventListener { // private ViewRootImpl viewRootImpl; // private Config config; // private Application application; // private LayerRoot layerRoot; // private RenderNodeCompact renderNode; // private View rootView; // private boolean isEnable; // // public Layer() { // // } // // public RenderNodeCompact getRenderNode() { // return renderNode; // } // // public final void attach(Config config, ViewRootImpl viewRoot, View rootView, Application application, LayerRoot layerRoot) { // this.viewRootImpl = viewRoot; // this.config = config; // this.application = application; // this.layerRoot = layerRoot; // this.rootView = rootView; // renderNode = RenderNodeCompact.create(getClass().getName()); // onAttach(getRootView()); // } // // // // // private final Canvas requireCanvas() { // // return CanvasHolder.requireCanvasFor(viewRootImpl); // // } // // // // private final void releaseCanvas() { // // CanvasHolder.releaseCanvasFor(viewRootImpl); // // } // // protected void invalidate() { // // renderNode.setLeftTopRightBottom(0, 0, getRootView().getWidth(), getRootView().getHeight()); // // DisplayListCanvas displayListCanvas = renderNode.start(getRootView().getWidth(), getRootView().getHeight()); // // onDraw(displayListCanvas); // // renderNode.end(displayListCanvas); // View view = getRootView(); // if (view == null) { // return; // } // Canvas canvas = renderNode.beginRecording(view.getWidth(), view.getHeight()); // draw(canvas); // renderNode.endRecording(canvas); // layerRoot.invalidate(); // } // // private void draw(Canvas canvas) { // if (isEnable == false) { // canvas.drawColor(0); // return; // } // onDraw(canvas); // } // // public final boolean isEnable() { // return isEnable; // } // // public final void enable(boolean enable) { // isEnable = enable; // invalidate(); // onEnableChange(enable); // } // // protected void onEnableChange(boolean enable) { // } // // protected void onDraw(Canvas canvas) { // // } // // @Override // public final void beforeTraversal(View rootView) { // onBeforeTraversal(rootView); // } // // @Override // public final void afterTraversal(View rootView) { // onAfterTraversal(rootView); // } // // @Override // public final boolean beforeInputEvent(View rootView, InputEvent event) { // //rootView.invalidate(); // return onBeforeInputEvent(rootView, event); // } // // @Override // public final void afterInputEvent(View rootView, InputEvent event) { // //rootView.invalidate(); // onAfterInputEvent(rootView, event); // } // // protected View getRootView() { // return rootView; // } // // protected void onBeforeTraversal(View rootView) { // } // // protected void onAfterTraversal(View rootView) { // } // // protected boolean onBeforeInputEvent(View rootView, InputEvent event) { // return false; // } // // protected void onAfterInputEvent(View rootView, InputEvent event) { // } // // protected void onAttach(View rootView) { // // } // // protected Application getContext() { // return application; // } // } // // Path: saklib/src/main/java/com/wanjian/sak/utils/ScreenUtils.java // public class ScreenUtils { // // public static int dp2px(Context context, int dip) { // float density = context.getResources().getDisplayMetrics().density; // return (int) (dip * density + 0.5); // } // // public static int px2dp(Context context, float pxValue) { // final float scale = context.getResources().getDisplayMetrics().density; // return (int) (pxValue / scale + 0.5f); // } // // } // Path: saklib/src/main/java/com/wanjian/sak/layer/impl/GridLayer.java import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.drawable.Drawable; import android.view.View; import com.wanjian.sak.R; import com.wanjian.sak.layer.Layer; import com.wanjian.sak.utils.ScreenUtils; } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); int w = getRootView().getWidth(); int h = getRootView().getHeight(); int space = space(); for (int i = space; i < w; i += space) { canvas.drawLine(i, 0, i, h, mPaint); } for (int i = space; i < h; i += space) { canvas.drawLine(0, i, w, i, mPaint); } } @Override protected void onAfterTraversal(View rootView) { invalidate(); } protected int color() { return 0x55000000; } protected int space() {
return ScreenUtils.dp2px(getContext(), 5);
android-notes/SwissArmyKnife
saklib/src/main/java/com/wanjian/sak/system/canvas/compact/HardwareCanvasV26Impl.java
// Path: systemlib/src/main/java/android/view/ThreadedRenderer.java // public abstract class ThreadedRenderer extends HardwareRenderer { // private int mInsetTop, mInsetLeft; // public void notifyFramePending() {} // } // // Path: systemlib/src/main/java/android/view/ViewRootImpl.java // public final class ViewRootImpl implements ViewParent { // // public View getView() { // return null; // } // // // @Override // public void requestLayout() { // // } // // @Override // public boolean isLayoutRequested() { // return false; // } // // @Override // public void requestTransparentRegion(View child) { // // } // // @Override // public void invalidateChild(View child, Rect r) { // // } // // @Override // public ViewParent invalidateChildInParent(int[] location, Rect r) { // return null; // } // // @Override // public ViewParent getParent() { // return null; // } // // @Override // public void requestChildFocus(View child, View focused) { // // } // // @Override // public void recomputeViewAttributes(View child) { // // } // // @Override // public void clearChildFocus(View child) { // // } // // @Override // public boolean getChildVisibleRect(View child, Rect r, Point offset) { // return false; // } // // @Override // public View focusSearch(View v, int direction) { // return null; // } // // @Override // public View keyboardNavigationClusterSearch(View currentCluster, int direction) { // return null; // } // // @Override // public void bringChildToFront(View child) { // // } // // @Override // public void focusableViewAvailable(View v) { // // } // // @Override // public boolean showContextMenuForChild(View originalView) { // return false; // } // // @Override // public boolean showContextMenuForChild(View originalView, float x, float y) { // return false; // } // // @Override // public void createContextMenu(ContextMenu menu) { // // } // // @Override // public ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback) { // return null; // } // // @Override // public ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback, int type) { // return null; // } // // @Override // public void childDrawableStateChanged(View child) { // // } // // @Override // public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) { // // } // // @Override // public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) { // return false; // } // // @Override // public boolean requestSendAccessibilityEvent(View child, AccessibilityEvent event) { // return false; // } // // @Override // public void childHasTransientStateChanged(View child, boolean hasTransientState) { // // } // // @Override // public void requestFitSystemWindows() { // // } // // @Override // public ViewParent getParentForAccessibility() { // return null; // } // // @Override // public void notifySubtreeAccessibilityStateChanged(View child, View source, int changeType) { // // } // // @Override // public boolean canResolveLayoutDirection() { // return false; // } // // @Override // public boolean isLayoutDirectionResolved() { // return false; // } // // @Override // public int getLayoutDirection() { // return 0; // } // // @Override // public boolean canResolveTextDirection() { // return false; // } // // @Override // public boolean isTextDirectionResolved() { // return false; // } // // @Override // public int getTextDirection() { // return 0; // } // // @Override // public boolean canResolveTextAlignment() { // return false; // } // // @Override // public boolean isTextAlignmentResolved() { // return false; // } // // @Override // public int getTextAlignment() { // return 0; // } // // @Override // public boolean onStartNestedScroll(View child, View target, int nestedScrollAxes) { // return false; // } // // @Override // public void onNestedScrollAccepted(View child, View target, int nestedScrollAxes) { // // } // // @Override // public void onStopNestedScroll(View target) { // // } // // @Override // public void onNestedScroll(View target, int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed) { // // } // // @Override // public void onNestedPreScroll(View target, int dx, int dy, int[] consumed) { // // } // // @Override // public boolean onNestedFling(View target, float velocityX, float velocityY, boolean consumed) { // return false; // } // // @Override // public boolean onNestedPreFling(View target, float velocityX, float velocityY) { // return false; // } // // @Override // public boolean onNestedPrePerformAccessibilityAction(View target, int action, Bundle arguments) { // return false; // } // }
import android.view.ThreadedRenderer; import android.view.View; import android.view.ViewParent; import android.view.ViewRootImpl; import java.lang.reflect.Field;
package com.wanjian.sak.system.canvas.compact; class HardwareCanvasV26Impl extends HardwareCanvasV24Impl { HardwareCanvasV26Impl(ViewRootImpl viewRootImpl) { super(viewRootImpl); }
// Path: systemlib/src/main/java/android/view/ThreadedRenderer.java // public abstract class ThreadedRenderer extends HardwareRenderer { // private int mInsetTop, mInsetLeft; // public void notifyFramePending() {} // } // // Path: systemlib/src/main/java/android/view/ViewRootImpl.java // public final class ViewRootImpl implements ViewParent { // // public View getView() { // return null; // } // // // @Override // public void requestLayout() { // // } // // @Override // public boolean isLayoutRequested() { // return false; // } // // @Override // public void requestTransparentRegion(View child) { // // } // // @Override // public void invalidateChild(View child, Rect r) { // // } // // @Override // public ViewParent invalidateChildInParent(int[] location, Rect r) { // return null; // } // // @Override // public ViewParent getParent() { // return null; // } // // @Override // public void requestChildFocus(View child, View focused) { // // } // // @Override // public void recomputeViewAttributes(View child) { // // } // // @Override // public void clearChildFocus(View child) { // // } // // @Override // public boolean getChildVisibleRect(View child, Rect r, Point offset) { // return false; // } // // @Override // public View focusSearch(View v, int direction) { // return null; // } // // @Override // public View keyboardNavigationClusterSearch(View currentCluster, int direction) { // return null; // } // // @Override // public void bringChildToFront(View child) { // // } // // @Override // public void focusableViewAvailable(View v) { // // } // // @Override // public boolean showContextMenuForChild(View originalView) { // return false; // } // // @Override // public boolean showContextMenuForChild(View originalView, float x, float y) { // return false; // } // // @Override // public void createContextMenu(ContextMenu menu) { // // } // // @Override // public ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback) { // return null; // } // // @Override // public ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback, int type) { // return null; // } // // @Override // public void childDrawableStateChanged(View child) { // // } // // @Override // public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) { // // } // // @Override // public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) { // return false; // } // // @Override // public boolean requestSendAccessibilityEvent(View child, AccessibilityEvent event) { // return false; // } // // @Override // public void childHasTransientStateChanged(View child, boolean hasTransientState) { // // } // // @Override // public void requestFitSystemWindows() { // // } // // @Override // public ViewParent getParentForAccessibility() { // return null; // } // // @Override // public void notifySubtreeAccessibilityStateChanged(View child, View source, int changeType) { // // } // // @Override // public boolean canResolveLayoutDirection() { // return false; // } // // @Override // public boolean isLayoutDirectionResolved() { // return false; // } // // @Override // public int getLayoutDirection() { // return 0; // } // // @Override // public boolean canResolveTextDirection() { // return false; // } // // @Override // public boolean isTextDirectionResolved() { // return false; // } // // @Override // public int getTextDirection() { // return 0; // } // // @Override // public boolean canResolveTextAlignment() { // return false; // } // // @Override // public boolean isTextAlignmentResolved() { // return false; // } // // @Override // public int getTextAlignment() { // return 0; // } // // @Override // public boolean onStartNestedScroll(View child, View target, int nestedScrollAxes) { // return false; // } // // @Override // public void onNestedScrollAccepted(View child, View target, int nestedScrollAxes) { // // } // // @Override // public void onStopNestedScroll(View target) { // // } // // @Override // public void onNestedScroll(View target, int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed) { // // } // // @Override // public void onNestedPreScroll(View target, int dx, int dy, int[] consumed) { // // } // // @Override // public boolean onNestedFling(View target, float velocityX, float velocityY, boolean consumed) { // return false; // } // // @Override // public boolean onNestedPreFling(View target, float velocityX, float velocityY) { // return false; // } // // @Override // public boolean onNestedPrePerformAccessibilityAction(View target, int action, Bundle arguments) { // return false; // } // } // Path: saklib/src/main/java/com/wanjian/sak/system/canvas/compact/HardwareCanvasV26Impl.java import android.view.ThreadedRenderer; import android.view.View; import android.view.ViewParent; import android.view.ViewRootImpl; import java.lang.reflect.Field; package com.wanjian.sak.system.canvas.compact; class HardwareCanvasV26Impl extends HardwareCanvasV24Impl { HardwareCanvasV26Impl(ViewRootImpl viewRootImpl) { super(viewRootImpl); }
protected ThreadedRenderer getHardwareRenderer(ViewRootImpl viewRootImpl) {
android-notes/SwissArmyKnife
saklib/src/main/java/com/wanjian/sak/layer/impl/TakeColorLayer.java
// Path: saklib/src/main/java/com/wanjian/sak/layer/Layer.java // public abstract class Layer implements EventListener { // private ViewRootImpl viewRootImpl; // private Config config; // private Application application; // private LayerRoot layerRoot; // private RenderNodeCompact renderNode; // private View rootView; // private boolean isEnable; // // public Layer() { // // } // // public RenderNodeCompact getRenderNode() { // return renderNode; // } // // public final void attach(Config config, ViewRootImpl viewRoot, View rootView, Application application, LayerRoot layerRoot) { // this.viewRootImpl = viewRoot; // this.config = config; // this.application = application; // this.layerRoot = layerRoot; // this.rootView = rootView; // renderNode = RenderNodeCompact.create(getClass().getName()); // onAttach(getRootView()); // } // // // // // private final Canvas requireCanvas() { // // return CanvasHolder.requireCanvasFor(viewRootImpl); // // } // // // // private final void releaseCanvas() { // // CanvasHolder.releaseCanvasFor(viewRootImpl); // // } // // protected void invalidate() { // // renderNode.setLeftTopRightBottom(0, 0, getRootView().getWidth(), getRootView().getHeight()); // // DisplayListCanvas displayListCanvas = renderNode.start(getRootView().getWidth(), getRootView().getHeight()); // // onDraw(displayListCanvas); // // renderNode.end(displayListCanvas); // View view = getRootView(); // if (view == null) { // return; // } // Canvas canvas = renderNode.beginRecording(view.getWidth(), view.getHeight()); // draw(canvas); // renderNode.endRecording(canvas); // layerRoot.invalidate(); // } // // private void draw(Canvas canvas) { // if (isEnable == false) { // canvas.drawColor(0); // return; // } // onDraw(canvas); // } // // public final boolean isEnable() { // return isEnable; // } // // public final void enable(boolean enable) { // isEnable = enable; // invalidate(); // onEnableChange(enable); // } // // protected void onEnableChange(boolean enable) { // } // // protected void onDraw(Canvas canvas) { // // } // // @Override // public final void beforeTraversal(View rootView) { // onBeforeTraversal(rootView); // } // // @Override // public final void afterTraversal(View rootView) { // onAfterTraversal(rootView); // } // // @Override // public final boolean beforeInputEvent(View rootView, InputEvent event) { // //rootView.invalidate(); // return onBeforeInputEvent(rootView, event); // } // // @Override // public final void afterInputEvent(View rootView, InputEvent event) { // //rootView.invalidate(); // onAfterInputEvent(rootView, event); // } // // protected View getRootView() { // return rootView; // } // // protected void onBeforeTraversal(View rootView) { // } // // protected void onAfterTraversal(View rootView) { // } // // protected boolean onBeforeInputEvent(View rootView, InputEvent event) { // return false; // } // // protected void onAfterInputEvent(View rootView, InputEvent event) { // } // // protected void onAttach(View rootView) { // // } // // protected Application getContext() { // return application; // } // } // // Path: saklib/src/main/java/com/wanjian/sak/utils/BitmapCreater.java // public class BitmapCreater { // public static Bitmap create(int w, int h, Bitmap.Config config) { // // Check.isNull(config, "config"); // if (w <= 0) { // new IllegalArgumentException("w can not be <= 0").printStackTrace(); // return null; // } // if (h <= 0) { // new IllegalArgumentException("h can not be <= 0").printStackTrace(); // return null; // } // for (int i = 0; i < 3; i++) { // try { // return Bitmap.createBitmap(w, h, config); // } catch (Throwable e) { // Runtime.getRuntime().gc(); // } // } // return null; // } // } // // Path: saklib/src/main/java/com/wanjian/sak/utils/ScreenUtils.java // public class ScreenUtils { // // public static int dp2px(Context context, int dip) { // float density = context.getResources().getDisplayMetrics().density; // return (int) (dip * density + 0.5); // } // // public static int px2dp(Context context, float pxValue) { // final float scale = context.getResources().getDisplayMetrics().density; // return (int) (pxValue / scale + 0.5f); // } // // }
import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Path; import android.graphics.Rect; import android.view.InputEvent; import android.view.MotionEvent; import android.view.View; import com.wanjian.sak.layer.Layer; import com.wanjian.sak.utils.BitmapCreater; import com.wanjian.sak.utils.ScreenUtils;
package com.wanjian.sak.layer.impl; public class TakeColorLayer extends Layer { private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); private Paint txtPaint = new Paint(Paint.ANTI_ALIAS_FLAG); private int x; private int y; private int r; private boolean consume; private float lastX, lastY; private Bitmap bitmap; private int strokeWidth; private Path path; private Matrix matrix = new Matrix(); private Rect mRect = new Rect(); @Override protected void onAttach(View rootView) { super.onAttach(rootView); x = getRootView().getWidth() / 2; y = getRootView().getHeight() / 2;
// Path: saklib/src/main/java/com/wanjian/sak/layer/Layer.java // public abstract class Layer implements EventListener { // private ViewRootImpl viewRootImpl; // private Config config; // private Application application; // private LayerRoot layerRoot; // private RenderNodeCompact renderNode; // private View rootView; // private boolean isEnable; // // public Layer() { // // } // // public RenderNodeCompact getRenderNode() { // return renderNode; // } // // public final void attach(Config config, ViewRootImpl viewRoot, View rootView, Application application, LayerRoot layerRoot) { // this.viewRootImpl = viewRoot; // this.config = config; // this.application = application; // this.layerRoot = layerRoot; // this.rootView = rootView; // renderNode = RenderNodeCompact.create(getClass().getName()); // onAttach(getRootView()); // } // // // // // private final Canvas requireCanvas() { // // return CanvasHolder.requireCanvasFor(viewRootImpl); // // } // // // // private final void releaseCanvas() { // // CanvasHolder.releaseCanvasFor(viewRootImpl); // // } // // protected void invalidate() { // // renderNode.setLeftTopRightBottom(0, 0, getRootView().getWidth(), getRootView().getHeight()); // // DisplayListCanvas displayListCanvas = renderNode.start(getRootView().getWidth(), getRootView().getHeight()); // // onDraw(displayListCanvas); // // renderNode.end(displayListCanvas); // View view = getRootView(); // if (view == null) { // return; // } // Canvas canvas = renderNode.beginRecording(view.getWidth(), view.getHeight()); // draw(canvas); // renderNode.endRecording(canvas); // layerRoot.invalidate(); // } // // private void draw(Canvas canvas) { // if (isEnable == false) { // canvas.drawColor(0); // return; // } // onDraw(canvas); // } // // public final boolean isEnable() { // return isEnable; // } // // public final void enable(boolean enable) { // isEnable = enable; // invalidate(); // onEnableChange(enable); // } // // protected void onEnableChange(boolean enable) { // } // // protected void onDraw(Canvas canvas) { // // } // // @Override // public final void beforeTraversal(View rootView) { // onBeforeTraversal(rootView); // } // // @Override // public final void afterTraversal(View rootView) { // onAfterTraversal(rootView); // } // // @Override // public final boolean beforeInputEvent(View rootView, InputEvent event) { // //rootView.invalidate(); // return onBeforeInputEvent(rootView, event); // } // // @Override // public final void afterInputEvent(View rootView, InputEvent event) { // //rootView.invalidate(); // onAfterInputEvent(rootView, event); // } // // protected View getRootView() { // return rootView; // } // // protected void onBeforeTraversal(View rootView) { // } // // protected void onAfterTraversal(View rootView) { // } // // protected boolean onBeforeInputEvent(View rootView, InputEvent event) { // return false; // } // // protected void onAfterInputEvent(View rootView, InputEvent event) { // } // // protected void onAttach(View rootView) { // // } // // protected Application getContext() { // return application; // } // } // // Path: saklib/src/main/java/com/wanjian/sak/utils/BitmapCreater.java // public class BitmapCreater { // public static Bitmap create(int w, int h, Bitmap.Config config) { // // Check.isNull(config, "config"); // if (w <= 0) { // new IllegalArgumentException("w can not be <= 0").printStackTrace(); // return null; // } // if (h <= 0) { // new IllegalArgumentException("h can not be <= 0").printStackTrace(); // return null; // } // for (int i = 0; i < 3; i++) { // try { // return Bitmap.createBitmap(w, h, config); // } catch (Throwable e) { // Runtime.getRuntime().gc(); // } // } // return null; // } // } // // Path: saklib/src/main/java/com/wanjian/sak/utils/ScreenUtils.java // public class ScreenUtils { // // public static int dp2px(Context context, int dip) { // float density = context.getResources().getDisplayMetrics().density; // return (int) (dip * density + 0.5); // } // // public static int px2dp(Context context, float pxValue) { // final float scale = context.getResources().getDisplayMetrics().density; // return (int) (pxValue / scale + 0.5f); // } // // } // Path: saklib/src/main/java/com/wanjian/sak/layer/impl/TakeColorLayer.java import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Path; import android.graphics.Rect; import android.view.InputEvent; import android.view.MotionEvent; import android.view.View; import com.wanjian.sak.layer.Layer; import com.wanjian.sak.utils.BitmapCreater; import com.wanjian.sak.utils.ScreenUtils; package com.wanjian.sak.layer.impl; public class TakeColorLayer extends Layer { private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); private Paint txtPaint = new Paint(Paint.ANTI_ALIAS_FLAG); private int x; private int y; private int r; private boolean consume; private float lastX, lastY; private Bitmap bitmap; private int strokeWidth; private Path path; private Matrix matrix = new Matrix(); private Rect mRect = new Rect(); @Override protected void onAttach(View rootView) { super.onAttach(rootView); x = getRootView().getWidth() / 2; y = getRootView().getHeight() / 2;
r = ScreenUtils.dp2px(getContext(), 60);
android-notes/SwissArmyKnife
saklib/src/main/java/com/wanjian/sak/layer/impl/TakeColorLayer.java
// Path: saklib/src/main/java/com/wanjian/sak/layer/Layer.java // public abstract class Layer implements EventListener { // private ViewRootImpl viewRootImpl; // private Config config; // private Application application; // private LayerRoot layerRoot; // private RenderNodeCompact renderNode; // private View rootView; // private boolean isEnable; // // public Layer() { // // } // // public RenderNodeCompact getRenderNode() { // return renderNode; // } // // public final void attach(Config config, ViewRootImpl viewRoot, View rootView, Application application, LayerRoot layerRoot) { // this.viewRootImpl = viewRoot; // this.config = config; // this.application = application; // this.layerRoot = layerRoot; // this.rootView = rootView; // renderNode = RenderNodeCompact.create(getClass().getName()); // onAttach(getRootView()); // } // // // // // private final Canvas requireCanvas() { // // return CanvasHolder.requireCanvasFor(viewRootImpl); // // } // // // // private final void releaseCanvas() { // // CanvasHolder.releaseCanvasFor(viewRootImpl); // // } // // protected void invalidate() { // // renderNode.setLeftTopRightBottom(0, 0, getRootView().getWidth(), getRootView().getHeight()); // // DisplayListCanvas displayListCanvas = renderNode.start(getRootView().getWidth(), getRootView().getHeight()); // // onDraw(displayListCanvas); // // renderNode.end(displayListCanvas); // View view = getRootView(); // if (view == null) { // return; // } // Canvas canvas = renderNode.beginRecording(view.getWidth(), view.getHeight()); // draw(canvas); // renderNode.endRecording(canvas); // layerRoot.invalidate(); // } // // private void draw(Canvas canvas) { // if (isEnable == false) { // canvas.drawColor(0); // return; // } // onDraw(canvas); // } // // public final boolean isEnable() { // return isEnable; // } // // public final void enable(boolean enable) { // isEnable = enable; // invalidate(); // onEnableChange(enable); // } // // protected void onEnableChange(boolean enable) { // } // // protected void onDraw(Canvas canvas) { // // } // // @Override // public final void beforeTraversal(View rootView) { // onBeforeTraversal(rootView); // } // // @Override // public final void afterTraversal(View rootView) { // onAfterTraversal(rootView); // } // // @Override // public final boolean beforeInputEvent(View rootView, InputEvent event) { // //rootView.invalidate(); // return onBeforeInputEvent(rootView, event); // } // // @Override // public final void afterInputEvent(View rootView, InputEvent event) { // //rootView.invalidate(); // onAfterInputEvent(rootView, event); // } // // protected View getRootView() { // return rootView; // } // // protected void onBeforeTraversal(View rootView) { // } // // protected void onAfterTraversal(View rootView) { // } // // protected boolean onBeforeInputEvent(View rootView, InputEvent event) { // return false; // } // // protected void onAfterInputEvent(View rootView, InputEvent event) { // } // // protected void onAttach(View rootView) { // // } // // protected Application getContext() { // return application; // } // } // // Path: saklib/src/main/java/com/wanjian/sak/utils/BitmapCreater.java // public class BitmapCreater { // public static Bitmap create(int w, int h, Bitmap.Config config) { // // Check.isNull(config, "config"); // if (w <= 0) { // new IllegalArgumentException("w can not be <= 0").printStackTrace(); // return null; // } // if (h <= 0) { // new IllegalArgumentException("h can not be <= 0").printStackTrace(); // return null; // } // for (int i = 0; i < 3; i++) { // try { // return Bitmap.createBitmap(w, h, config); // } catch (Throwable e) { // Runtime.getRuntime().gc(); // } // } // return null; // } // } // // Path: saklib/src/main/java/com/wanjian/sak/utils/ScreenUtils.java // public class ScreenUtils { // // public static int dp2px(Context context, int dip) { // float density = context.getResources().getDisplayMetrics().density; // return (int) (dip * density + 0.5); // } // // public static int px2dp(Context context, float pxValue) { // final float scale = context.getResources().getDisplayMetrics().density; // return (int) (pxValue / scale + 0.5f); // } // // }
import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Path; import android.graphics.Rect; import android.view.InputEvent; import android.view.MotionEvent; import android.view.View; import com.wanjian.sak.layer.Layer; import com.wanjian.sak.utils.BitmapCreater; import com.wanjian.sak.utils.ScreenUtils;
lastY = motionEvent.getY(); if (contains(lastX, lastY)) { consume = true; } else { consume = false; } } if (consume == false) { return false; } float curX = motionEvent.getX(); float curY = motionEvent.getY(); int dx = (int) (curX - lastX); int dy = (int) (curY - lastY); x += dx; y += dy; drawBitmap(); invalidate(); lastX = curX; lastY = curY; return true; } private void drawBitmap() { View rootView = getRootView(); int w = rootView.getWidth(); int h = rootView.getHeight(); if (bitmap == null || bitmap.getWidth() < w || bitmap.getHeight() < h) {
// Path: saklib/src/main/java/com/wanjian/sak/layer/Layer.java // public abstract class Layer implements EventListener { // private ViewRootImpl viewRootImpl; // private Config config; // private Application application; // private LayerRoot layerRoot; // private RenderNodeCompact renderNode; // private View rootView; // private boolean isEnable; // // public Layer() { // // } // // public RenderNodeCompact getRenderNode() { // return renderNode; // } // // public final void attach(Config config, ViewRootImpl viewRoot, View rootView, Application application, LayerRoot layerRoot) { // this.viewRootImpl = viewRoot; // this.config = config; // this.application = application; // this.layerRoot = layerRoot; // this.rootView = rootView; // renderNode = RenderNodeCompact.create(getClass().getName()); // onAttach(getRootView()); // } // // // // // private final Canvas requireCanvas() { // // return CanvasHolder.requireCanvasFor(viewRootImpl); // // } // // // // private final void releaseCanvas() { // // CanvasHolder.releaseCanvasFor(viewRootImpl); // // } // // protected void invalidate() { // // renderNode.setLeftTopRightBottom(0, 0, getRootView().getWidth(), getRootView().getHeight()); // // DisplayListCanvas displayListCanvas = renderNode.start(getRootView().getWidth(), getRootView().getHeight()); // // onDraw(displayListCanvas); // // renderNode.end(displayListCanvas); // View view = getRootView(); // if (view == null) { // return; // } // Canvas canvas = renderNode.beginRecording(view.getWidth(), view.getHeight()); // draw(canvas); // renderNode.endRecording(canvas); // layerRoot.invalidate(); // } // // private void draw(Canvas canvas) { // if (isEnable == false) { // canvas.drawColor(0); // return; // } // onDraw(canvas); // } // // public final boolean isEnable() { // return isEnable; // } // // public final void enable(boolean enable) { // isEnable = enable; // invalidate(); // onEnableChange(enable); // } // // protected void onEnableChange(boolean enable) { // } // // protected void onDraw(Canvas canvas) { // // } // // @Override // public final void beforeTraversal(View rootView) { // onBeforeTraversal(rootView); // } // // @Override // public final void afterTraversal(View rootView) { // onAfterTraversal(rootView); // } // // @Override // public final boolean beforeInputEvent(View rootView, InputEvent event) { // //rootView.invalidate(); // return onBeforeInputEvent(rootView, event); // } // // @Override // public final void afterInputEvent(View rootView, InputEvent event) { // //rootView.invalidate(); // onAfterInputEvent(rootView, event); // } // // protected View getRootView() { // return rootView; // } // // protected void onBeforeTraversal(View rootView) { // } // // protected void onAfterTraversal(View rootView) { // } // // protected boolean onBeforeInputEvent(View rootView, InputEvent event) { // return false; // } // // protected void onAfterInputEvent(View rootView, InputEvent event) { // } // // protected void onAttach(View rootView) { // // } // // protected Application getContext() { // return application; // } // } // // Path: saklib/src/main/java/com/wanjian/sak/utils/BitmapCreater.java // public class BitmapCreater { // public static Bitmap create(int w, int h, Bitmap.Config config) { // // Check.isNull(config, "config"); // if (w <= 0) { // new IllegalArgumentException("w can not be <= 0").printStackTrace(); // return null; // } // if (h <= 0) { // new IllegalArgumentException("h can not be <= 0").printStackTrace(); // return null; // } // for (int i = 0; i < 3; i++) { // try { // return Bitmap.createBitmap(w, h, config); // } catch (Throwable e) { // Runtime.getRuntime().gc(); // } // } // return null; // } // } // // Path: saklib/src/main/java/com/wanjian/sak/utils/ScreenUtils.java // public class ScreenUtils { // // public static int dp2px(Context context, int dip) { // float density = context.getResources().getDisplayMetrics().density; // return (int) (dip * density + 0.5); // } // // public static int px2dp(Context context, float pxValue) { // final float scale = context.getResources().getDisplayMetrics().density; // return (int) (pxValue / scale + 0.5f); // } // // } // Path: saklib/src/main/java/com/wanjian/sak/layer/impl/TakeColorLayer.java import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Path; import android.graphics.Rect; import android.view.InputEvent; import android.view.MotionEvent; import android.view.View; import com.wanjian.sak.layer.Layer; import com.wanjian.sak.utils.BitmapCreater; import com.wanjian.sak.utils.ScreenUtils; lastY = motionEvent.getY(); if (contains(lastX, lastY)) { consume = true; } else { consume = false; } } if (consume == false) { return false; } float curX = motionEvent.getX(); float curY = motionEvent.getY(); int dx = (int) (curX - lastX); int dy = (int) (curY - lastY); x += dx; y += dy; drawBitmap(); invalidate(); lastX = curX; lastY = curY; return true; } private void drawBitmap() { View rootView = getRootView(); int w = rootView.getWidth(); int h = rootView.getHeight(); if (bitmap == null || bitmap.getWidth() < w || bitmap.getHeight() < h) {
bitmap = BitmapCreater.create(w, h, Bitmap.Config.ARGB_8888);
android-notes/SwissArmyKnife
saklib/src/main/java/com/wanjian/sak/layer/impl/TextSizeLayer.java
// Path: sak-nop/src/main/java/com/wanjian/sak/converter/ISizeConverter.java // public abstract class ISizeConverter { // public static ISizeConverter CONVERTER; // // public abstract String desc(); // // public abstract Size convert(Context context, float length); // // public abstract int recovery(Context context, float length); // // } // // Path: saklib/src/main/java/com/wanjian/sak/layer/ISize.java // public interface ISize { // void onSizeConvertChange(ISizeConverter converter); // }
import android.graphics.drawable.Drawable; import android.view.View; import android.widget.TextView; import com.wanjian.sak.R; import com.wanjian.sak.converter.ISizeConverter; import com.wanjian.sak.layer.ISize;
package com.wanjian.sak.layer.impl; /** * Created by wanjian on 2016/10/26. */ public class TextSizeLayer extends LayerTxtAdapter implements ISize { @Override protected String getTxt(View view) { if (view instanceof TextView) { float size = ((TextView) view).getTextSize(); return String.valueOf(getSizeConverter().convert(getContext(), size).getLength()); } return ""; }
// Path: sak-nop/src/main/java/com/wanjian/sak/converter/ISizeConverter.java // public abstract class ISizeConverter { // public static ISizeConverter CONVERTER; // // public abstract String desc(); // // public abstract Size convert(Context context, float length); // // public abstract int recovery(Context context, float length); // // } // // Path: saklib/src/main/java/com/wanjian/sak/layer/ISize.java // public interface ISize { // void onSizeConvertChange(ISizeConverter converter); // } // Path: saklib/src/main/java/com/wanjian/sak/layer/impl/TextSizeLayer.java import android.graphics.drawable.Drawable; import android.view.View; import android.widget.TextView; import com.wanjian.sak.R; import com.wanjian.sak.converter.ISizeConverter; import com.wanjian.sak.layer.ISize; package com.wanjian.sak.layer.impl; /** * Created by wanjian on 2016/10/26. */ public class TextSizeLayer extends LayerTxtAdapter implements ISize { @Override protected String getTxt(View view) { if (view instanceof TextView) { float size = ((TextView) view).getTextSize(); return String.valueOf(getSizeConverter().convert(getContext(), size).getLength()); } return ""; }
private ISizeConverter getSizeConverter() {
android-notes/SwissArmyKnife
saklib/src/main/java/com/wanjian/sak/support/FPSView.java
// Path: saklib/src/main/java/com/wanjian/sak/utils/LoopQueue.java // public class LoopQueue<T> { // private int size; // private LinkedList<T> queue; // private int cursor; // // public LoopQueue(int size) { // if (size < 1) { // throw new IllegalArgumentException(); // } // this.size = size; // queue = new LinkedList<T>(); // } // // public T take() { // if (has() == false) { // throw new IllegalStateException("end!"); // } // return queue.get(cursor++); // } // // public void append(T t) { // if (queue.size() == size) { // queue.remove(0); // cursor--; // if (cursor < 0) { // cursor = 0; // } // } // queue.add(t); // } // // public boolean has() { // return cursor != queue.size(); // } // // public int maxSize() { // return size; // } // // public int size() { // return queue.size(); // } // // public void reset() { // cursor = 0; // } // // public void clean() { // cursor = 0; // queue.clear(); // } // }
import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.view.View; import com.wanjian.sak.utils.LoopQueue;
package com.wanjian.sak.support; public class FPSView extends View { private Paint paint; private float density; private Path path = new Path();
// Path: saklib/src/main/java/com/wanjian/sak/utils/LoopQueue.java // public class LoopQueue<T> { // private int size; // private LinkedList<T> queue; // private int cursor; // // public LoopQueue(int size) { // if (size < 1) { // throw new IllegalArgumentException(); // } // this.size = size; // queue = new LinkedList<T>(); // } // // public T take() { // if (has() == false) { // throw new IllegalStateException("end!"); // } // return queue.get(cursor++); // } // // public void append(T t) { // if (queue.size() == size) { // queue.remove(0); // cursor--; // if (cursor < 0) { // cursor = 0; // } // } // queue.add(t); // } // // public boolean has() { // return cursor != queue.size(); // } // // public int maxSize() { // return size; // } // // public int size() { // return queue.size(); // } // // public void reset() { // cursor = 0; // } // // public void clean() { // cursor = 0; // queue.clear(); // } // } // Path: saklib/src/main/java/com/wanjian/sak/support/FPSView.java import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.view.View; import com.wanjian.sak.utils.LoopQueue; package com.wanjian.sak.support; public class FPSView extends View { private Paint paint; private float density; private Path path = new Path();
private LoopQueue<Long> data;
android-notes/SwissArmyKnife
saklib/src/main/java/com/wanjian/sak/layer/impl/WidthHeightLayer.java
// Path: sak-nop/src/main/java/com/wanjian/sak/converter/ISizeConverter.java // public abstract class ISizeConverter { // public static ISizeConverter CONVERTER; // // public abstract String desc(); // // public abstract Size convert(Context context, float length); // // public abstract int recovery(Context context, float length); // // } // // Path: saklib/src/main/java/com/wanjian/sak/layer/ISize.java // public interface ISize { // void onSizeConvertChange(ISizeConverter converter); // }
import android.graphics.drawable.Drawable; import android.view.View; import com.wanjian.sak.R; import com.wanjian.sak.converter.ISizeConverter; import com.wanjian.sak.layer.ISize;
package com.wanjian.sak.layer.impl; /** * */ public class WidthHeightLayer extends LayerTxtAdapter implements ISize { @Override protected String getTxt(View view) { int w = view.getWidth(); int h = view.getHeight();
// Path: sak-nop/src/main/java/com/wanjian/sak/converter/ISizeConverter.java // public abstract class ISizeConverter { // public static ISizeConverter CONVERTER; // // public abstract String desc(); // // public abstract Size convert(Context context, float length); // // public abstract int recovery(Context context, float length); // // } // // Path: saklib/src/main/java/com/wanjian/sak/layer/ISize.java // public interface ISize { // void onSizeConvertChange(ISizeConverter converter); // } // Path: saklib/src/main/java/com/wanjian/sak/layer/impl/WidthHeightLayer.java import android.graphics.drawable.Drawable; import android.view.View; import com.wanjian.sak.R; import com.wanjian.sak.converter.ISizeConverter; import com.wanjian.sak.layer.ISize; package com.wanjian.sak.layer.impl; /** * */ public class WidthHeightLayer extends LayerTxtAdapter implements ISize { @Override protected String getTxt(View view) { int w = view.getWidth(); int h = view.getHeight();
ISizeConverter converter = getSizeConverter();
android-notes/SwissArmyKnife
saklib/src/main/java/com/wanjian/sak/system/rendernode/RenderNodeV23Impl.java
// Path: systemlib/src/main/java/android/view/DisplayListCanvas.java // public class DisplayListCanvas extends Canvas { // // private static final int POOL_LIMIT = 25; // //android 6.0,7.0,7.1,8.0,8.1,9.0 // private static final Pools.SynchronizedPool<DisplayListCanvas> sPool = // new Pools.SynchronizedPool<DisplayListCanvas>(POOL_LIMIT); // // public void onPreDraw(Rect dirty) { // } // // public void insertReorderBarrier() { // } // // public void insertInorderBarrier() { // } // // public void drawRenderNode(RenderNode renderNode) { // } // } // // Path: systemlib/src/main/java/android/view/HardwareCanvas.java // public class HardwareCanvas extends Canvas { // // public void insertReorderBarrier() { // } // // public void insertInorderBarrier() { // } // // public void drawRenderNode(RenderNode renderNode) { // } // } // // Path: systemlib/src/main/java/android/view/RenderNode.java // public class RenderNode { // public DisplayListCanvas start(int width, int height) { // return null; // } // // // public HardwareCanvas start(int width, int height,Object...obj) { // // return null; // // } // // private RenderNode() { // } // // public static RenderNode create(String name, View owningView) { // return null; // } // // public void end(HardwareCanvas canvas) { // } // // // public void end(DisplayListCanvas canvas) { // } // // public boolean setAlpha(float alpha) { // return false; // } // // // public boolean setLeftTopRightBottom(int left, int top, int right, int bottom){ // return false; // } // // public boolean setOutline( Outline outline) { // return false; // } // // public boolean setHasOverlappingRendering(boolean hasOverlappingRendering) { // return false; // } // // public boolean setClipToBounds(boolean clipToBounds) { // return false; // } // public boolean isValid() { // return false; // } // // } // // Path: systemlib/src/main/java/android/view/ThreadedRenderer.java // public abstract class ThreadedRenderer extends HardwareRenderer { // private int mInsetTop, mInsetLeft; // public void notifyFramePending() {} // }
import android.graphics.Canvas; import android.view.DisplayListCanvas; import android.view.HardwareCanvas; import android.view.RenderNode; import android.view.ThreadedRenderer; import java.lang.reflect.Method;
package com.wanjian.sak.system.rendernode; public class RenderNodeV23Impl extends RenderNodeCompact { private RenderNode renderNode; public RenderNodeV23Impl(String name) { renderNode = RenderNode.create(name, null); } @Override public void drawRenderNode(Canvas canvas) {
// Path: systemlib/src/main/java/android/view/DisplayListCanvas.java // public class DisplayListCanvas extends Canvas { // // private static final int POOL_LIMIT = 25; // //android 6.0,7.0,7.1,8.0,8.1,9.0 // private static final Pools.SynchronizedPool<DisplayListCanvas> sPool = // new Pools.SynchronizedPool<DisplayListCanvas>(POOL_LIMIT); // // public void onPreDraw(Rect dirty) { // } // // public void insertReorderBarrier() { // } // // public void insertInorderBarrier() { // } // // public void drawRenderNode(RenderNode renderNode) { // } // } // // Path: systemlib/src/main/java/android/view/HardwareCanvas.java // public class HardwareCanvas extends Canvas { // // public void insertReorderBarrier() { // } // // public void insertInorderBarrier() { // } // // public void drawRenderNode(RenderNode renderNode) { // } // } // // Path: systemlib/src/main/java/android/view/RenderNode.java // public class RenderNode { // public DisplayListCanvas start(int width, int height) { // return null; // } // // // public HardwareCanvas start(int width, int height,Object...obj) { // // return null; // // } // // private RenderNode() { // } // // public static RenderNode create(String name, View owningView) { // return null; // } // // public void end(HardwareCanvas canvas) { // } // // // public void end(DisplayListCanvas canvas) { // } // // public boolean setAlpha(float alpha) { // return false; // } // // // public boolean setLeftTopRightBottom(int left, int top, int right, int bottom){ // return false; // } // // public boolean setOutline( Outline outline) { // return false; // } // // public boolean setHasOverlappingRendering(boolean hasOverlappingRendering) { // return false; // } // // public boolean setClipToBounds(boolean clipToBounds) { // return false; // } // public boolean isValid() { // return false; // } // // } // // Path: systemlib/src/main/java/android/view/ThreadedRenderer.java // public abstract class ThreadedRenderer extends HardwareRenderer { // private int mInsetTop, mInsetLeft; // public void notifyFramePending() {} // } // Path: saklib/src/main/java/com/wanjian/sak/system/rendernode/RenderNodeV23Impl.java import android.graphics.Canvas; import android.view.DisplayListCanvas; import android.view.HardwareCanvas; import android.view.RenderNode; import android.view.ThreadedRenderer; import java.lang.reflect.Method; package com.wanjian.sak.system.rendernode; public class RenderNodeV23Impl extends RenderNodeCompact { private RenderNode renderNode; public RenderNodeV23Impl(String name) { renderNode = RenderNode.create(name, null); } @Override public void drawRenderNode(Canvas canvas) {
((DisplayListCanvas) canvas).drawRenderNode(renderNode);
android-notes/SwissArmyKnife
systemlib/src/main/java/android/view/DisplayListCanvas.java
// Path: systemlib/src/main/java/android/util/Pools.java // public final class Pools { // // /** // * Interface for managing a pool of objects. // * // * @param <T> The pooled type. // */ // public static interface Pool<T> { // // /** // * @return An instance from the pool if such, null otherwise. // */ // public T acquire(); // // /** // * Release an instance to the pool. // * // * @param instance The instance to release. // * @return Whether the instance was put in the pool. // * @throws IllegalStateException If the instance is already in the pool. // */ // public boolean release(T instance); // } // // private Pools() { // /* do nothing - hiding constructor */ // } // // /** // * Simple (non-synchronized) pool of objects. // * // * @param <T> The pooled type. // */ // public static class SimplePool<T> implements Pool<T> { // private final Object[] mPool; // // private int mPoolSize; // // /** // * Creates a new instance. // * // * @param maxPoolSize The max pool size. // * @throws IllegalArgumentException If the max pool size is less than zero. // */ // public SimplePool(int maxPoolSize) { // if (maxPoolSize <= 0) { // throw new IllegalArgumentException("The max pool size must be > 0"); // } // mPool = new Object[maxPoolSize]; // } // // @Override // @SuppressWarnings("unchecked") // public T acquire() { // if (mPoolSize > 0) { // final int lastPooledIndex = mPoolSize - 1; // T instance = (T) mPool[lastPooledIndex]; // mPool[lastPooledIndex] = null; // mPoolSize--; // return instance; // } // return null; // } // // @Override // public boolean release(T instance) { // if (isInPool(instance)) { // throw new IllegalStateException("Already in the pool!"); // } // if (mPoolSize < mPool.length) { // mPool[mPoolSize] = instance; // mPoolSize++; // return true; // } // return false; // } // // private boolean isInPool(T instance) { // for (int i = 0; i < mPoolSize; i++) { // if (mPool[i] == instance) { // return true; // } // } // return false; // } // } // // /** // * Synchronized pool of objects. // * // * @param <T> The pooled type. // */ // public static class SynchronizedPool<T> extends SimplePool<T> { // private final Object mLock; // // /** // * Creates a new instance. // * // * @param maxPoolSize The max pool size. // * @param lock an optional custom object to synchronize on // * @throws IllegalArgumentException If the max pool size is less than zero. // */ // public SynchronizedPool(int maxPoolSize, Object lock) { // super(maxPoolSize); // mLock = lock; // } // // /** // * @see #SynchronizedPool(int, Object) // */ // public SynchronizedPool(int maxPoolSize) { // this(maxPoolSize, new Object()); // } // // @Override // public T acquire() { // synchronized (mLock) { // return super.acquire(); // } // } // // @Override // public boolean release(T element) { // synchronized (mLock) { // return super.release(element); // } // } // } // }
import android.graphics.Canvas; import android.graphics.Rect; import android.util.Pools;
package android.view; public class DisplayListCanvas extends Canvas { private static final int POOL_LIMIT = 25; //android 6.0,7.0,7.1,8.0,8.1,9.0
// Path: systemlib/src/main/java/android/util/Pools.java // public final class Pools { // // /** // * Interface for managing a pool of objects. // * // * @param <T> The pooled type. // */ // public static interface Pool<T> { // // /** // * @return An instance from the pool if such, null otherwise. // */ // public T acquire(); // // /** // * Release an instance to the pool. // * // * @param instance The instance to release. // * @return Whether the instance was put in the pool. // * @throws IllegalStateException If the instance is already in the pool. // */ // public boolean release(T instance); // } // // private Pools() { // /* do nothing - hiding constructor */ // } // // /** // * Simple (non-synchronized) pool of objects. // * // * @param <T> The pooled type. // */ // public static class SimplePool<T> implements Pool<T> { // private final Object[] mPool; // // private int mPoolSize; // // /** // * Creates a new instance. // * // * @param maxPoolSize The max pool size. // * @throws IllegalArgumentException If the max pool size is less than zero. // */ // public SimplePool(int maxPoolSize) { // if (maxPoolSize <= 0) { // throw new IllegalArgumentException("The max pool size must be > 0"); // } // mPool = new Object[maxPoolSize]; // } // // @Override // @SuppressWarnings("unchecked") // public T acquire() { // if (mPoolSize > 0) { // final int lastPooledIndex = mPoolSize - 1; // T instance = (T) mPool[lastPooledIndex]; // mPool[lastPooledIndex] = null; // mPoolSize--; // return instance; // } // return null; // } // // @Override // public boolean release(T instance) { // if (isInPool(instance)) { // throw new IllegalStateException("Already in the pool!"); // } // if (mPoolSize < mPool.length) { // mPool[mPoolSize] = instance; // mPoolSize++; // return true; // } // return false; // } // // private boolean isInPool(T instance) { // for (int i = 0; i < mPoolSize; i++) { // if (mPool[i] == instance) { // return true; // } // } // return false; // } // } // // /** // * Synchronized pool of objects. // * // * @param <T> The pooled type. // */ // public static class SynchronizedPool<T> extends SimplePool<T> { // private final Object mLock; // // /** // * Creates a new instance. // * // * @param maxPoolSize The max pool size. // * @param lock an optional custom object to synchronize on // * @throws IllegalArgumentException If the max pool size is less than zero. // */ // public SynchronizedPool(int maxPoolSize, Object lock) { // super(maxPoolSize); // mLock = lock; // } // // /** // * @see #SynchronizedPool(int, Object) // */ // public SynchronizedPool(int maxPoolSize) { // this(maxPoolSize, new Object()); // } // // @Override // public T acquire() { // synchronized (mLock) { // return super.acquire(); // } // } // // @Override // public boolean release(T element) { // synchronized (mLock) { // return super.release(element); // } // } // } // } // Path: systemlib/src/main/java/android/view/DisplayListCanvas.java import android.graphics.Canvas; import android.graphics.Rect; import android.util.Pools; package android.view; public class DisplayListCanvas extends Canvas { private static final int POOL_LIMIT = 25; //android 6.0,7.0,7.1,8.0,8.1,9.0
private static final Pools.SynchronizedPool<DisplayListCanvas> sPool =
android-notes/SwissArmyKnife
saklib/src/main/java/com/wanjian/sak/system/rendernode/RenderNodeV21Impl.java
// Path: systemlib/src/main/java/android/view/DisplayListCanvas.java // public class DisplayListCanvas extends Canvas { // // private static final int POOL_LIMIT = 25; // //android 6.0,7.0,7.1,8.0,8.1,9.0 // private static final Pools.SynchronizedPool<DisplayListCanvas> sPool = // new Pools.SynchronizedPool<DisplayListCanvas>(POOL_LIMIT); // // public void onPreDraw(Rect dirty) { // } // // public void insertReorderBarrier() { // } // // public void insertInorderBarrier() { // } // // public void drawRenderNode(RenderNode renderNode) { // } // } // // Path: systemlib/src/main/java/android/view/HardwareCanvas.java // public class HardwareCanvas extends Canvas { // // public void insertReorderBarrier() { // } // // public void insertInorderBarrier() { // } // // public void drawRenderNode(RenderNode renderNode) { // } // } // // Path: systemlib/src/main/java/android/view/RenderNode.java // public class RenderNode { // public DisplayListCanvas start(int width, int height) { // return null; // } // // // public HardwareCanvas start(int width, int height,Object...obj) { // // return null; // // } // // private RenderNode() { // } // // public static RenderNode create(String name, View owningView) { // return null; // } // // public void end(HardwareCanvas canvas) { // } // // // public void end(DisplayListCanvas canvas) { // } // // public boolean setAlpha(float alpha) { // return false; // } // // // public boolean setLeftTopRightBottom(int left, int top, int right, int bottom){ // return false; // } // // public boolean setOutline( Outline outline) { // return false; // } // // public boolean setHasOverlappingRendering(boolean hasOverlappingRendering) { // return false; // } // // public boolean setClipToBounds(boolean clipToBounds) { // return false; // } // public boolean isValid() { // return false; // } // // }
import android.graphics.Canvas; import android.view.DisplayListCanvas; import android.view.HardwareCanvas; import android.view.RenderNode; import java.lang.reflect.Method;
package com.wanjian.sak.system.rendernode; public class RenderNodeV21Impl extends RenderNodeCompact { private RenderNode renderNode; public RenderNodeV21Impl(String name) { renderNode = RenderNode.create(name, null); } @Override public void drawRenderNode(Canvas canvas) {
// Path: systemlib/src/main/java/android/view/DisplayListCanvas.java // public class DisplayListCanvas extends Canvas { // // private static final int POOL_LIMIT = 25; // //android 6.0,7.0,7.1,8.0,8.1,9.0 // private static final Pools.SynchronizedPool<DisplayListCanvas> sPool = // new Pools.SynchronizedPool<DisplayListCanvas>(POOL_LIMIT); // // public void onPreDraw(Rect dirty) { // } // // public void insertReorderBarrier() { // } // // public void insertInorderBarrier() { // } // // public void drawRenderNode(RenderNode renderNode) { // } // } // // Path: systemlib/src/main/java/android/view/HardwareCanvas.java // public class HardwareCanvas extends Canvas { // // public void insertReorderBarrier() { // } // // public void insertInorderBarrier() { // } // // public void drawRenderNode(RenderNode renderNode) { // } // } // // Path: systemlib/src/main/java/android/view/RenderNode.java // public class RenderNode { // public DisplayListCanvas start(int width, int height) { // return null; // } // // // public HardwareCanvas start(int width, int height,Object...obj) { // // return null; // // } // // private RenderNode() { // } // // public static RenderNode create(String name, View owningView) { // return null; // } // // public void end(HardwareCanvas canvas) { // } // // // public void end(DisplayListCanvas canvas) { // } // // public boolean setAlpha(float alpha) { // return false; // } // // // public boolean setLeftTopRightBottom(int left, int top, int right, int bottom){ // return false; // } // // public boolean setOutline( Outline outline) { // return false; // } // // public boolean setHasOverlappingRendering(boolean hasOverlappingRendering) { // return false; // } // // public boolean setClipToBounds(boolean clipToBounds) { // return false; // } // public boolean isValid() { // return false; // } // // } // Path: saklib/src/main/java/com/wanjian/sak/system/rendernode/RenderNodeV21Impl.java import android.graphics.Canvas; import android.view.DisplayListCanvas; import android.view.HardwareCanvas; import android.view.RenderNode; import java.lang.reflect.Method; package com.wanjian.sak.system.rendernode; public class RenderNodeV21Impl extends RenderNodeCompact { private RenderNode renderNode; public RenderNodeV21Impl(String name) { renderNode = RenderNode.create(name, null); } @Override public void drawRenderNode(Canvas canvas) {
((HardwareCanvas) canvas).drawRenderNode(renderNode);
android-notes/SwissArmyKnife
saklib/src/main/java/com/wanjian/sak/layer/impl/LayerTxtAdapter.java
// Path: saklib/src/main/java/com/wanjian/sak/utils/ScreenUtils.java // public class ScreenUtils { // // public static int dp2px(Context context, int dip) { // float density = context.getResources().getDisplayMetrics().density; // return (int) (dip * density + 0.5); // } // // public static int px2dp(Context context, float pxValue) { // final float scale = context.getResources().getDisplayMetrics().density; // return (int) (pxValue / scale + 0.5f); // } // // }
import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.view.View; import com.wanjian.sak.utils.ScreenUtils;
package com.wanjian.sak.layer.impl; /** * Created by wanjian on 2016/10/26. * <p> * 在view左上角画浅白色背景和文本 */ public abstract class LayerTxtAdapter extends ViewLayer { private Paint mPaint; private Rect mRect = new Rect(); @Override protected void onAttach(View rootView) { super.onAttach(rootView); mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
// Path: saklib/src/main/java/com/wanjian/sak/utils/ScreenUtils.java // public class ScreenUtils { // // public static int dp2px(Context context, int dip) { // float density = context.getResources().getDisplayMetrics().density; // return (int) (dip * density + 0.5); // } // // public static int px2dp(Context context, float pxValue) { // final float scale = context.getResources().getDisplayMetrics().density; // return (int) (pxValue / scale + 0.5f); // } // // } // Path: saklib/src/main/java/com/wanjian/sak/layer/impl/LayerTxtAdapter.java import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.view.View; import com.wanjian.sak.utils.ScreenUtils; package com.wanjian.sak.layer.impl; /** * Created by wanjian on 2016/10/26. * <p> * 在view左上角画浅白色背景和文本 */ public abstract class LayerTxtAdapter extends ViewLayer { private Paint mPaint; private Rect mRect = new Rect(); @Override protected void onAttach(View rootView) { super.onAttach(rootView); mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setTextSize(ScreenUtils.dp2px(getContext(), 10));
sourcepole/jasperreports-wms-component
jasperreports-wms-component/src/main/java/com/sourcepole/jasperreports/wmsmap/WmsMapElementXmlHandler.java
// Path: jasperreports-wms-component/src/main/java/com/sourcepole/jasperreports/wmsmap/WmsMapElementImageProvider.java // public static JRPrintImage getImage( // JasperReportsContext jasperReportsContext, JRGenericPrintElement element) // throws JRException, IOException { // // JRBasePrintImage printImage = new JRBasePrintImage( // element.getDefaultStyleProvider()); // // printImage.setUUID(element.getUUID()); // printImage.setX(element.getX()); // printImage.setY(element.getY()); // printImage.setWidth(element.getWidth()); // printImage.setHeight(element.getHeight()); // printImage.setStyle(element.getStyle()); // printImage.setMode(element.getModeValue()); // printImage.setBackcolor(element.getBackcolor()); // printImage.setForecolor(element.getForecolor()); // printImage.setLazy(false); // printImage.setScaleImage(ScaleImageEnum.CLIP); // printImage.setHorizontalAlignment(HorizontalAlignEnum.LEFT); // printImage.setVerticalAlignment(VerticalAlignEnum.TOP); // // Renderable cacheRenderer = (Renderable) element // .getParameterValue(WmsMapPrintElement.PARAMETER_CACHE_RENDERER); // // if (cacheRenderer == null) { // cacheRenderer = getImageRenderable(jasperReportsContext, element); // element.setParameterValue(WmsMapPrintElement.PARAMETER_CACHE_RENDERER, // cacheRenderer); // } // // printImage.setRenderable(cacheRenderer); // // return printImage; // }
import static com.sourcepole.jasperreports.wmsmap.WmsMapElementImageProvider.getImage; import net.sf.jasperreports.engine.JRGenericPrintElement; import net.sf.jasperreports.engine.export.GenericElementXmlHandler; import net.sf.jasperreports.engine.export.JRXmlExporter; import net.sf.jasperreports.engine.export.JRXmlExporterContext;
/* * JasperReports/iReport WMS Component * * Copyright (C) 2013 Sourcepole AG * * JasperReports/iReport WMS Component is free software: you can redistribute * it and/or modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * JasperReports/iReport WMS Component is distributed in the hope that it will * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with JasperReports/iReport WMS Component. * If not, see <http://www.gnu.org/licenses/>. */ package com.sourcepole.jasperreports.wmsmap; /** * WMS map element handler to produce XML report output. */ public class WmsMapElementXmlHandler implements GenericElementXmlHandler { private static final WmsMapElementXmlHandler INSTANCE = new WmsMapElementXmlHandler(); public static WmsMapElementXmlHandler getInstance() { return INSTANCE; } @Override public void exportElement(JRXmlExporterContext exporterContext, JRGenericPrintElement element) { try { JRXmlExporter exporter = (JRXmlExporter) exporterContext.getExporter();
// Path: jasperreports-wms-component/src/main/java/com/sourcepole/jasperreports/wmsmap/WmsMapElementImageProvider.java // public static JRPrintImage getImage( // JasperReportsContext jasperReportsContext, JRGenericPrintElement element) // throws JRException, IOException { // // JRBasePrintImage printImage = new JRBasePrintImage( // element.getDefaultStyleProvider()); // // printImage.setUUID(element.getUUID()); // printImage.setX(element.getX()); // printImage.setY(element.getY()); // printImage.setWidth(element.getWidth()); // printImage.setHeight(element.getHeight()); // printImage.setStyle(element.getStyle()); // printImage.setMode(element.getModeValue()); // printImage.setBackcolor(element.getBackcolor()); // printImage.setForecolor(element.getForecolor()); // printImage.setLazy(false); // printImage.setScaleImage(ScaleImageEnum.CLIP); // printImage.setHorizontalAlignment(HorizontalAlignEnum.LEFT); // printImage.setVerticalAlignment(VerticalAlignEnum.TOP); // // Renderable cacheRenderer = (Renderable) element // .getParameterValue(WmsMapPrintElement.PARAMETER_CACHE_RENDERER); // // if (cacheRenderer == null) { // cacheRenderer = getImageRenderable(jasperReportsContext, element); // element.setParameterValue(WmsMapPrintElement.PARAMETER_CACHE_RENDERER, // cacheRenderer); // } // // printImage.setRenderable(cacheRenderer); // // return printImage; // } // Path: jasperreports-wms-component/src/main/java/com/sourcepole/jasperreports/wmsmap/WmsMapElementXmlHandler.java import static com.sourcepole.jasperreports.wmsmap.WmsMapElementImageProvider.getImage; import net.sf.jasperreports.engine.JRGenericPrintElement; import net.sf.jasperreports.engine.export.GenericElementXmlHandler; import net.sf.jasperreports.engine.export.JRXmlExporter; import net.sf.jasperreports.engine.export.JRXmlExporterContext; /* * JasperReports/iReport WMS Component * * Copyright (C) 2013 Sourcepole AG * * JasperReports/iReport WMS Component is free software: you can redistribute * it and/or modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * JasperReports/iReport WMS Component is distributed in the hope that it will * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with JasperReports/iReport WMS Component. * If not, see <http://www.gnu.org/licenses/>. */ package com.sourcepole.jasperreports.wmsmap; /** * WMS map element handler to produce XML report output. */ public class WmsMapElementXmlHandler implements GenericElementXmlHandler { private static final WmsMapElementXmlHandler INSTANCE = new WmsMapElementXmlHandler(); public static WmsMapElementXmlHandler getInstance() { return INSTANCE; } @Override public void exportElement(JRXmlExporterContext exporterContext, JRGenericPrintElement element) { try { JRXmlExporter exporter = (JRXmlExporter) exporterContext.getExporter();
exporter.exportImage(getImage(exporterContext.getJasperReportsContext(),
sourcepole/jasperreports-wms-component
jasperreports-wms-component/src/main/java/com/sourcepole/jasperreports/wmsmap/WmsMapElementXlsHandler.java
// Path: jasperreports-wms-component/src/main/java/com/sourcepole/jasperreports/wmsmap/WmsMapElementImageProvider.java // public static JRPrintImage getImage( // JasperReportsContext jasperReportsContext, JRGenericPrintElement element) // throws JRException, IOException { // // JRBasePrintImage printImage = new JRBasePrintImage( // element.getDefaultStyleProvider()); // // printImage.setUUID(element.getUUID()); // printImage.setX(element.getX()); // printImage.setY(element.getY()); // printImage.setWidth(element.getWidth()); // printImage.setHeight(element.getHeight()); // printImage.setStyle(element.getStyle()); // printImage.setMode(element.getModeValue()); // printImage.setBackcolor(element.getBackcolor()); // printImage.setForecolor(element.getForecolor()); // printImage.setLazy(false); // printImage.setScaleImage(ScaleImageEnum.CLIP); // printImage.setHorizontalAlignment(HorizontalAlignEnum.LEFT); // printImage.setVerticalAlignment(VerticalAlignEnum.TOP); // // Renderable cacheRenderer = (Renderable) element // .getParameterValue(WmsMapPrintElement.PARAMETER_CACHE_RENDERER); // // if (cacheRenderer == null) { // cacheRenderer = getImageRenderable(jasperReportsContext, element); // element.setParameterValue(WmsMapPrintElement.PARAMETER_CACHE_RENDERER, // cacheRenderer); // } // // printImage.setRenderable(cacheRenderer); // // return printImage; // }
import static com.sourcepole.jasperreports.wmsmap.WmsMapElementImageProvider.getImage; import net.sf.jasperreports.engine.JRGenericPrintElement; import net.sf.jasperreports.engine.JRPrintImage; import net.sf.jasperreports.engine.export.GenericElementXlsHandler; import net.sf.jasperreports.engine.export.JRExporterGridCell; import net.sf.jasperreports.engine.export.JRGridLayout; import net.sf.jasperreports.engine.export.JRXlsExporter; import net.sf.jasperreports.engine.export.JRXlsExporterContext;
/* * JasperReports/iReport WMS Component * * Copyright (C) 2013 Sourcepole AG * * JasperReports/iReport WMS Component is free software: you can redistribute * it and/or modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * JasperReports/iReport WMS Component is distributed in the hope that it will * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with JasperReports/iReport WMS Component. * If not, see <http://www.gnu.org/licenses/>. */ package com.sourcepole.jasperreports.wmsmap; /** * WMS map element handler to produce XLS report output. */ public class WmsMapElementXlsHandler implements GenericElementXlsHandler { private static final WmsMapElementXlsHandler INSTANCE = new WmsMapElementXlsHandler(); public static WmsMapElementXlsHandler getInstance() { return INSTANCE; } @Override public void exportElement(JRXlsExporterContext exporterContext, JRGenericPrintElement element, JRExporterGridCell gridCell, int colIndex, int rowIndex, int emptyCols, int yCutsRow, JRGridLayout layout ) { try { JRXlsExporter exporter = (JRXlsExporter) exporterContext.getExporter();
// Path: jasperreports-wms-component/src/main/java/com/sourcepole/jasperreports/wmsmap/WmsMapElementImageProvider.java // public static JRPrintImage getImage( // JasperReportsContext jasperReportsContext, JRGenericPrintElement element) // throws JRException, IOException { // // JRBasePrintImage printImage = new JRBasePrintImage( // element.getDefaultStyleProvider()); // // printImage.setUUID(element.getUUID()); // printImage.setX(element.getX()); // printImage.setY(element.getY()); // printImage.setWidth(element.getWidth()); // printImage.setHeight(element.getHeight()); // printImage.setStyle(element.getStyle()); // printImage.setMode(element.getModeValue()); // printImage.setBackcolor(element.getBackcolor()); // printImage.setForecolor(element.getForecolor()); // printImage.setLazy(false); // printImage.setScaleImage(ScaleImageEnum.CLIP); // printImage.setHorizontalAlignment(HorizontalAlignEnum.LEFT); // printImage.setVerticalAlignment(VerticalAlignEnum.TOP); // // Renderable cacheRenderer = (Renderable) element // .getParameterValue(WmsMapPrintElement.PARAMETER_CACHE_RENDERER); // // if (cacheRenderer == null) { // cacheRenderer = getImageRenderable(jasperReportsContext, element); // element.setParameterValue(WmsMapPrintElement.PARAMETER_CACHE_RENDERER, // cacheRenderer); // } // // printImage.setRenderable(cacheRenderer); // // return printImage; // } // Path: jasperreports-wms-component/src/main/java/com/sourcepole/jasperreports/wmsmap/WmsMapElementXlsHandler.java import static com.sourcepole.jasperreports.wmsmap.WmsMapElementImageProvider.getImage; import net.sf.jasperreports.engine.JRGenericPrintElement; import net.sf.jasperreports.engine.JRPrintImage; import net.sf.jasperreports.engine.export.GenericElementXlsHandler; import net.sf.jasperreports.engine.export.JRExporterGridCell; import net.sf.jasperreports.engine.export.JRGridLayout; import net.sf.jasperreports.engine.export.JRXlsExporter; import net.sf.jasperreports.engine.export.JRXlsExporterContext; /* * JasperReports/iReport WMS Component * * Copyright (C) 2013 Sourcepole AG * * JasperReports/iReport WMS Component is free software: you can redistribute * it and/or modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * JasperReports/iReport WMS Component is distributed in the hope that it will * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with JasperReports/iReport WMS Component. * If not, see <http://www.gnu.org/licenses/>. */ package com.sourcepole.jasperreports.wmsmap; /** * WMS map element handler to produce XLS report output. */ public class WmsMapElementXlsHandler implements GenericElementXlsHandler { private static final WmsMapElementXlsHandler INSTANCE = new WmsMapElementXlsHandler(); public static WmsMapElementXlsHandler getInstance() { return INSTANCE; } @Override public void exportElement(JRXlsExporterContext exporterContext, JRGenericPrintElement element, JRExporterGridCell gridCell, int colIndex, int rowIndex, int emptyCols, int yCutsRow, JRGridLayout layout ) { try { JRXlsExporter exporter = (JRXlsExporter) exporterContext.getExporter();
JRPrintImage image = getImage(exporterContext.getJasperReportsContext(),
sourcepole/jasperreports-wms-component
jasperreports-wms-component/src/main/java/com/sourcepole/jasperreports/wmsmap/fill/WmsMapFillFactory.java
// Path: jasperreports-wms-component/src/main/java/com/sourcepole/jasperreports/wmsmap/WmsMapComponent.java // public interface WmsMapComponent extends Component, JRCloneable { // // JRExpression getBBoxExpression(); // // JRExpression getLayersExpression(); // // JRExpression getStylesExpression(); // // JRExpression getUrlParametersExpression(); // // EvaluationTimeEnum getEvaluationTime(); // // String getEvaluationGroup(); // // String getWmsServiceUrl(); // // String getWmsVersion(); // // String getSrs(); // // String getImageType(); // // Boolean getTransparent(); // // }
import net.sf.jasperreports.engine.component.Component; import net.sf.jasperreports.engine.component.ComponentFillFactory; import net.sf.jasperreports.engine.component.FillComponent; import net.sf.jasperreports.engine.fill.JRFillCloneFactory; import net.sf.jasperreports.engine.fill.JRFillObjectFactory; import com.sourcepole.jasperreports.wmsmap.WmsMapComponent;
/* * JasperReports/iReport WMS Component * * Copyright (C) 2013 Sourcepole AG * * JasperReports/iReport WMS Component is free software: you can redistribute * it and/or modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * JasperReports/iReport WMS Component is distributed in the hope that it will * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with JasperReports/iReport WMS Component. * If not, see <http://www.gnu.org/licenses/>. */ package com.sourcepole.jasperreports.wmsmap.fill; /** * Factory for {@link WmsMapFillComponent}s. */ public class WmsMapFillFactory implements ComponentFillFactory { @Override public FillComponent toFillComponent(Component component, JRFillObjectFactory factory) {
// Path: jasperreports-wms-component/src/main/java/com/sourcepole/jasperreports/wmsmap/WmsMapComponent.java // public interface WmsMapComponent extends Component, JRCloneable { // // JRExpression getBBoxExpression(); // // JRExpression getLayersExpression(); // // JRExpression getStylesExpression(); // // JRExpression getUrlParametersExpression(); // // EvaluationTimeEnum getEvaluationTime(); // // String getEvaluationGroup(); // // String getWmsServiceUrl(); // // String getWmsVersion(); // // String getSrs(); // // String getImageType(); // // Boolean getTransparent(); // // } // Path: jasperreports-wms-component/src/main/java/com/sourcepole/jasperreports/wmsmap/fill/WmsMapFillFactory.java import net.sf.jasperreports.engine.component.Component; import net.sf.jasperreports.engine.component.ComponentFillFactory; import net.sf.jasperreports.engine.component.FillComponent; import net.sf.jasperreports.engine.fill.JRFillCloneFactory; import net.sf.jasperreports.engine.fill.JRFillObjectFactory; import com.sourcepole.jasperreports.wmsmap.WmsMapComponent; /* * JasperReports/iReport WMS Component * * Copyright (C) 2013 Sourcepole AG * * JasperReports/iReport WMS Component is free software: you can redistribute * it and/or modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * JasperReports/iReport WMS Component is distributed in the hope that it will * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with JasperReports/iReport WMS Component. * If not, see <http://www.gnu.org/licenses/>. */ package com.sourcepole.jasperreports.wmsmap.fill; /** * Factory for {@link WmsMapFillComponent}s. */ public class WmsMapFillFactory implements ComponentFillFactory { @Override public FillComponent toFillComponent(Component component, JRFillObjectFactory factory) {
WmsMapComponent map = (WmsMapComponent) component;
sourcepole/jasperreports-wms-component
jasperreports-wms-component/src/main/java/com/sourcepole/jasperreports/wmsmap/WmsMapElementJExcelApiHandler.java
// Path: jasperreports-wms-component/src/main/java/com/sourcepole/jasperreports/wmsmap/WmsMapElementImageProvider.java // public static JRPrintImage getImage( // JasperReportsContext jasperReportsContext, JRGenericPrintElement element) // throws JRException, IOException { // // JRBasePrintImage printImage = new JRBasePrintImage( // element.getDefaultStyleProvider()); // // printImage.setUUID(element.getUUID()); // printImage.setX(element.getX()); // printImage.setY(element.getY()); // printImage.setWidth(element.getWidth()); // printImage.setHeight(element.getHeight()); // printImage.setStyle(element.getStyle()); // printImage.setMode(element.getModeValue()); // printImage.setBackcolor(element.getBackcolor()); // printImage.setForecolor(element.getForecolor()); // printImage.setLazy(false); // printImage.setScaleImage(ScaleImageEnum.CLIP); // printImage.setHorizontalAlignment(HorizontalAlignEnum.LEFT); // printImage.setVerticalAlignment(VerticalAlignEnum.TOP); // // Renderable cacheRenderer = (Renderable) element // .getParameterValue(WmsMapPrintElement.PARAMETER_CACHE_RENDERER); // // if (cacheRenderer == null) { // cacheRenderer = getImageRenderable(jasperReportsContext, element); // element.setParameterValue(WmsMapPrintElement.PARAMETER_CACHE_RENDERER, // cacheRenderer); // } // // printImage.setRenderable(cacheRenderer); // // return printImage; // }
import static com.sourcepole.jasperreports.wmsmap.WmsMapElementImageProvider.getImage; import net.sf.jasperreports.engine.JRGenericPrintElement; import net.sf.jasperreports.engine.JRPrintImage; import net.sf.jasperreports.engine.JasperReportsContext; import net.sf.jasperreports.engine.export.GenericElementJExcelApiHandler; import net.sf.jasperreports.engine.export.JExcelApiExporter; import net.sf.jasperreports.engine.export.JExcelApiExporterContext; import net.sf.jasperreports.engine.export.JRExporterGridCell; import net.sf.jasperreports.engine.export.JRGridLayout;
/* * JasperReports/iReport WMS Component * * Copyright (C) 2013 Sourcepole AG * * JasperReports/iReport WMS Component is free software: you can redistribute * it and/or modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * JasperReports/iReport WMS Component is distributed in the hope that it will * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with JasperReports/iReport WMS Component. * If not, see <http://www.gnu.org/licenses/>. */ package com.sourcepole.jasperreports.wmsmap; /** * JExcel handler for WmsMap elements. */ public class WmsMapElementJExcelApiHandler implements GenericElementJExcelApiHandler { /** Singleton instance. */ private static final WmsMapElementJExcelApiHandler INSTANCE = new WmsMapElementJExcelApiHandler(); public static WmsMapElementJExcelApiHandler getInstance() { return INSTANCE; } @Override public void exportElement(JExcelApiExporterContext exporterContext, JRGenericPrintElement element, JRExporterGridCell gridCell, int colIndex, int rowIndex, int emptyCols, int yCutsRow, JRGridLayout layout) { try { JExcelApiExporter exporter = (JExcelApiExporter) exporterContext .getExporter(); JasperReportsContext reportsContext = exporterContext .getJasperReportsContext();
// Path: jasperreports-wms-component/src/main/java/com/sourcepole/jasperreports/wmsmap/WmsMapElementImageProvider.java // public static JRPrintImage getImage( // JasperReportsContext jasperReportsContext, JRGenericPrintElement element) // throws JRException, IOException { // // JRBasePrintImage printImage = new JRBasePrintImage( // element.getDefaultStyleProvider()); // // printImage.setUUID(element.getUUID()); // printImage.setX(element.getX()); // printImage.setY(element.getY()); // printImage.setWidth(element.getWidth()); // printImage.setHeight(element.getHeight()); // printImage.setStyle(element.getStyle()); // printImage.setMode(element.getModeValue()); // printImage.setBackcolor(element.getBackcolor()); // printImage.setForecolor(element.getForecolor()); // printImage.setLazy(false); // printImage.setScaleImage(ScaleImageEnum.CLIP); // printImage.setHorizontalAlignment(HorizontalAlignEnum.LEFT); // printImage.setVerticalAlignment(VerticalAlignEnum.TOP); // // Renderable cacheRenderer = (Renderable) element // .getParameterValue(WmsMapPrintElement.PARAMETER_CACHE_RENDERER); // // if (cacheRenderer == null) { // cacheRenderer = getImageRenderable(jasperReportsContext, element); // element.setParameterValue(WmsMapPrintElement.PARAMETER_CACHE_RENDERER, // cacheRenderer); // } // // printImage.setRenderable(cacheRenderer); // // return printImage; // } // Path: jasperreports-wms-component/src/main/java/com/sourcepole/jasperreports/wmsmap/WmsMapElementJExcelApiHandler.java import static com.sourcepole.jasperreports.wmsmap.WmsMapElementImageProvider.getImage; import net.sf.jasperreports.engine.JRGenericPrintElement; import net.sf.jasperreports.engine.JRPrintImage; import net.sf.jasperreports.engine.JasperReportsContext; import net.sf.jasperreports.engine.export.GenericElementJExcelApiHandler; import net.sf.jasperreports.engine.export.JExcelApiExporter; import net.sf.jasperreports.engine.export.JExcelApiExporterContext; import net.sf.jasperreports.engine.export.JRExporterGridCell; import net.sf.jasperreports.engine.export.JRGridLayout; /* * JasperReports/iReport WMS Component * * Copyright (C) 2013 Sourcepole AG * * JasperReports/iReport WMS Component is free software: you can redistribute * it and/or modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * JasperReports/iReport WMS Component is distributed in the hope that it will * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with JasperReports/iReport WMS Component. * If not, see <http://www.gnu.org/licenses/>. */ package com.sourcepole.jasperreports.wmsmap; /** * JExcel handler for WmsMap elements. */ public class WmsMapElementJExcelApiHandler implements GenericElementJExcelApiHandler { /** Singleton instance. */ private static final WmsMapElementJExcelApiHandler INSTANCE = new WmsMapElementJExcelApiHandler(); public static WmsMapElementJExcelApiHandler getInstance() { return INSTANCE; } @Override public void exportElement(JExcelApiExporterContext exporterContext, JRGenericPrintElement element, JRExporterGridCell gridCell, int colIndex, int rowIndex, int emptyCols, int yCutsRow, JRGridLayout layout) { try { JExcelApiExporter exporter = (JExcelApiExporter) exporterContext .getExporter(); JasperReportsContext reportsContext = exporterContext .getJasperReportsContext();
JRPrintImage printImage = getImage(reportsContext, element);
sourcepole/jasperreports-wms-component
jasperreports-wms-component/src/main/java/com/sourcepole/jasperreports/wmsmap/WmsMapElementGraphics2DHandler.java
// Path: jasperreports-wms-component/src/main/java/com/sourcepole/jasperreports/wmsmap/WmsMapElementImageProvider.java // public static JRPrintImage getImage( // JasperReportsContext jasperReportsContext, JRGenericPrintElement element) // throws JRException, IOException { // // JRBasePrintImage printImage = new JRBasePrintImage( // element.getDefaultStyleProvider()); // // printImage.setUUID(element.getUUID()); // printImage.setX(element.getX()); // printImage.setY(element.getY()); // printImage.setWidth(element.getWidth()); // printImage.setHeight(element.getHeight()); // printImage.setStyle(element.getStyle()); // printImage.setMode(element.getModeValue()); // printImage.setBackcolor(element.getBackcolor()); // printImage.setForecolor(element.getForecolor()); // printImage.setLazy(false); // printImage.setScaleImage(ScaleImageEnum.CLIP); // printImage.setHorizontalAlignment(HorizontalAlignEnum.LEFT); // printImage.setVerticalAlignment(VerticalAlignEnum.TOP); // // Renderable cacheRenderer = (Renderable) element // .getParameterValue(WmsMapPrintElement.PARAMETER_CACHE_RENDERER); // // if (cacheRenderer == null) { // cacheRenderer = getImageRenderable(jasperReportsContext, element); // element.setParameterValue(WmsMapPrintElement.PARAMETER_CACHE_RENDERER, // cacheRenderer); // } // // printImage.setRenderable(cacheRenderer); // // return printImage; // }
import static com.sourcepole.jasperreports.wmsmap.WmsMapElementImageProvider.getImage; import java.awt.Graphics2D; import net.sf.jasperreports.engine.JRGenericPrintElement; import net.sf.jasperreports.engine.JRPrintImage; import net.sf.jasperreports.engine.export.GenericElementGraphics2DHandler; import net.sf.jasperreports.engine.export.JRGraphics2DExporter; import net.sf.jasperreports.engine.export.JRGraphics2DExporterContext; import net.sf.jasperreports.engine.export.draw.ImageDrawer; import net.sf.jasperreports.engine.export.draw.Offset;
/* * JasperReports/iReport WMS Component * * Copyright (C) 2013 Sourcepole AG * * JasperReports/iReport WMS Component is free software: you can redistribute * it and/or modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * JasperReports/iReport WMS Component is distributed in the hope that it will * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with JasperReports/iReport WMS Component. * If not, see <http://www.gnu.org/licenses/>. */ package com.sourcepole.jasperreports.wmsmap; /** * WMS map element handler to produce {@link Graphics2D} report output as used * in iReport preview. */ public class WmsMapElementGraphics2DHandler implements GenericElementGraphics2DHandler { private static final WmsMapElementGraphics2DHandler INSTANCE = new WmsMapElementGraphics2DHandler(); public static WmsMapElementGraphics2DHandler getInstance() { return INSTANCE; } @Override public void exportElement(JRGraphics2DExporterContext context, JRGenericPrintElement element, Graphics2D grx, Offset offset) { try { JRGraphics2DExporter exporter = (JRGraphics2DExporter) context .getExporter(); ImageDrawer imageDrawer = exporter.getFrameDrawer().getDrawVisitor() .getImageDrawer();
// Path: jasperreports-wms-component/src/main/java/com/sourcepole/jasperreports/wmsmap/WmsMapElementImageProvider.java // public static JRPrintImage getImage( // JasperReportsContext jasperReportsContext, JRGenericPrintElement element) // throws JRException, IOException { // // JRBasePrintImage printImage = new JRBasePrintImage( // element.getDefaultStyleProvider()); // // printImage.setUUID(element.getUUID()); // printImage.setX(element.getX()); // printImage.setY(element.getY()); // printImage.setWidth(element.getWidth()); // printImage.setHeight(element.getHeight()); // printImage.setStyle(element.getStyle()); // printImage.setMode(element.getModeValue()); // printImage.setBackcolor(element.getBackcolor()); // printImage.setForecolor(element.getForecolor()); // printImage.setLazy(false); // printImage.setScaleImage(ScaleImageEnum.CLIP); // printImage.setHorizontalAlignment(HorizontalAlignEnum.LEFT); // printImage.setVerticalAlignment(VerticalAlignEnum.TOP); // // Renderable cacheRenderer = (Renderable) element // .getParameterValue(WmsMapPrintElement.PARAMETER_CACHE_RENDERER); // // if (cacheRenderer == null) { // cacheRenderer = getImageRenderable(jasperReportsContext, element); // element.setParameterValue(WmsMapPrintElement.PARAMETER_CACHE_RENDERER, // cacheRenderer); // } // // printImage.setRenderable(cacheRenderer); // // return printImage; // } // Path: jasperreports-wms-component/src/main/java/com/sourcepole/jasperreports/wmsmap/WmsMapElementGraphics2DHandler.java import static com.sourcepole.jasperreports.wmsmap.WmsMapElementImageProvider.getImage; import java.awt.Graphics2D; import net.sf.jasperreports.engine.JRGenericPrintElement; import net.sf.jasperreports.engine.JRPrintImage; import net.sf.jasperreports.engine.export.GenericElementGraphics2DHandler; import net.sf.jasperreports.engine.export.JRGraphics2DExporter; import net.sf.jasperreports.engine.export.JRGraphics2DExporterContext; import net.sf.jasperreports.engine.export.draw.ImageDrawer; import net.sf.jasperreports.engine.export.draw.Offset; /* * JasperReports/iReport WMS Component * * Copyright (C) 2013 Sourcepole AG * * JasperReports/iReport WMS Component is free software: you can redistribute * it and/or modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * JasperReports/iReport WMS Component is distributed in the hope that it will * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with JasperReports/iReport WMS Component. * If not, see <http://www.gnu.org/licenses/>. */ package com.sourcepole.jasperreports.wmsmap; /** * WMS map element handler to produce {@link Graphics2D} report output as used * in iReport preview. */ public class WmsMapElementGraphics2DHandler implements GenericElementGraphics2DHandler { private static final WmsMapElementGraphics2DHandler INSTANCE = new WmsMapElementGraphics2DHandler(); public static WmsMapElementGraphics2DHandler getInstance() { return INSTANCE; } @Override public void exportElement(JRGraphics2DExporterContext context, JRGenericPrintElement element, Graphics2D grx, Offset offset) { try { JRGraphics2DExporter exporter = (JRGraphics2DExporter) context .getExporter(); ImageDrawer imageDrawer = exporter.getFrameDrawer().getDrawVisitor() .getImageDrawer();
JRPrintImage image = getImage(context.getJasperReportsContext(), element);