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
dazraf/vertx-futures
src/test/java/io/dazraf/vertx/futures/FuturesTest.java
// Path: src/main/java/io/dazraf/vertx/futures/Futures.java // static <T> Futures<T> when(Future<T> future) { // return FuturesImpl.when(future); // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/CallProcessor.java // static <T, R> CallProcessor<T, R> call(Supplier<Future<R>> supplier) { // return call(result -> supplier.get()); // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/RunProcessor.java // static <T> RunProcessor<T> runOnFail(Consumer<Throwable> consumer) { // return runOnResponse(failure(consumer)); // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/RunProcessor.java // static <T> RunProcessor<T> run(Runnable runnable) { // return runOnResponse(success(runnable)); // }
import org.junit.ClassRule; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import io.vertx.core.Future; import io.vertx.ext.unit.junit.RunTestOnContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import static io.dazraf.vertx.futures.Futures.when; import static io.dazraf.vertx.futures.processors.CallProcessor.call; import static io.dazraf.vertx.futures.processors.RunProcessor.runOnFail; import static io.dazraf.vertx.futures.processors.RunProcessor.run; import static io.vertx.core.Future.succeededFuture; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.*; import static org.slf4j.LoggerFactory.getLogger;
package io.dazraf.vertx.futures; @RunWith(VertxUnitRunner.class) public class FuturesTest { private static final Logger LOG = getLogger(FuturesTest.class); private static final int ID = 1; private static final String FAILURE_MSG = "Failure!"; @ClassRule public static RunTestOnContext context = new RunTestOnContext(); @Test public void test_1then2then1_happypath_succeeds() {
// Path: src/main/java/io/dazraf/vertx/futures/Futures.java // static <T> Futures<T> when(Future<T> future) { // return FuturesImpl.when(future); // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/CallProcessor.java // static <T, R> CallProcessor<T, R> call(Supplier<Future<R>> supplier) { // return call(result -> supplier.get()); // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/RunProcessor.java // static <T> RunProcessor<T> runOnFail(Consumer<Throwable> consumer) { // return runOnResponse(failure(consumer)); // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/RunProcessor.java // static <T> RunProcessor<T> run(Runnable runnable) { // return runOnResponse(success(runnable)); // } // Path: src/test/java/io/dazraf/vertx/futures/FuturesTest.java import org.junit.ClassRule; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import io.vertx.core.Future; import io.vertx.ext.unit.junit.RunTestOnContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import static io.dazraf.vertx.futures.Futures.when; import static io.dazraf.vertx.futures.processors.CallProcessor.call; import static io.dazraf.vertx.futures.processors.RunProcessor.runOnFail; import static io.dazraf.vertx.futures.processors.RunProcessor.run; import static io.vertx.core.Future.succeededFuture; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.*; import static org.slf4j.LoggerFactory.getLogger; package io.dazraf.vertx.futures; @RunWith(VertxUnitRunner.class) public class FuturesTest { private static final Logger LOG = getLogger(FuturesTest.class); private static final int ID = 1; private static final String FAILURE_MSG = "Failure!"; @ClassRule public static RunTestOnContext context = new RunTestOnContext(); @Test public void test_1then2then1_happypath_succeeds() {
when(getId())
dazraf/vertx-futures
src/test/java/io/dazraf/vertx/futures/FuturesTest.java
// Path: src/main/java/io/dazraf/vertx/futures/Futures.java // static <T> Futures<T> when(Future<T> future) { // return FuturesImpl.when(future); // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/CallProcessor.java // static <T, R> CallProcessor<T, R> call(Supplier<Future<R>> supplier) { // return call(result -> supplier.get()); // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/RunProcessor.java // static <T> RunProcessor<T> runOnFail(Consumer<Throwable> consumer) { // return runOnResponse(failure(consumer)); // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/RunProcessor.java // static <T> RunProcessor<T> run(Runnable runnable) { // return runOnResponse(success(runnable)); // }
import org.junit.ClassRule; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import io.vertx.core.Future; import io.vertx.ext.unit.junit.RunTestOnContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import static io.dazraf.vertx.futures.Futures.when; import static io.dazraf.vertx.futures.processors.CallProcessor.call; import static io.dazraf.vertx.futures.processors.RunProcessor.runOnFail; import static io.dazraf.vertx.futures.processors.RunProcessor.run; import static io.vertx.core.Future.succeededFuture; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.*; import static org.slf4j.LoggerFactory.getLogger;
package io.dazraf.vertx.futures; @RunWith(VertxUnitRunner.class) public class FuturesTest { private static final Logger LOG = getLogger(FuturesTest.class); private static final int ID = 1; private static final String FAILURE_MSG = "Failure!"; @ClassRule public static RunTestOnContext context = new RunTestOnContext(); @Test public void test_1then2then1_happypath_succeeds() { when(getId())
// Path: src/main/java/io/dazraf/vertx/futures/Futures.java // static <T> Futures<T> when(Future<T> future) { // return FuturesImpl.when(future); // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/CallProcessor.java // static <T, R> CallProcessor<T, R> call(Supplier<Future<R>> supplier) { // return call(result -> supplier.get()); // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/RunProcessor.java // static <T> RunProcessor<T> runOnFail(Consumer<Throwable> consumer) { // return runOnResponse(failure(consumer)); // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/RunProcessor.java // static <T> RunProcessor<T> run(Runnable runnable) { // return runOnResponse(success(runnable)); // } // Path: src/test/java/io/dazraf/vertx/futures/FuturesTest.java import org.junit.ClassRule; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import io.vertx.core.Future; import io.vertx.ext.unit.junit.RunTestOnContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import static io.dazraf.vertx.futures.Futures.when; import static io.dazraf.vertx.futures.processors.CallProcessor.call; import static io.dazraf.vertx.futures.processors.RunProcessor.runOnFail; import static io.dazraf.vertx.futures.processors.RunProcessor.run; import static io.vertx.core.Future.succeededFuture; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.*; import static org.slf4j.LoggerFactory.getLogger; package io.dazraf.vertx.futures; @RunWith(VertxUnitRunner.class) public class FuturesTest { private static final Logger LOG = getLogger(FuturesTest.class); private static final int ID = 1; private static final String FAILURE_MSG = "Failure!"; @ClassRule public static RunTestOnContext context = new RunTestOnContext(); @Test public void test_1then2then1_happypath_succeeds() { when(getId())
.then(call(id -> when(getName(id), getAge(id))))
dazraf/vertx-futures
src/test/java/io/dazraf/vertx/futures/FuturesTest.java
// Path: src/main/java/io/dazraf/vertx/futures/Futures.java // static <T> Futures<T> when(Future<T> future) { // return FuturesImpl.when(future); // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/CallProcessor.java // static <T, R> CallProcessor<T, R> call(Supplier<Future<R>> supplier) { // return call(result -> supplier.get()); // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/RunProcessor.java // static <T> RunProcessor<T> runOnFail(Consumer<Throwable> consumer) { // return runOnResponse(failure(consumer)); // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/RunProcessor.java // static <T> RunProcessor<T> run(Runnable runnable) { // return runOnResponse(success(runnable)); // }
import org.junit.ClassRule; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import io.vertx.core.Future; import io.vertx.ext.unit.junit.RunTestOnContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import static io.dazraf.vertx.futures.Futures.when; import static io.dazraf.vertx.futures.processors.CallProcessor.call; import static io.dazraf.vertx.futures.processors.RunProcessor.runOnFail; import static io.dazraf.vertx.futures.processors.RunProcessor.run; import static io.vertx.core.Future.succeededFuture; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.*; import static org.slf4j.LoggerFactory.getLogger;
package io.dazraf.vertx.futures; @RunWith(VertxUnitRunner.class) public class FuturesTest { private static final Logger LOG = getLogger(FuturesTest.class); private static final int ID = 1; private static final String FAILURE_MSG = "Failure!"; @ClassRule public static RunTestOnContext context = new RunTestOnContext(); @Test public void test_1then2then1_happypath_succeeds() { when(getId()) .then(call(id -> when(getName(id), getAge(id)))) .then(call((name, age) -> composeMessage(name, age)))
// Path: src/main/java/io/dazraf/vertx/futures/Futures.java // static <T> Futures<T> when(Future<T> future) { // return FuturesImpl.when(future); // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/CallProcessor.java // static <T, R> CallProcessor<T, R> call(Supplier<Future<R>> supplier) { // return call(result -> supplier.get()); // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/RunProcessor.java // static <T> RunProcessor<T> runOnFail(Consumer<Throwable> consumer) { // return runOnResponse(failure(consumer)); // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/RunProcessor.java // static <T> RunProcessor<T> run(Runnable runnable) { // return runOnResponse(success(runnable)); // } // Path: src/test/java/io/dazraf/vertx/futures/FuturesTest.java import org.junit.ClassRule; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import io.vertx.core.Future; import io.vertx.ext.unit.junit.RunTestOnContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import static io.dazraf.vertx.futures.Futures.when; import static io.dazraf.vertx.futures.processors.CallProcessor.call; import static io.dazraf.vertx.futures.processors.RunProcessor.runOnFail; import static io.dazraf.vertx.futures.processors.RunProcessor.run; import static io.vertx.core.Future.succeededFuture; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.*; import static org.slf4j.LoggerFactory.getLogger; package io.dazraf.vertx.futures; @RunWith(VertxUnitRunner.class) public class FuturesTest { private static final Logger LOG = getLogger(FuturesTest.class); private static final int ID = 1; private static final String FAILURE_MSG = "Failure!"; @ClassRule public static RunTestOnContext context = new RunTestOnContext(); @Test public void test_1then2then1_happypath_succeeds() { when(getId()) .then(call(id -> when(getName(id), getAge(id)))) .then(call((name, age) -> composeMessage(name, age)))
.then(run(result -> LOG.info(result)))
dazraf/vertx-futures
src/test/java/io/dazraf/vertx/futures/FuturesTest.java
// Path: src/main/java/io/dazraf/vertx/futures/Futures.java // static <T> Futures<T> when(Future<T> future) { // return FuturesImpl.when(future); // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/CallProcessor.java // static <T, R> CallProcessor<T, R> call(Supplier<Future<R>> supplier) { // return call(result -> supplier.get()); // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/RunProcessor.java // static <T> RunProcessor<T> runOnFail(Consumer<Throwable> consumer) { // return runOnResponse(failure(consumer)); // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/RunProcessor.java // static <T> RunProcessor<T> run(Runnable runnable) { // return runOnResponse(success(runnable)); // }
import org.junit.ClassRule; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import io.vertx.core.Future; import io.vertx.ext.unit.junit.RunTestOnContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import static io.dazraf.vertx.futures.Futures.when; import static io.dazraf.vertx.futures.processors.CallProcessor.call; import static io.dazraf.vertx.futures.processors.RunProcessor.runOnFail; import static io.dazraf.vertx.futures.processors.RunProcessor.run; import static io.vertx.core.Future.succeededFuture; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.*; import static org.slf4j.LoggerFactory.getLogger;
package io.dazraf.vertx.futures; @RunWith(VertxUnitRunner.class) public class FuturesTest { private static final Logger LOG = getLogger(FuturesTest.class); private static final int ID = 1; private static final String FAILURE_MSG = "Failure!"; @ClassRule public static RunTestOnContext context = new RunTestOnContext(); @Test public void test_1then2then1_happypath_succeeds() { when(getId()) .then(call(id -> when(getName(id), getAge(id)))) .then(call((name, age) -> composeMessage(name, age))) .then(run(result -> LOG.info(result)))
// Path: src/main/java/io/dazraf/vertx/futures/Futures.java // static <T> Futures<T> when(Future<T> future) { // return FuturesImpl.when(future); // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/CallProcessor.java // static <T, R> CallProcessor<T, R> call(Supplier<Future<R>> supplier) { // return call(result -> supplier.get()); // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/RunProcessor.java // static <T> RunProcessor<T> runOnFail(Consumer<Throwable> consumer) { // return runOnResponse(failure(consumer)); // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/RunProcessor.java // static <T> RunProcessor<T> run(Runnable runnable) { // return runOnResponse(success(runnable)); // } // Path: src/test/java/io/dazraf/vertx/futures/FuturesTest.java import org.junit.ClassRule; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import io.vertx.core.Future; import io.vertx.ext.unit.junit.RunTestOnContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import static io.dazraf.vertx.futures.Futures.when; import static io.dazraf.vertx.futures.processors.CallProcessor.call; import static io.dazraf.vertx.futures.processors.RunProcessor.runOnFail; import static io.dazraf.vertx.futures.processors.RunProcessor.run; import static io.vertx.core.Future.succeededFuture; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.*; import static org.slf4j.LoggerFactory.getLogger; package io.dazraf.vertx.futures; @RunWith(VertxUnitRunner.class) public class FuturesTest { private static final Logger LOG = getLogger(FuturesTest.class); private static final int ID = 1; private static final String FAILURE_MSG = "Failure!"; @ClassRule public static RunTestOnContext context = new RunTestOnContext(); @Test public void test_1then2then1_happypath_succeeds() { when(getId()) .then(call(id -> when(getName(id), getAge(id)))) .then(call((name, age) -> composeMessage(name, age))) .then(run(result -> LOG.info(result)))
.then(runOnFail(cause -> LOG.error("error handler", cause)));
dazraf/vertx-futures
src/test/java/io/dazraf/vertx/futures/processors/MapProcessorTest.java
// Path: src/main/java/io/dazraf/vertx/futures/Futures.java // static <T> Futures<T> when(Future<T> future) { // return FuturesImpl.when(future); // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/MapProcessor.java // static <T, R> MapProcessor<T, R> map(Function<T, R> function) { // return mapOnResponse(future -> { // if (future.succeeded()) { // return function.apply(future.result()); // } else { // throw new WrappedException(future.cause()); // } // }); // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/MapProcessor.java // static <T, R> MapProcessor<T, R> mapOnResponse(Function<AsyncResult<T>, R> function) { // return future -> { // try { // return succeededFuture(function.apply(future)); // } // catch (WrappedException err) { // return failedFuture(err.getCause()); // } // catch (Throwable err) { // return failedFuture(err); // } // }; // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/RunProcessor.java // public interface RunProcessor<T> extends FutureProcessor<T, T> { // // Logger LOG = getLogger(RunProcessor.class); // // /** // * Observe the state of the chain. Any exceptions from the consumer will cause the chain to fail. // * @param consumer // * @param <T> // * @return // */ // static <T> RunProcessor<T> runOnResponse(Handler<AsyncResult<T>> consumer) { // return future -> { // Future<T> result = Future.future(); // try { // consumer.handle(future); // result.completer().handle(future); // } catch (Throwable error) { // LOG.error("consumer function failed", error); // result.fail(error); // } // return result; // }; // } // // static <T> RunProcessor<T> run(Runnable runnable) { // return runOnResponse(success(runnable)); // } // // static <T> RunProcessor<T> run(Consumer<T> consumer) { // return runOnResponse(success(consumer)); // } // // static <T1, T2> RunProcessor<Tuple2<T1, T2>> run(Consumer2<T1, T2> consumer) { // return runOnResponse(success(consumer)); // } // // static <T1, T2, T3> RunProcessor<Tuple3<T1, T2, T3>> run(Consumer3<T1, T2, T3> consumer) { // return runOnResponse(success(consumer)); // } // // static <T1, T2, T3, T4> RunProcessor<Tuple4<T1, T2, T3, T4>> run(Consumer4<T1, T2, T3, T4> consumer) { // return runOnResponse(success(consumer)); // } // // static <T1, T2, T3, T4, T5> RunProcessor<Tuple5<T1, T2, T3, T4, T5>> run(Consumer5<T1, T2, T3, T4, T5> consumer) { // return runOnResponse(success(consumer)); // } // // static <T> RunProcessor<T> runOnFail(Consumer<Throwable> consumer) { // return runOnResponse(failure(consumer)); // } // // }
import org.junit.ClassRule; import org.junit.Test; import org.junit.runner.RunWith; import io.vertx.core.Future; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import io.vertx.ext.unit.junit.RunTestOnContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import static io.dazraf.vertx.futures.Futures.when; import static io.dazraf.vertx.futures.processors.MapProcessor.map; import static io.dazraf.vertx.futures.processors.MapProcessor.mapOnResponse; import static io.dazraf.vertx.futures.processors.RunProcessor.*; import static io.vertx.core.Future.*;
package io.dazraf.vertx.futures.processors; @RunWith(VertxUnitRunner.class) public class MapProcessorTest { @ClassRule public static final RunTestOnContext vertxContext = new RunTestOnContext(); private static final String MSG = "message!"; @Test public void mapValueTest(TestContext context) { Async async = context.async();
// Path: src/main/java/io/dazraf/vertx/futures/Futures.java // static <T> Futures<T> when(Future<T> future) { // return FuturesImpl.when(future); // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/MapProcessor.java // static <T, R> MapProcessor<T, R> map(Function<T, R> function) { // return mapOnResponse(future -> { // if (future.succeeded()) { // return function.apply(future.result()); // } else { // throw new WrappedException(future.cause()); // } // }); // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/MapProcessor.java // static <T, R> MapProcessor<T, R> mapOnResponse(Function<AsyncResult<T>, R> function) { // return future -> { // try { // return succeededFuture(function.apply(future)); // } // catch (WrappedException err) { // return failedFuture(err.getCause()); // } // catch (Throwable err) { // return failedFuture(err); // } // }; // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/RunProcessor.java // public interface RunProcessor<T> extends FutureProcessor<T, T> { // // Logger LOG = getLogger(RunProcessor.class); // // /** // * Observe the state of the chain. Any exceptions from the consumer will cause the chain to fail. // * @param consumer // * @param <T> // * @return // */ // static <T> RunProcessor<T> runOnResponse(Handler<AsyncResult<T>> consumer) { // return future -> { // Future<T> result = Future.future(); // try { // consumer.handle(future); // result.completer().handle(future); // } catch (Throwable error) { // LOG.error("consumer function failed", error); // result.fail(error); // } // return result; // }; // } // // static <T> RunProcessor<T> run(Runnable runnable) { // return runOnResponse(success(runnable)); // } // // static <T> RunProcessor<T> run(Consumer<T> consumer) { // return runOnResponse(success(consumer)); // } // // static <T1, T2> RunProcessor<Tuple2<T1, T2>> run(Consumer2<T1, T2> consumer) { // return runOnResponse(success(consumer)); // } // // static <T1, T2, T3> RunProcessor<Tuple3<T1, T2, T3>> run(Consumer3<T1, T2, T3> consumer) { // return runOnResponse(success(consumer)); // } // // static <T1, T2, T3, T4> RunProcessor<Tuple4<T1, T2, T3, T4>> run(Consumer4<T1, T2, T3, T4> consumer) { // return runOnResponse(success(consumer)); // } // // static <T1, T2, T3, T4, T5> RunProcessor<Tuple5<T1, T2, T3, T4, T5>> run(Consumer5<T1, T2, T3, T4, T5> consumer) { // return runOnResponse(success(consumer)); // } // // static <T> RunProcessor<T> runOnFail(Consumer<Throwable> consumer) { // return runOnResponse(failure(consumer)); // } // // } // Path: src/test/java/io/dazraf/vertx/futures/processors/MapProcessorTest.java import org.junit.ClassRule; import org.junit.Test; import org.junit.runner.RunWith; import io.vertx.core.Future; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import io.vertx.ext.unit.junit.RunTestOnContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import static io.dazraf.vertx.futures.Futures.when; import static io.dazraf.vertx.futures.processors.MapProcessor.map; import static io.dazraf.vertx.futures.processors.MapProcessor.mapOnResponse; import static io.dazraf.vertx.futures.processors.RunProcessor.*; import static io.vertx.core.Future.*; package io.dazraf.vertx.futures.processors; @RunWith(VertxUnitRunner.class) public class MapProcessorTest { @ClassRule public static final RunTestOnContext vertxContext = new RunTestOnContext(); private static final String MSG = "message!"; @Test public void mapValueTest(TestContext context) { Async async = context.async();
when(futureMessage())
dazraf/vertx-futures
src/test/java/io/dazraf/vertx/futures/processors/MapProcessorTest.java
// Path: src/main/java/io/dazraf/vertx/futures/Futures.java // static <T> Futures<T> when(Future<T> future) { // return FuturesImpl.when(future); // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/MapProcessor.java // static <T, R> MapProcessor<T, R> map(Function<T, R> function) { // return mapOnResponse(future -> { // if (future.succeeded()) { // return function.apply(future.result()); // } else { // throw new WrappedException(future.cause()); // } // }); // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/MapProcessor.java // static <T, R> MapProcessor<T, R> mapOnResponse(Function<AsyncResult<T>, R> function) { // return future -> { // try { // return succeededFuture(function.apply(future)); // } // catch (WrappedException err) { // return failedFuture(err.getCause()); // } // catch (Throwable err) { // return failedFuture(err); // } // }; // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/RunProcessor.java // public interface RunProcessor<T> extends FutureProcessor<T, T> { // // Logger LOG = getLogger(RunProcessor.class); // // /** // * Observe the state of the chain. Any exceptions from the consumer will cause the chain to fail. // * @param consumer // * @param <T> // * @return // */ // static <T> RunProcessor<T> runOnResponse(Handler<AsyncResult<T>> consumer) { // return future -> { // Future<T> result = Future.future(); // try { // consumer.handle(future); // result.completer().handle(future); // } catch (Throwable error) { // LOG.error("consumer function failed", error); // result.fail(error); // } // return result; // }; // } // // static <T> RunProcessor<T> run(Runnable runnable) { // return runOnResponse(success(runnable)); // } // // static <T> RunProcessor<T> run(Consumer<T> consumer) { // return runOnResponse(success(consumer)); // } // // static <T1, T2> RunProcessor<Tuple2<T1, T2>> run(Consumer2<T1, T2> consumer) { // return runOnResponse(success(consumer)); // } // // static <T1, T2, T3> RunProcessor<Tuple3<T1, T2, T3>> run(Consumer3<T1, T2, T3> consumer) { // return runOnResponse(success(consumer)); // } // // static <T1, T2, T3, T4> RunProcessor<Tuple4<T1, T2, T3, T4>> run(Consumer4<T1, T2, T3, T4> consumer) { // return runOnResponse(success(consumer)); // } // // static <T1, T2, T3, T4, T5> RunProcessor<Tuple5<T1, T2, T3, T4, T5>> run(Consumer5<T1, T2, T3, T4, T5> consumer) { // return runOnResponse(success(consumer)); // } // // static <T> RunProcessor<T> runOnFail(Consumer<Throwable> consumer) { // return runOnResponse(failure(consumer)); // } // // }
import org.junit.ClassRule; import org.junit.Test; import org.junit.runner.RunWith; import io.vertx.core.Future; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import io.vertx.ext.unit.junit.RunTestOnContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import static io.dazraf.vertx.futures.Futures.when; import static io.dazraf.vertx.futures.processors.MapProcessor.map; import static io.dazraf.vertx.futures.processors.MapProcessor.mapOnResponse; import static io.dazraf.vertx.futures.processors.RunProcessor.*; import static io.vertx.core.Future.*;
package io.dazraf.vertx.futures.processors; @RunWith(VertxUnitRunner.class) public class MapProcessorTest { @ClassRule public static final RunTestOnContext vertxContext = new RunTestOnContext(); private static final String MSG = "message!"; @Test public void mapValueTest(TestContext context) { Async async = context.async(); when(futureMessage()) .then(run(val -> context.assertEquals(MSG, val)))
// Path: src/main/java/io/dazraf/vertx/futures/Futures.java // static <T> Futures<T> when(Future<T> future) { // return FuturesImpl.when(future); // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/MapProcessor.java // static <T, R> MapProcessor<T, R> map(Function<T, R> function) { // return mapOnResponse(future -> { // if (future.succeeded()) { // return function.apply(future.result()); // } else { // throw new WrappedException(future.cause()); // } // }); // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/MapProcessor.java // static <T, R> MapProcessor<T, R> mapOnResponse(Function<AsyncResult<T>, R> function) { // return future -> { // try { // return succeededFuture(function.apply(future)); // } // catch (WrappedException err) { // return failedFuture(err.getCause()); // } // catch (Throwable err) { // return failedFuture(err); // } // }; // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/RunProcessor.java // public interface RunProcessor<T> extends FutureProcessor<T, T> { // // Logger LOG = getLogger(RunProcessor.class); // // /** // * Observe the state of the chain. Any exceptions from the consumer will cause the chain to fail. // * @param consumer // * @param <T> // * @return // */ // static <T> RunProcessor<T> runOnResponse(Handler<AsyncResult<T>> consumer) { // return future -> { // Future<T> result = Future.future(); // try { // consumer.handle(future); // result.completer().handle(future); // } catch (Throwable error) { // LOG.error("consumer function failed", error); // result.fail(error); // } // return result; // }; // } // // static <T> RunProcessor<T> run(Runnable runnable) { // return runOnResponse(success(runnable)); // } // // static <T> RunProcessor<T> run(Consumer<T> consumer) { // return runOnResponse(success(consumer)); // } // // static <T1, T2> RunProcessor<Tuple2<T1, T2>> run(Consumer2<T1, T2> consumer) { // return runOnResponse(success(consumer)); // } // // static <T1, T2, T3> RunProcessor<Tuple3<T1, T2, T3>> run(Consumer3<T1, T2, T3> consumer) { // return runOnResponse(success(consumer)); // } // // static <T1, T2, T3, T4> RunProcessor<Tuple4<T1, T2, T3, T4>> run(Consumer4<T1, T2, T3, T4> consumer) { // return runOnResponse(success(consumer)); // } // // static <T1, T2, T3, T4, T5> RunProcessor<Tuple5<T1, T2, T3, T4, T5>> run(Consumer5<T1, T2, T3, T4, T5> consumer) { // return runOnResponse(success(consumer)); // } // // static <T> RunProcessor<T> runOnFail(Consumer<Throwable> consumer) { // return runOnResponse(failure(consumer)); // } // // } // Path: src/test/java/io/dazraf/vertx/futures/processors/MapProcessorTest.java import org.junit.ClassRule; import org.junit.Test; import org.junit.runner.RunWith; import io.vertx.core.Future; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import io.vertx.ext.unit.junit.RunTestOnContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import static io.dazraf.vertx.futures.Futures.when; import static io.dazraf.vertx.futures.processors.MapProcessor.map; import static io.dazraf.vertx.futures.processors.MapProcessor.mapOnResponse; import static io.dazraf.vertx.futures.processors.RunProcessor.*; import static io.vertx.core.Future.*; package io.dazraf.vertx.futures.processors; @RunWith(VertxUnitRunner.class) public class MapProcessorTest { @ClassRule public static final RunTestOnContext vertxContext = new RunTestOnContext(); private static final String MSG = "message!"; @Test public void mapValueTest(TestContext context) { Async async = context.async(); when(futureMessage()) .then(run(val -> context.assertEquals(MSG, val)))
.then(map(val -> val + val))
dazraf/vertx-futures
src/test/java/io/dazraf/vertx/futures/processors/MapProcessorTest.java
// Path: src/main/java/io/dazraf/vertx/futures/Futures.java // static <T> Futures<T> when(Future<T> future) { // return FuturesImpl.when(future); // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/MapProcessor.java // static <T, R> MapProcessor<T, R> map(Function<T, R> function) { // return mapOnResponse(future -> { // if (future.succeeded()) { // return function.apply(future.result()); // } else { // throw new WrappedException(future.cause()); // } // }); // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/MapProcessor.java // static <T, R> MapProcessor<T, R> mapOnResponse(Function<AsyncResult<T>, R> function) { // return future -> { // try { // return succeededFuture(function.apply(future)); // } // catch (WrappedException err) { // return failedFuture(err.getCause()); // } // catch (Throwable err) { // return failedFuture(err); // } // }; // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/RunProcessor.java // public interface RunProcessor<T> extends FutureProcessor<T, T> { // // Logger LOG = getLogger(RunProcessor.class); // // /** // * Observe the state of the chain. Any exceptions from the consumer will cause the chain to fail. // * @param consumer // * @param <T> // * @return // */ // static <T> RunProcessor<T> runOnResponse(Handler<AsyncResult<T>> consumer) { // return future -> { // Future<T> result = Future.future(); // try { // consumer.handle(future); // result.completer().handle(future); // } catch (Throwable error) { // LOG.error("consumer function failed", error); // result.fail(error); // } // return result; // }; // } // // static <T> RunProcessor<T> run(Runnable runnable) { // return runOnResponse(success(runnable)); // } // // static <T> RunProcessor<T> run(Consumer<T> consumer) { // return runOnResponse(success(consumer)); // } // // static <T1, T2> RunProcessor<Tuple2<T1, T2>> run(Consumer2<T1, T2> consumer) { // return runOnResponse(success(consumer)); // } // // static <T1, T2, T3> RunProcessor<Tuple3<T1, T2, T3>> run(Consumer3<T1, T2, T3> consumer) { // return runOnResponse(success(consumer)); // } // // static <T1, T2, T3, T4> RunProcessor<Tuple4<T1, T2, T3, T4>> run(Consumer4<T1, T2, T3, T4> consumer) { // return runOnResponse(success(consumer)); // } // // static <T1, T2, T3, T4, T5> RunProcessor<Tuple5<T1, T2, T3, T4, T5>> run(Consumer5<T1, T2, T3, T4, T5> consumer) { // return runOnResponse(success(consumer)); // } // // static <T> RunProcessor<T> runOnFail(Consumer<Throwable> consumer) { // return runOnResponse(failure(consumer)); // } // // }
import org.junit.ClassRule; import org.junit.Test; import org.junit.runner.RunWith; import io.vertx.core.Future; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import io.vertx.ext.unit.junit.RunTestOnContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import static io.dazraf.vertx.futures.Futures.when; import static io.dazraf.vertx.futures.processors.MapProcessor.map; import static io.dazraf.vertx.futures.processors.MapProcessor.mapOnResponse; import static io.dazraf.vertx.futures.processors.RunProcessor.*; import static io.vertx.core.Future.*;
context .assertEquals(MSG, val1).assertEquals(MSG, val2) .assertEquals(MSG, val3) .assertEquals(MSG, val4))) .then(map((val1, val2, val3, val4) -> val1 + val2 + val3 + val4)) .then(run(val -> context.assertEquals(MSG + MSG + MSG + MSG, val))) .then(run(async::complete)) .then(runOnFail(context::fail)); } @Test public void map5ValuesTest(TestContext context) { Async async = context.async(); when(futureMessage(), futureMessage(), futureMessage(), futureMessage(), futureMessage()) .then(run((val1, val2, val3, val4, val5) -> context .assertEquals(MSG, val1).assertEquals(MSG, val2) .assertEquals(MSG, val3) .assertEquals(MSG, val4) .assertEquals(MSG, val5))) .then(map((val1, val2, val3, val4, val5) -> val1 + val2 + val3 + val4 + val5)) .then(run(val -> context.assertEquals(MSG + MSG + MSG + MSG + MSG, val))) .then(run(async::complete)) .then(runOnFail(context::fail)); } @Test public void mapResponseTest(TestContext context) { Async async = context.async(); when(futureMessage(), futureMessage())
// Path: src/main/java/io/dazraf/vertx/futures/Futures.java // static <T> Futures<T> when(Future<T> future) { // return FuturesImpl.when(future); // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/MapProcessor.java // static <T, R> MapProcessor<T, R> map(Function<T, R> function) { // return mapOnResponse(future -> { // if (future.succeeded()) { // return function.apply(future.result()); // } else { // throw new WrappedException(future.cause()); // } // }); // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/MapProcessor.java // static <T, R> MapProcessor<T, R> mapOnResponse(Function<AsyncResult<T>, R> function) { // return future -> { // try { // return succeededFuture(function.apply(future)); // } // catch (WrappedException err) { // return failedFuture(err.getCause()); // } // catch (Throwable err) { // return failedFuture(err); // } // }; // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/RunProcessor.java // public interface RunProcessor<T> extends FutureProcessor<T, T> { // // Logger LOG = getLogger(RunProcessor.class); // // /** // * Observe the state of the chain. Any exceptions from the consumer will cause the chain to fail. // * @param consumer // * @param <T> // * @return // */ // static <T> RunProcessor<T> runOnResponse(Handler<AsyncResult<T>> consumer) { // return future -> { // Future<T> result = Future.future(); // try { // consumer.handle(future); // result.completer().handle(future); // } catch (Throwable error) { // LOG.error("consumer function failed", error); // result.fail(error); // } // return result; // }; // } // // static <T> RunProcessor<T> run(Runnable runnable) { // return runOnResponse(success(runnable)); // } // // static <T> RunProcessor<T> run(Consumer<T> consumer) { // return runOnResponse(success(consumer)); // } // // static <T1, T2> RunProcessor<Tuple2<T1, T2>> run(Consumer2<T1, T2> consumer) { // return runOnResponse(success(consumer)); // } // // static <T1, T2, T3> RunProcessor<Tuple3<T1, T2, T3>> run(Consumer3<T1, T2, T3> consumer) { // return runOnResponse(success(consumer)); // } // // static <T1, T2, T3, T4> RunProcessor<Tuple4<T1, T2, T3, T4>> run(Consumer4<T1, T2, T3, T4> consumer) { // return runOnResponse(success(consumer)); // } // // static <T1, T2, T3, T4, T5> RunProcessor<Tuple5<T1, T2, T3, T4, T5>> run(Consumer5<T1, T2, T3, T4, T5> consumer) { // return runOnResponse(success(consumer)); // } // // static <T> RunProcessor<T> runOnFail(Consumer<Throwable> consumer) { // return runOnResponse(failure(consumer)); // } // // } // Path: src/test/java/io/dazraf/vertx/futures/processors/MapProcessorTest.java import org.junit.ClassRule; import org.junit.Test; import org.junit.runner.RunWith; import io.vertx.core.Future; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import io.vertx.ext.unit.junit.RunTestOnContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import static io.dazraf.vertx.futures.Futures.when; import static io.dazraf.vertx.futures.processors.MapProcessor.map; import static io.dazraf.vertx.futures.processors.MapProcessor.mapOnResponse; import static io.dazraf.vertx.futures.processors.RunProcessor.*; import static io.vertx.core.Future.*; context .assertEquals(MSG, val1).assertEquals(MSG, val2) .assertEquals(MSG, val3) .assertEquals(MSG, val4))) .then(map((val1, val2, val3, val4) -> val1 + val2 + val3 + val4)) .then(run(val -> context.assertEquals(MSG + MSG + MSG + MSG, val))) .then(run(async::complete)) .then(runOnFail(context::fail)); } @Test public void map5ValuesTest(TestContext context) { Async async = context.async(); when(futureMessage(), futureMessage(), futureMessage(), futureMessage(), futureMessage()) .then(run((val1, val2, val3, val4, val5) -> context .assertEquals(MSG, val1).assertEquals(MSG, val2) .assertEquals(MSG, val3) .assertEquals(MSG, val4) .assertEquals(MSG, val5))) .then(map((val1, val2, val3, val4, val5) -> val1 + val2 + val3 + val4 + val5)) .then(run(val -> context.assertEquals(MSG + MSG + MSG + MSG + MSG, val))) .then(run(async::complete)) .then(runOnFail(context::fail)); } @Test public void mapResponseTest(TestContext context) { Async async = context.async(); when(futureMessage(), futureMessage())
.then(mapOnResponse(asyncResult -> {
dazraf/vertx-futures
src/test/java/io/dazraf/vertx/tuple/Tuple3Test.java
// Path: src/test/java/io/dazraf/vertx/TestUtils.java // public static boolean RESULT_BOOL = true; // // Path: src/test/java/io/dazraf/vertx/TestUtils.java // public static final int RESULT_INT = 42; // // Path: src/test/java/io/dazraf/vertx/TestUtils.java // public static final String RESULT_MSG = "result";
import org.junit.Test; import java.util.HashSet; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import static io.dazraf.vertx.TestUtils.RESULT_BOOL; import static io.dazraf.vertx.TestUtils.RESULT_INT; import static io.dazraf.vertx.TestUtils.RESULT_MSG; import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.*;
package io.dazraf.vertx.tuple; public class Tuple3Test { @Test public void createAndRetrieveTest() {
// Path: src/test/java/io/dazraf/vertx/TestUtils.java // public static boolean RESULT_BOOL = true; // // Path: src/test/java/io/dazraf/vertx/TestUtils.java // public static final int RESULT_INT = 42; // // Path: src/test/java/io/dazraf/vertx/TestUtils.java // public static final String RESULT_MSG = "result"; // Path: src/test/java/io/dazraf/vertx/tuple/Tuple3Test.java import org.junit.Test; import java.util.HashSet; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import static io.dazraf.vertx.TestUtils.RESULT_BOOL; import static io.dazraf.vertx.TestUtils.RESULT_INT; import static io.dazraf.vertx.TestUtils.RESULT_MSG; import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.*; package io.dazraf.vertx.tuple; public class Tuple3Test { @Test public void createAndRetrieveTest() {
final Tuple3<String, Integer, Boolean> t = Tuple.tuple(RESULT_MSG, RESULT_INT, RESULT_BOOL);
dazraf/vertx-futures
src/test/java/io/dazraf/vertx/tuple/Tuple3Test.java
// Path: src/test/java/io/dazraf/vertx/TestUtils.java // public static boolean RESULT_BOOL = true; // // Path: src/test/java/io/dazraf/vertx/TestUtils.java // public static final int RESULT_INT = 42; // // Path: src/test/java/io/dazraf/vertx/TestUtils.java // public static final String RESULT_MSG = "result";
import org.junit.Test; import java.util.HashSet; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import static io.dazraf.vertx.TestUtils.RESULT_BOOL; import static io.dazraf.vertx.TestUtils.RESULT_INT; import static io.dazraf.vertx.TestUtils.RESULT_MSG; import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.*;
package io.dazraf.vertx.tuple; public class Tuple3Test { @Test public void createAndRetrieveTest() {
// Path: src/test/java/io/dazraf/vertx/TestUtils.java // public static boolean RESULT_BOOL = true; // // Path: src/test/java/io/dazraf/vertx/TestUtils.java // public static final int RESULT_INT = 42; // // Path: src/test/java/io/dazraf/vertx/TestUtils.java // public static final String RESULT_MSG = "result"; // Path: src/test/java/io/dazraf/vertx/tuple/Tuple3Test.java import org.junit.Test; import java.util.HashSet; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import static io.dazraf.vertx.TestUtils.RESULT_BOOL; import static io.dazraf.vertx.TestUtils.RESULT_INT; import static io.dazraf.vertx.TestUtils.RESULT_MSG; import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.*; package io.dazraf.vertx.tuple; public class Tuple3Test { @Test public void createAndRetrieveTest() {
final Tuple3<String, Integer, Boolean> t = Tuple.tuple(RESULT_MSG, RESULT_INT, RESULT_BOOL);
dazraf/vertx-futures
src/test/java/io/dazraf/vertx/tuple/Tuple3Test.java
// Path: src/test/java/io/dazraf/vertx/TestUtils.java // public static boolean RESULT_BOOL = true; // // Path: src/test/java/io/dazraf/vertx/TestUtils.java // public static final int RESULT_INT = 42; // // Path: src/test/java/io/dazraf/vertx/TestUtils.java // public static final String RESULT_MSG = "result";
import org.junit.Test; import java.util.HashSet; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import static io.dazraf.vertx.TestUtils.RESULT_BOOL; import static io.dazraf.vertx.TestUtils.RESULT_INT; import static io.dazraf.vertx.TestUtils.RESULT_MSG; import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.*;
package io.dazraf.vertx.tuple; public class Tuple3Test { @Test public void createAndRetrieveTest() {
// Path: src/test/java/io/dazraf/vertx/TestUtils.java // public static boolean RESULT_BOOL = true; // // Path: src/test/java/io/dazraf/vertx/TestUtils.java // public static final int RESULT_INT = 42; // // Path: src/test/java/io/dazraf/vertx/TestUtils.java // public static final String RESULT_MSG = "result"; // Path: src/test/java/io/dazraf/vertx/tuple/Tuple3Test.java import org.junit.Test; import java.util.HashSet; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import static io.dazraf.vertx.TestUtils.RESULT_BOOL; import static io.dazraf.vertx.TestUtils.RESULT_INT; import static io.dazraf.vertx.TestUtils.RESULT_MSG; import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.*; package io.dazraf.vertx.tuple; public class Tuple3Test { @Test public void createAndRetrieveTest() {
final Tuple3<String, Integer, Boolean> t = Tuple.tuple(RESULT_MSG, RESULT_INT, RESULT_BOOL);
pedrovgs/Nox
nox/src/main/java/com/github/pedrovgs/nox/NoxItemCatalog.java
// Path: nox/src/main/java/com/github/pedrovgs/nox/imageloader/ImageLoader.java // public interface ImageLoader { // // /** // * Configures an url to be downloaded. // */ // ImageLoader load(String url); // // /** // * Configures a resource id to be loaded. // */ // ImageLoader load(Integer resourceId); // // /** // * Loads a placeholder using a resource id to be shown while the external resource is being // * downloaded. // */ // ImageLoader withPlaceholder(Integer placeholderId); // // /** // * Applies a circular transformation to transform the source bitmap into a circular one. // */ // ImageLoader useCircularTransformation(boolean useCircularTransformation); // // /** // * Changes the external resource size once it downloaded and before to notify the listener. // */ // ImageLoader size(int size); // // /** // * Configures a listener where the ImageLoader will notify once the resource be loaded. This // * method has to be called to start the resource download. The listener used can't be null. // */ // void notify(Listener listener); // // /** // * Pauses all the resource downloads associated to this library. // */ // void pause(); // // /** // * Resumes all the resource downloads associated to this library. // */ // void resume(); // // /** // * Cancels all the pending requests to download a resource. // */ // void cancelPendingRequests(); // // /** // * Declares some methods which will be called during the resource download process implemented by // * the ImageLoader. Use this interface to be notified when the placeholder and the final resource // * be ready to be used. // */ // interface Listener { // // void onPlaceholderLoaded(Drawable placeholder); // // void onImageLoaded(Bitmap image); // // void onError(); // // void onDrawableLoaded(Drawable drawable); // } // }
import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import com.github.pedrovgs.nox.imageloader.ImageLoader; import java.lang.ref.WeakReference; import java.util.List; import java.util.Observable;
/* * Copyright (C) 2015 Pedro Vicente Gomez Sanchez. * * 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 com.github.pedrovgs.nox; /** * Processes NoxItem instances to download the images or resources associated to a list of NoxItem * instances asynchronously. This object notifies the observers previously added when the resource * or the image associated to the NoxItem is ready to be used. * * @author Pedro Vicente Gomez Sanchez. */ class NoxItemCatalog extends Observable { private final List<NoxItem> noxItems; private final int noxItemSize;
// Path: nox/src/main/java/com/github/pedrovgs/nox/imageloader/ImageLoader.java // public interface ImageLoader { // // /** // * Configures an url to be downloaded. // */ // ImageLoader load(String url); // // /** // * Configures a resource id to be loaded. // */ // ImageLoader load(Integer resourceId); // // /** // * Loads a placeholder using a resource id to be shown while the external resource is being // * downloaded. // */ // ImageLoader withPlaceholder(Integer placeholderId); // // /** // * Applies a circular transformation to transform the source bitmap into a circular one. // */ // ImageLoader useCircularTransformation(boolean useCircularTransformation); // // /** // * Changes the external resource size once it downloaded and before to notify the listener. // */ // ImageLoader size(int size); // // /** // * Configures a listener where the ImageLoader will notify once the resource be loaded. This // * method has to be called to start the resource download. The listener used can't be null. // */ // void notify(Listener listener); // // /** // * Pauses all the resource downloads associated to this library. // */ // void pause(); // // /** // * Resumes all the resource downloads associated to this library. // */ // void resume(); // // /** // * Cancels all the pending requests to download a resource. // */ // void cancelPendingRequests(); // // /** // * Declares some methods which will be called during the resource download process implemented by // * the ImageLoader. Use this interface to be notified when the placeholder and the final resource // * be ready to be used. // */ // interface Listener { // // void onPlaceholderLoaded(Drawable placeholder); // // void onImageLoaded(Bitmap image); // // void onError(); // // void onDrawableLoaded(Drawable drawable); // } // } // Path: nox/src/main/java/com/github/pedrovgs/nox/NoxItemCatalog.java import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import com.github.pedrovgs.nox.imageloader.ImageLoader; import java.lang.ref.WeakReference; import java.util.List; import java.util.Observable; /* * Copyright (C) 2015 Pedro Vicente Gomez Sanchez. * * 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 com.github.pedrovgs.nox; /** * Processes NoxItem instances to download the images or resources associated to a list of NoxItem * instances asynchronously. This object notifies the observers previously added when the resource * or the image associated to the NoxItem is ready to be used. * * @author Pedro Vicente Gomez Sanchez. */ class NoxItemCatalog extends Observable { private final List<NoxItem> noxItems; private final int noxItemSize;
private final ImageLoader imageLoader;
pedrovgs/Nox
nox/src/test/java/com/github/pedrovgs/nox/NoxItemCatalogTest.java
// Path: nox/src/test/java/com/github/pedrovgs/nox/doubles/FakeImageLoader.java // public class FakeImageLoader implements ImageLoader { // // private String url; // private Integer resourceId; // private Integer placeholderId; // private Listener listener; // private boolean loadOnDemand; // // public FakeImageLoader() { // // } // // public FakeImageLoader(boolean loadOnDemand) { // this.loadOnDemand = loadOnDemand; // } // // @Override public ImageLoader load(String url) { // this.url = url; // return this; // } // // @Override public ImageLoader load(Integer resourceId) { // this.resourceId = resourceId; // return this; // } // // @Override public ImageLoader withPlaceholder(Integer placeholderId) { // this.placeholderId = placeholderId; // return this; // } // // @Override public ImageLoader useCircularTransformation(boolean useCircularTransformation) { // return this; // } // // @Override public ImageLoader size(int size) { // return this; // } // // @Override public void notify(Listener listener) { // this.listener = listener; // if (loadOnDemand) { // return; // } // Drawable fakeDrawable = placeholderId != null ? new ColorDrawable() : null; // listener.onPlaceholderLoaded(fakeDrawable); // // boolean hasResourceToLoad = url != null || resourceId != null; // Bitmap fakeBitmap = hasResourceToLoad ? Bitmap.createBitmap(1, 1, Bitmap.Config.ALPHA_8) : null; // listener.onImageLoaded(fakeBitmap); // } // // @Override public void pause() { // // } // // @Override public void resume() { // // } // // @Override public void cancelPendingRequests() { // // } // // public void forceLoad() { // loadOnDemand = false; // notify(listener); // } // // public void forceError() { // listener.onError(); // } // } // // Path: nox/src/main/java/com/github/pedrovgs/nox/imageloader/ImageLoader.java // public interface ImageLoader { // // /** // * Configures an url to be downloaded. // */ // ImageLoader load(String url); // // /** // * Configures a resource id to be loaded. // */ // ImageLoader load(Integer resourceId); // // /** // * Loads a placeholder using a resource id to be shown while the external resource is being // * downloaded. // */ // ImageLoader withPlaceholder(Integer placeholderId); // // /** // * Applies a circular transformation to transform the source bitmap into a circular one. // */ // ImageLoader useCircularTransformation(boolean useCircularTransformation); // // /** // * Changes the external resource size once it downloaded and before to notify the listener. // */ // ImageLoader size(int size); // // /** // * Configures a listener where the ImageLoader will notify once the resource be loaded. This // * method has to be called to start the resource download. The listener used can't be null. // */ // void notify(Listener listener); // // /** // * Pauses all the resource downloads associated to this library. // */ // void pause(); // // /** // * Resumes all the resource downloads associated to this library. // */ // void resume(); // // /** // * Cancels all the pending requests to download a resource. // */ // void cancelPendingRequests(); // // /** // * Declares some methods which will be called during the resource download process implemented by // * the ImageLoader. Use this interface to be notified when the placeholder and the final resource // * be ready to be used. // */ // interface Listener { // // void onPlaceholderLoaded(Drawable placeholder); // // void onImageLoaded(Bitmap image); // // void onError(); // // void onDrawableLoaded(Drawable drawable); // } // }
import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import com.github.pedrovgs.nox.doubles.FakeImageLoader; import com.github.pedrovgs.nox.imageloader.ImageLoader; import java.util.LinkedList; import java.util.List; import java.util.Observer; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.mockito.Spy; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify;
/* * Copyright (C) 2015 Pedro Vicente Gomez Sanchez. * * 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 com.github.pedrovgs.nox; /** * @author Pedro Vicente Gómez Sánchez. */ @Config(emulateSdk = 18) @RunWith(RobolectricTestRunner.class) public class NoxItemCatalogTest { private static final int ANY_NOX_ITEM_SIZE = 100; private static final String ANY_URL = "http://anyimage.com/1"; private static final String ANY_URL_2 = "http://anyimage.com/2"; private static final NoxItem ANY_NOX_ITEM = new NoxItem(ANY_URL); private static final Drawable ANY_PLACEHOLDER = new ColorDrawable(); private static final int ANY_PLACEHOLDER_ID = 2; private static final int ANY_RESOURCE_ID = 1; private static final boolean USE_CIRCULAR_TRANSFORMATION = true;
// Path: nox/src/test/java/com/github/pedrovgs/nox/doubles/FakeImageLoader.java // public class FakeImageLoader implements ImageLoader { // // private String url; // private Integer resourceId; // private Integer placeholderId; // private Listener listener; // private boolean loadOnDemand; // // public FakeImageLoader() { // // } // // public FakeImageLoader(boolean loadOnDemand) { // this.loadOnDemand = loadOnDemand; // } // // @Override public ImageLoader load(String url) { // this.url = url; // return this; // } // // @Override public ImageLoader load(Integer resourceId) { // this.resourceId = resourceId; // return this; // } // // @Override public ImageLoader withPlaceholder(Integer placeholderId) { // this.placeholderId = placeholderId; // return this; // } // // @Override public ImageLoader useCircularTransformation(boolean useCircularTransformation) { // return this; // } // // @Override public ImageLoader size(int size) { // return this; // } // // @Override public void notify(Listener listener) { // this.listener = listener; // if (loadOnDemand) { // return; // } // Drawable fakeDrawable = placeholderId != null ? new ColorDrawable() : null; // listener.onPlaceholderLoaded(fakeDrawable); // // boolean hasResourceToLoad = url != null || resourceId != null; // Bitmap fakeBitmap = hasResourceToLoad ? Bitmap.createBitmap(1, 1, Bitmap.Config.ALPHA_8) : null; // listener.onImageLoaded(fakeBitmap); // } // // @Override public void pause() { // // } // // @Override public void resume() { // // } // // @Override public void cancelPendingRequests() { // // } // // public void forceLoad() { // loadOnDemand = false; // notify(listener); // } // // public void forceError() { // listener.onError(); // } // } // // Path: nox/src/main/java/com/github/pedrovgs/nox/imageloader/ImageLoader.java // public interface ImageLoader { // // /** // * Configures an url to be downloaded. // */ // ImageLoader load(String url); // // /** // * Configures a resource id to be loaded. // */ // ImageLoader load(Integer resourceId); // // /** // * Loads a placeholder using a resource id to be shown while the external resource is being // * downloaded. // */ // ImageLoader withPlaceholder(Integer placeholderId); // // /** // * Applies a circular transformation to transform the source bitmap into a circular one. // */ // ImageLoader useCircularTransformation(boolean useCircularTransformation); // // /** // * Changes the external resource size once it downloaded and before to notify the listener. // */ // ImageLoader size(int size); // // /** // * Configures a listener where the ImageLoader will notify once the resource be loaded. This // * method has to be called to start the resource download. The listener used can't be null. // */ // void notify(Listener listener); // // /** // * Pauses all the resource downloads associated to this library. // */ // void pause(); // // /** // * Resumes all the resource downloads associated to this library. // */ // void resume(); // // /** // * Cancels all the pending requests to download a resource. // */ // void cancelPendingRequests(); // // /** // * Declares some methods which will be called during the resource download process implemented by // * the ImageLoader. Use this interface to be notified when the placeholder and the final resource // * be ready to be used. // */ // interface Listener { // // void onPlaceholderLoaded(Drawable placeholder); // // void onImageLoaded(Bitmap image); // // void onError(); // // void onDrawableLoaded(Drawable drawable); // } // } // Path: nox/src/test/java/com/github/pedrovgs/nox/NoxItemCatalogTest.java import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import com.github.pedrovgs.nox.doubles.FakeImageLoader; import com.github.pedrovgs.nox.imageloader.ImageLoader; import java.util.LinkedList; import java.util.List; import java.util.Observer; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.mockito.Spy; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; /* * Copyright (C) 2015 Pedro Vicente Gomez Sanchez. * * 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 com.github.pedrovgs.nox; /** * @author Pedro Vicente Gómez Sánchez. */ @Config(emulateSdk = 18) @RunWith(RobolectricTestRunner.class) public class NoxItemCatalogTest { private static final int ANY_NOX_ITEM_SIZE = 100; private static final String ANY_URL = "http://anyimage.com/1"; private static final String ANY_URL_2 = "http://anyimage.com/2"; private static final NoxItem ANY_NOX_ITEM = new NoxItem(ANY_URL); private static final Drawable ANY_PLACEHOLDER = new ColorDrawable(); private static final int ANY_PLACEHOLDER_ID = 2; private static final int ANY_RESOURCE_ID = 1; private static final boolean USE_CIRCULAR_TRANSFORMATION = true;
@Spy private ImageLoader imageLoader = new FakeImageLoader();
pedrovgs/Nox
nox/src/test/java/com/github/pedrovgs/nox/NoxItemCatalogTest.java
// Path: nox/src/test/java/com/github/pedrovgs/nox/doubles/FakeImageLoader.java // public class FakeImageLoader implements ImageLoader { // // private String url; // private Integer resourceId; // private Integer placeholderId; // private Listener listener; // private boolean loadOnDemand; // // public FakeImageLoader() { // // } // // public FakeImageLoader(boolean loadOnDemand) { // this.loadOnDemand = loadOnDemand; // } // // @Override public ImageLoader load(String url) { // this.url = url; // return this; // } // // @Override public ImageLoader load(Integer resourceId) { // this.resourceId = resourceId; // return this; // } // // @Override public ImageLoader withPlaceholder(Integer placeholderId) { // this.placeholderId = placeholderId; // return this; // } // // @Override public ImageLoader useCircularTransformation(boolean useCircularTransformation) { // return this; // } // // @Override public ImageLoader size(int size) { // return this; // } // // @Override public void notify(Listener listener) { // this.listener = listener; // if (loadOnDemand) { // return; // } // Drawable fakeDrawable = placeholderId != null ? new ColorDrawable() : null; // listener.onPlaceholderLoaded(fakeDrawable); // // boolean hasResourceToLoad = url != null || resourceId != null; // Bitmap fakeBitmap = hasResourceToLoad ? Bitmap.createBitmap(1, 1, Bitmap.Config.ALPHA_8) : null; // listener.onImageLoaded(fakeBitmap); // } // // @Override public void pause() { // // } // // @Override public void resume() { // // } // // @Override public void cancelPendingRequests() { // // } // // public void forceLoad() { // loadOnDemand = false; // notify(listener); // } // // public void forceError() { // listener.onError(); // } // } // // Path: nox/src/main/java/com/github/pedrovgs/nox/imageloader/ImageLoader.java // public interface ImageLoader { // // /** // * Configures an url to be downloaded. // */ // ImageLoader load(String url); // // /** // * Configures a resource id to be loaded. // */ // ImageLoader load(Integer resourceId); // // /** // * Loads a placeholder using a resource id to be shown while the external resource is being // * downloaded. // */ // ImageLoader withPlaceholder(Integer placeholderId); // // /** // * Applies a circular transformation to transform the source bitmap into a circular one. // */ // ImageLoader useCircularTransformation(boolean useCircularTransformation); // // /** // * Changes the external resource size once it downloaded and before to notify the listener. // */ // ImageLoader size(int size); // // /** // * Configures a listener where the ImageLoader will notify once the resource be loaded. This // * method has to be called to start the resource download. The listener used can't be null. // */ // void notify(Listener listener); // // /** // * Pauses all the resource downloads associated to this library. // */ // void pause(); // // /** // * Resumes all the resource downloads associated to this library. // */ // void resume(); // // /** // * Cancels all the pending requests to download a resource. // */ // void cancelPendingRequests(); // // /** // * Declares some methods which will be called during the resource download process implemented by // * the ImageLoader. Use this interface to be notified when the placeholder and the final resource // * be ready to be used. // */ // interface Listener { // // void onPlaceholderLoaded(Drawable placeholder); // // void onImageLoaded(Bitmap image); // // void onError(); // // void onDrawableLoaded(Drawable drawable); // } // }
import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import com.github.pedrovgs.nox.doubles.FakeImageLoader; import com.github.pedrovgs.nox.imageloader.ImageLoader; import java.util.LinkedList; import java.util.List; import java.util.Observer; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.mockito.Spy; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify;
/* * Copyright (C) 2015 Pedro Vicente Gomez Sanchez. * * 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 com.github.pedrovgs.nox; /** * @author Pedro Vicente Gómez Sánchez. */ @Config(emulateSdk = 18) @RunWith(RobolectricTestRunner.class) public class NoxItemCatalogTest { private static final int ANY_NOX_ITEM_SIZE = 100; private static final String ANY_URL = "http://anyimage.com/1"; private static final String ANY_URL_2 = "http://anyimage.com/2"; private static final NoxItem ANY_NOX_ITEM = new NoxItem(ANY_URL); private static final Drawable ANY_PLACEHOLDER = new ColorDrawable(); private static final int ANY_PLACEHOLDER_ID = 2; private static final int ANY_RESOURCE_ID = 1; private static final boolean USE_CIRCULAR_TRANSFORMATION = true;
// Path: nox/src/test/java/com/github/pedrovgs/nox/doubles/FakeImageLoader.java // public class FakeImageLoader implements ImageLoader { // // private String url; // private Integer resourceId; // private Integer placeholderId; // private Listener listener; // private boolean loadOnDemand; // // public FakeImageLoader() { // // } // // public FakeImageLoader(boolean loadOnDemand) { // this.loadOnDemand = loadOnDemand; // } // // @Override public ImageLoader load(String url) { // this.url = url; // return this; // } // // @Override public ImageLoader load(Integer resourceId) { // this.resourceId = resourceId; // return this; // } // // @Override public ImageLoader withPlaceholder(Integer placeholderId) { // this.placeholderId = placeholderId; // return this; // } // // @Override public ImageLoader useCircularTransformation(boolean useCircularTransformation) { // return this; // } // // @Override public ImageLoader size(int size) { // return this; // } // // @Override public void notify(Listener listener) { // this.listener = listener; // if (loadOnDemand) { // return; // } // Drawable fakeDrawable = placeholderId != null ? new ColorDrawable() : null; // listener.onPlaceholderLoaded(fakeDrawable); // // boolean hasResourceToLoad = url != null || resourceId != null; // Bitmap fakeBitmap = hasResourceToLoad ? Bitmap.createBitmap(1, 1, Bitmap.Config.ALPHA_8) : null; // listener.onImageLoaded(fakeBitmap); // } // // @Override public void pause() { // // } // // @Override public void resume() { // // } // // @Override public void cancelPendingRequests() { // // } // // public void forceLoad() { // loadOnDemand = false; // notify(listener); // } // // public void forceError() { // listener.onError(); // } // } // // Path: nox/src/main/java/com/github/pedrovgs/nox/imageloader/ImageLoader.java // public interface ImageLoader { // // /** // * Configures an url to be downloaded. // */ // ImageLoader load(String url); // // /** // * Configures a resource id to be loaded. // */ // ImageLoader load(Integer resourceId); // // /** // * Loads a placeholder using a resource id to be shown while the external resource is being // * downloaded. // */ // ImageLoader withPlaceholder(Integer placeholderId); // // /** // * Applies a circular transformation to transform the source bitmap into a circular one. // */ // ImageLoader useCircularTransformation(boolean useCircularTransformation); // // /** // * Changes the external resource size once it downloaded and before to notify the listener. // */ // ImageLoader size(int size); // // /** // * Configures a listener where the ImageLoader will notify once the resource be loaded. This // * method has to be called to start the resource download. The listener used can't be null. // */ // void notify(Listener listener); // // /** // * Pauses all the resource downloads associated to this library. // */ // void pause(); // // /** // * Resumes all the resource downloads associated to this library. // */ // void resume(); // // /** // * Cancels all the pending requests to download a resource. // */ // void cancelPendingRequests(); // // /** // * Declares some methods which will be called during the resource download process implemented by // * the ImageLoader. Use this interface to be notified when the placeholder and the final resource // * be ready to be used. // */ // interface Listener { // // void onPlaceholderLoaded(Drawable placeholder); // // void onImageLoaded(Bitmap image); // // void onError(); // // void onDrawableLoaded(Drawable drawable); // } // } // Path: nox/src/test/java/com/github/pedrovgs/nox/NoxItemCatalogTest.java import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import com.github.pedrovgs.nox.doubles.FakeImageLoader; import com.github.pedrovgs.nox.imageloader.ImageLoader; import java.util.LinkedList; import java.util.List; import java.util.Observer; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.mockito.Spy; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; /* * Copyright (C) 2015 Pedro Vicente Gomez Sanchez. * * 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 com.github.pedrovgs.nox; /** * @author Pedro Vicente Gómez Sánchez. */ @Config(emulateSdk = 18) @RunWith(RobolectricTestRunner.class) public class NoxItemCatalogTest { private static final int ANY_NOX_ITEM_SIZE = 100; private static final String ANY_URL = "http://anyimage.com/1"; private static final String ANY_URL_2 = "http://anyimage.com/2"; private static final NoxItem ANY_NOX_ITEM = new NoxItem(ANY_URL); private static final Drawable ANY_PLACEHOLDER = new ColorDrawable(); private static final int ANY_PLACEHOLDER_ID = 2; private static final int ANY_RESOURCE_ID = 1; private static final boolean USE_CIRCULAR_TRANSFORMATION = true;
@Spy private ImageLoader imageLoader = new FakeImageLoader();
pedrovgs/Nox
nox/src/test/java/com/github/pedrovgs/nox/shape/BoundaryShapeTest.java
// Path: nox/src/test/java/com/github/pedrovgs/nox/doubles/FakeShape.java // public class FakeShape extends Shape { // // private float xPosition; // private float yPosition; // private int overSize; // // public FakeShape(ShapeConfig shapeConfig) { // super(shapeConfig); // } // // public void setXPosition(float xPosition) { // this.xPosition = xPosition; // } // // public void setYPosition(float yPosition) { // this.yPosition = yPosition; // } // // @Override public void calculate() { // for (int i = 0; i < getShapeConfig().getNumberOfElements(); i++) { // setNoxItemXPosition(i, xPosition); // setNoxItemYPosition(i, yPosition); // } // } // // public void setBoundaries(int minX, int maxX, int minY, int maxY, int overSize) { // setNoxItemXPosition(0, minX); // setNoxItemXPosition(0, maxX); // setNoxItemYPosition(0, minY); // setNoxItemYPosition(0, maxY); // this.overSize = overSize; // } // // @Override public int getOverSize() { // return overSize; // } // }
import com.github.pedrovgs.nox.doubles.FakeShape; import org.junit.Before; import org.junit.Test; import static junit.framework.Assert.assertTrue; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse;
/* * Copyright (C) 2015 Pedro Vicente Gomez Sanchez. * * 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 com.github.pedrovgs.nox.shape; /** * @author Pedro Vicente Gomez Sanchez. */ public class BoundaryShapeTest { private static final int ANY_VIEW_WIDTH = 100; private static final int ANY_VIEW_HEIGHT = 100; private static final float ANY_ITEM_SIZE = 8; private static final float ANY_ITEM_MARGIN = 2; private static final float ANY_X_POSITION = 1; private static final double DELTA = 0.1; private static final float ANY_Y_POSITION = 1; private static final int ANY_ITEM_POSITION = 0; private static final int ANY_BIG_OFFSET = 1000;
// Path: nox/src/test/java/com/github/pedrovgs/nox/doubles/FakeShape.java // public class FakeShape extends Shape { // // private float xPosition; // private float yPosition; // private int overSize; // // public FakeShape(ShapeConfig shapeConfig) { // super(shapeConfig); // } // // public void setXPosition(float xPosition) { // this.xPosition = xPosition; // } // // public void setYPosition(float yPosition) { // this.yPosition = yPosition; // } // // @Override public void calculate() { // for (int i = 0; i < getShapeConfig().getNumberOfElements(); i++) { // setNoxItemXPosition(i, xPosition); // setNoxItemYPosition(i, yPosition); // } // } // // public void setBoundaries(int minX, int maxX, int minY, int maxY, int overSize) { // setNoxItemXPosition(0, minX); // setNoxItemXPosition(0, maxX); // setNoxItemYPosition(0, minY); // setNoxItemYPosition(0, maxY); // this.overSize = overSize; // } // // @Override public int getOverSize() { // return overSize; // } // } // Path: nox/src/test/java/com/github/pedrovgs/nox/shape/BoundaryShapeTest.java import com.github.pedrovgs.nox.doubles.FakeShape; import org.junit.Before; import org.junit.Test; import static junit.framework.Assert.assertTrue; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; /* * Copyright (C) 2015 Pedro Vicente Gomez Sanchez. * * 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 com.github.pedrovgs.nox.shape; /** * @author Pedro Vicente Gomez Sanchez. */ public class BoundaryShapeTest { private static final int ANY_VIEW_WIDTH = 100; private static final int ANY_VIEW_HEIGHT = 100; private static final float ANY_ITEM_SIZE = 8; private static final float ANY_ITEM_MARGIN = 2; private static final float ANY_X_POSITION = 1; private static final double DELTA = 0.1; private static final float ANY_Y_POSITION = 1; private static final int ANY_ITEM_POSITION = 0; private static final int ANY_BIG_OFFSET = 1000;
private FakeShape path;
pedrovgs/Nox
nox/src/main/java/com/github/pedrovgs/nox/imageloader/PicassoImageLoader.java
// Path: nox/src/main/java/com/github/pedrovgs/nox/imageloader/transformation/CircleTransformation.java // public class CircleTransformation implements Transformation { // // @Override public Bitmap transform(Bitmap source) { // int size = Math.min(source.getWidth(), source.getHeight()); // int x = (source.getWidth() - size) / 2; // int y = (source.getHeight() - size) / 2; // Bitmap squaredBitmap = Bitmap.createBitmap(source, x, y, size, size); // if (squaredBitmap != source) { // source.recycle(); // } // Bitmap bitmap = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888); // Canvas canvas = new Canvas(bitmap); // Paint paint = new Paint(); // BitmapShader shader = // new BitmapShader(squaredBitmap, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP); // paint.setShader(shader); // paint.setAntiAlias(true); // float r = size / 2f; // canvas.drawCircle(r, r, r, paint); // squaredBitmap.recycle(); // return bitmap; // } // // @Override public String key() { // return "Circle_Transformation"; // } // }
import android.content.Context; import android.content.res.Resources; import android.graphics.drawable.Drawable; import com.github.pedrovgs.nox.imageloader.transformation.CircleTransformation; import com.squareup.picasso.Picasso; import com.squareup.picasso.RequestCreator; import com.squareup.picasso.Transformation; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.WeakHashMap;
* notifies when the resource has been downloaded. * * Listener and Target instances are going to be stored into a WeakHashMap to avoid a memory leak * when ImageLoader client code is garbage collected. */ private ListenerTarget getLinearTarget(final Listener listener) { ListenerTarget target = targets.get(listener); if (target == null) { target = new ListenerTarget(listener); targets.put(listener, target); } return target; } private RequestCreator applyPlaceholder(RequestCreator bitmapRequest) { if (placeholderId != null) { bitmapRequest.placeholder(placeholderId); } return bitmapRequest; } /** * Lazy instantiation of the list of transformations used during the image download. This method * returns a List<Transformation> because Picasso doesn't support a null instance as * transformation. */ private List<Transformation> getTransformations() { if (transformations == null) { transformations = new LinkedList<Transformation>(); if (useCircularTransformation) {
// Path: nox/src/main/java/com/github/pedrovgs/nox/imageloader/transformation/CircleTransformation.java // public class CircleTransformation implements Transformation { // // @Override public Bitmap transform(Bitmap source) { // int size = Math.min(source.getWidth(), source.getHeight()); // int x = (source.getWidth() - size) / 2; // int y = (source.getHeight() - size) / 2; // Bitmap squaredBitmap = Bitmap.createBitmap(source, x, y, size, size); // if (squaredBitmap != source) { // source.recycle(); // } // Bitmap bitmap = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888); // Canvas canvas = new Canvas(bitmap); // Paint paint = new Paint(); // BitmapShader shader = // new BitmapShader(squaredBitmap, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP); // paint.setShader(shader); // paint.setAntiAlias(true); // float r = size / 2f; // canvas.drawCircle(r, r, r, paint); // squaredBitmap.recycle(); // return bitmap; // } // // @Override public String key() { // return "Circle_Transformation"; // } // } // Path: nox/src/main/java/com/github/pedrovgs/nox/imageloader/PicassoImageLoader.java import android.content.Context; import android.content.res.Resources; import android.graphics.drawable.Drawable; import com.github.pedrovgs.nox.imageloader.transformation.CircleTransformation; import com.squareup.picasso.Picasso; import com.squareup.picasso.RequestCreator; import com.squareup.picasso.Transformation; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.WeakHashMap; * notifies when the resource has been downloaded. * * Listener and Target instances are going to be stored into a WeakHashMap to avoid a memory leak * when ImageLoader client code is garbage collected. */ private ListenerTarget getLinearTarget(final Listener listener) { ListenerTarget target = targets.get(listener); if (target == null) { target = new ListenerTarget(listener); targets.put(listener, target); } return target; } private RequestCreator applyPlaceholder(RequestCreator bitmapRequest) { if (placeholderId != null) { bitmapRequest.placeholder(placeholderId); } return bitmapRequest; } /** * Lazy instantiation of the list of transformations used during the image download. This method * returns a List<Transformation> because Picasso doesn't support a null instance as * transformation. */ private List<Transformation> getTransformations() { if (transformations == null) { transformations = new LinkedList<Transformation>(); if (useCircularTransformation) {
transformations.add(new CircleTransformation());
AgNO3/jcifs-ng
src/main/java/jcifs/dcerpc/msrpc/LsarSidArrayX.java
// Path: src/main/java/jcifs/dcerpc/rpc.java // public static class sid_t extends NdrObject { // // public byte revision; // public byte sub_authority_count; // public byte[] identifier_authority; // public int[] sub_authority; // // // @Override // public void encode ( NdrBuffer _dst ) throws NdrException { // _dst.align(4); // int _sub_authoritys = this.sub_authority_count; // _dst.enc_ndr_long(_sub_authoritys); // _dst.enc_ndr_small(this.revision); // _dst.enc_ndr_small(this.sub_authority_count); // int _identifier_authoritys = 6; // int _identifier_authorityi = _dst.index; // _dst.advance(1 * _identifier_authoritys); // int _sub_authorityi = _dst.index; // _dst.advance(4 * _sub_authoritys); // // _dst = _dst.derive(_identifier_authorityi); // for ( int _i = 0; _i < _identifier_authoritys; _i++ ) { // _dst.enc_ndr_small(this.identifier_authority[ _i ]); // } // _dst = _dst.derive(_sub_authorityi); // for ( int _i = 0; _i < _sub_authoritys; _i++ ) { // _dst.enc_ndr_long(this.sub_authority[ _i ]); // } // } // // // @Override // public void decode ( NdrBuffer _src ) throws NdrException { // _src.align(4); // int _sub_authoritys = _src.dec_ndr_long(); // this.revision = (byte) _src.dec_ndr_small(); // this.sub_authority_count = (byte) _src.dec_ndr_small(); // int _identifier_authoritys = 6; // int _identifier_authorityi = _src.index; // _src.advance(1 * _identifier_authoritys); // int _sub_authorityi = _src.index; // _src.advance(4 * _sub_authoritys); // // if ( this.identifier_authority == null ) { // if ( _identifier_authoritys < 0 || _identifier_authoritys > 0xFFFF ) // throw new NdrException(NdrException.INVALID_CONFORMANCE); // this.identifier_authority = new byte[_identifier_authoritys]; // } // _src = _src.derive(_identifier_authorityi); // for ( int _i = 0; _i < _identifier_authoritys; _i++ ) { // this.identifier_authority[ _i ] = (byte) _src.dec_ndr_small(); // } // if ( this.sub_authority == null ) { // if ( _sub_authoritys < 0 || _sub_authoritys > 0xFFFF ) // throw new NdrException(NdrException.INVALID_CONFORMANCE); // this.sub_authority = new int[_sub_authoritys]; // } // _src = _src.derive(_sub_authorityi); // for ( int _i = 0; _i < _sub_authoritys; _i++ ) { // this.sub_authority[ _i ] = _src.dec_ndr_long(); // } // } // }
import jcifs.dcerpc.rpc.sid_t; import jcifs.smb.SID;
/* * * This library 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 2.1 of the License, or (at your option) any later version. * * This library 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 this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package jcifs.dcerpc.msrpc; class LsarSidArrayX extends lsarpc.LsarSidArray { LsarSidArrayX ( jcifs.SID[] sids ) { this.num_sids = sids.length; this.sids = new lsarpc.LsarSidPtr[sids.length]; for ( int si = 0; si < sids.length; si++ ) { this.sids[ si ] = new lsarpc.LsarSidPtr();
// Path: src/main/java/jcifs/dcerpc/rpc.java // public static class sid_t extends NdrObject { // // public byte revision; // public byte sub_authority_count; // public byte[] identifier_authority; // public int[] sub_authority; // // // @Override // public void encode ( NdrBuffer _dst ) throws NdrException { // _dst.align(4); // int _sub_authoritys = this.sub_authority_count; // _dst.enc_ndr_long(_sub_authoritys); // _dst.enc_ndr_small(this.revision); // _dst.enc_ndr_small(this.sub_authority_count); // int _identifier_authoritys = 6; // int _identifier_authorityi = _dst.index; // _dst.advance(1 * _identifier_authoritys); // int _sub_authorityi = _dst.index; // _dst.advance(4 * _sub_authoritys); // // _dst = _dst.derive(_identifier_authorityi); // for ( int _i = 0; _i < _identifier_authoritys; _i++ ) { // _dst.enc_ndr_small(this.identifier_authority[ _i ]); // } // _dst = _dst.derive(_sub_authorityi); // for ( int _i = 0; _i < _sub_authoritys; _i++ ) { // _dst.enc_ndr_long(this.sub_authority[ _i ]); // } // } // // // @Override // public void decode ( NdrBuffer _src ) throws NdrException { // _src.align(4); // int _sub_authoritys = _src.dec_ndr_long(); // this.revision = (byte) _src.dec_ndr_small(); // this.sub_authority_count = (byte) _src.dec_ndr_small(); // int _identifier_authoritys = 6; // int _identifier_authorityi = _src.index; // _src.advance(1 * _identifier_authoritys); // int _sub_authorityi = _src.index; // _src.advance(4 * _sub_authoritys); // // if ( this.identifier_authority == null ) { // if ( _identifier_authoritys < 0 || _identifier_authoritys > 0xFFFF ) // throw new NdrException(NdrException.INVALID_CONFORMANCE); // this.identifier_authority = new byte[_identifier_authoritys]; // } // _src = _src.derive(_identifier_authorityi); // for ( int _i = 0; _i < _identifier_authoritys; _i++ ) { // this.identifier_authority[ _i ] = (byte) _src.dec_ndr_small(); // } // if ( this.sub_authority == null ) { // if ( _sub_authoritys < 0 || _sub_authoritys > 0xFFFF ) // throw new NdrException(NdrException.INVALID_CONFORMANCE); // this.sub_authority = new int[_sub_authoritys]; // } // _src = _src.derive(_sub_authorityi); // for ( int _i = 0; _i < _sub_authoritys; _i++ ) { // this.sub_authority[ _i ] = _src.dec_ndr_long(); // } // } // } // Path: src/main/java/jcifs/dcerpc/msrpc/LsarSidArrayX.java import jcifs.dcerpc.rpc.sid_t; import jcifs.smb.SID; /* * * This library 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 2.1 of the License, or (at your option) any later version. * * This library 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 this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package jcifs.dcerpc.msrpc; class LsarSidArrayX extends lsarpc.LsarSidArray { LsarSidArrayX ( jcifs.SID[] sids ) { this.num_sids = sids.length; this.sids = new lsarpc.LsarSidPtr[sids.length]; for ( int si = 0; si < sids.length; si++ ) { this.sids[ si ] = new lsarpc.LsarSidPtr();
this.sids[ si ].sid = sids[ si ].unwrap(sid_t.class);
AgNO3/jcifs-ng
src/main/java/jcifs/internal/smb2/info/Smb2QueryInfoRequest.java
// Path: src/main/java/jcifs/internal/smb2/Smb2Constants.java // public final class Smb2Constants { // // /** // * // */ // private Smb2Constants () {} // // /** // * // */ // public static final int SMB2_HEADER_LENGTH = 64; // // /** // * // */ // public static final int SMB2_NEGOTIATE_SIGNING_ENABLED = 0x0001; // // /** // * // */ // public static final int SMB2_NEGOTIATE_SIGNING_REQUIRED = 0x0002; // // /** // * // */ // public static final int SMB2_DIALECT_0202 = 0x0202; // // /** // * // */ // public static final int SMB2_DIALECT_0210 = 0x0210; // // /** // * // */ // public static final int SMB2_DIALECT_0300 = 0x0300; // // /** // * // */ // public static final int SMB2_DIALECT_0302 = 0x0302; // // /** // * // */ // public static final int SMB2_DIALECT_0311 = 0x0311; // // /** // * // */ // public static final int SMB2_DIALECT_ANY = 0x02FF; // // /** // * // */ // public static final int SMB2_GLOBAL_CAP_DFS = 0x1; // // /** // * // */ // public static final int SMB2_GLOBAL_CAP_LEASING = 0x2; // // /** // * // */ // public static final int SMB2_GLOBAL_CAP_LARGE_MTU = 0x4; // // /** // * // */ // public static final int SMB2_GLOBAL_CAP_MULTI_CHANNEL = 0x8; // // /** // * // */ // public static final int SMB2_GLOBAL_CAP_PERSISTENT_HANDLES = 0x10; // // /** // * // */ // public static final int SMB2_GLOBAL_CAP_DIRECTORY_LEASING = 0x20; // // /** // * // */ // public static final int SMB2_GLOBAL_CAP_ENCRYPTION = 0x40; // // /** // * // */ // public static final byte SMB2_0_INFO_FILE = 1; // // /** // * // */ // public static final byte SMB2_0_INFO_FILESYSTEM = 2; // // /** // * // */ // public static final byte SMB2_0_INFO_SECURITY = 3; // // /** // * // */ // public static final byte SMB2_0_INFO_QUOTA = 4; // // /** // * // */ // public static final byte[] UNSPECIFIED_FILEID = new byte[] { // (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, // (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF // }; // // /** // * // */ // public static final int UNSPECIFIED_TREEID = 0xFFFFFFFF; // // /** // * // */ // public static final long UNSPECIFIED_SESSIONID = 0xFFFFFFFFFFFFFFFFL; // }
import jcifs.CIFSContext; import jcifs.Configuration; import jcifs.Encodable; import jcifs.internal.smb2.RequestWithFileId; import jcifs.internal.smb2.ServerMessageBlock2Request; import jcifs.internal.smb2.Smb2Constants; import jcifs.internal.util.SMBUtil;
/* * © 2017 AgNO3 Gmbh & Co. KG * * This library 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 2.1 of the License, or (at your option) any later version. * * This library 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 this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package jcifs.internal.smb2.info; /** * @author mbechler * */ public class Smb2QueryInfoRequest extends ServerMessageBlock2Request<Smb2QueryInfoResponse> implements RequestWithFileId { private byte infoType; private byte fileInfoClass; private int outputBufferLength; private int additionalInformation; private int queryFlags; private byte[] fileId; private Encodable inputBuffer; /** * @param config */ public Smb2QueryInfoRequest ( Configuration config ) {
// Path: src/main/java/jcifs/internal/smb2/Smb2Constants.java // public final class Smb2Constants { // // /** // * // */ // private Smb2Constants () {} // // /** // * // */ // public static final int SMB2_HEADER_LENGTH = 64; // // /** // * // */ // public static final int SMB2_NEGOTIATE_SIGNING_ENABLED = 0x0001; // // /** // * // */ // public static final int SMB2_NEGOTIATE_SIGNING_REQUIRED = 0x0002; // // /** // * // */ // public static final int SMB2_DIALECT_0202 = 0x0202; // // /** // * // */ // public static final int SMB2_DIALECT_0210 = 0x0210; // // /** // * // */ // public static final int SMB2_DIALECT_0300 = 0x0300; // // /** // * // */ // public static final int SMB2_DIALECT_0302 = 0x0302; // // /** // * // */ // public static final int SMB2_DIALECT_0311 = 0x0311; // // /** // * // */ // public static final int SMB2_DIALECT_ANY = 0x02FF; // // /** // * // */ // public static final int SMB2_GLOBAL_CAP_DFS = 0x1; // // /** // * // */ // public static final int SMB2_GLOBAL_CAP_LEASING = 0x2; // // /** // * // */ // public static final int SMB2_GLOBAL_CAP_LARGE_MTU = 0x4; // // /** // * // */ // public static final int SMB2_GLOBAL_CAP_MULTI_CHANNEL = 0x8; // // /** // * // */ // public static final int SMB2_GLOBAL_CAP_PERSISTENT_HANDLES = 0x10; // // /** // * // */ // public static final int SMB2_GLOBAL_CAP_DIRECTORY_LEASING = 0x20; // // /** // * // */ // public static final int SMB2_GLOBAL_CAP_ENCRYPTION = 0x40; // // /** // * // */ // public static final byte SMB2_0_INFO_FILE = 1; // // /** // * // */ // public static final byte SMB2_0_INFO_FILESYSTEM = 2; // // /** // * // */ // public static final byte SMB2_0_INFO_SECURITY = 3; // // /** // * // */ // public static final byte SMB2_0_INFO_QUOTA = 4; // // /** // * // */ // public static final byte[] UNSPECIFIED_FILEID = new byte[] { // (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, // (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF // }; // // /** // * // */ // public static final int UNSPECIFIED_TREEID = 0xFFFFFFFF; // // /** // * // */ // public static final long UNSPECIFIED_SESSIONID = 0xFFFFFFFFFFFFFFFFL; // } // Path: src/main/java/jcifs/internal/smb2/info/Smb2QueryInfoRequest.java import jcifs.CIFSContext; import jcifs.Configuration; import jcifs.Encodable; import jcifs.internal.smb2.RequestWithFileId; import jcifs.internal.smb2.ServerMessageBlock2Request; import jcifs.internal.smb2.Smb2Constants; import jcifs.internal.util.SMBUtil; /* * © 2017 AgNO3 Gmbh & Co. KG * * This library 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 2.1 of the License, or (at your option) any later version. * * This library 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 this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package jcifs.internal.smb2.info; /** * @author mbechler * */ public class Smb2QueryInfoRequest extends ServerMessageBlock2Request<Smb2QueryInfoResponse> implements RequestWithFileId { private byte infoType; private byte fileInfoClass; private int outputBufferLength; private int additionalInformation; private int queryFlags; private byte[] fileId; private Encodable inputBuffer; /** * @param config */ public Smb2QueryInfoRequest ( Configuration config ) {
this(config, Smb2Constants.UNSPECIFIED_FILEID);
AgNO3/jcifs-ng
src/main/java/jcifs/pac/kerberos/KerberosRelevantAuthData.java
// Path: src/main/java/jcifs/pac/ASN1Util.java // public final class ASN1Util { // // private ASN1Util () {} // // // /** // * // * @param type // * @param object // * @return object cast to type // * @throws PACDecodingException // */ // public static <T> T as ( Class<T> type, Object object ) throws PACDecodingException { // if ( !type.isInstance(object) ) { // throw new PACDecodingException("Incompatible object types " + type + " " + object.getClass()); // } // // return type.cast(object); // } // // // /** // * // * @param type // * @param enumeration // * @return next element from enumeration cast to type // * @throws PACDecodingException // */ // public static <T extends Object> T as ( Class<T> type, Enumeration<?> enumeration ) throws PACDecodingException { // return as(type, enumeration.nextElement()); // } // // // /** // * // * @param type // * @param stream // * @return next object from stream cast to type // * @throws PACDecodingException // * @throws IOException // */ // public static <T extends ASN1Primitive> T as ( Class<T> type, ASN1InputStream stream ) throws PACDecodingException, IOException { // return as(type, stream.readObject()); // } // // // /** // * // * @param type // * @param tagged // * @return tagged object contents cast to type // * @throws PACDecodingException // */ // public static <T extends ASN1Primitive> T as ( Class<T> type, ASN1TaggedObject tagged ) throws PACDecodingException { // return as(type, tagged.getObject()); // } // // // /** // * // * @param type // * @param sequence // * @param index // * @return sequence element cast to type // * @throws PACDecodingException // */ // public static <T extends ASN1Primitive> T as ( Class<T> type, DLSequence sequence, int index ) throws PACDecodingException { // return as(type, sequence.getObjectAt(index)); // } // // }
import org.bouncycastle.asn1.DLSequence; import jcifs.pac.ASN1Util; import jcifs.pac.PACDecodingException; import java.io.ByteArrayInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.Map; import javax.security.auth.kerberos.KerberosKey; import org.bouncycastle.asn1.ASN1InputStream; import org.bouncycastle.asn1.ASN1Integer; import org.bouncycastle.asn1.DEROctetString; import org.bouncycastle.asn1.DERTaggedObject;
/* * * This library 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 2.1 of the License, or (at your option) any later version. * * This library 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 this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package jcifs.pac.kerberos; @SuppressWarnings ( "javadoc" ) public class KerberosRelevantAuthData extends KerberosAuthData { private List<KerberosAuthData> authorizations; public KerberosRelevantAuthData ( byte[] token, Map<Integer, KerberosKey> keys ) throws PACDecodingException { DLSequence authSequence; try { try ( ASN1InputStream stream = new ASN1InputStream(new ByteArrayInputStream(token)) ) {
// Path: src/main/java/jcifs/pac/ASN1Util.java // public final class ASN1Util { // // private ASN1Util () {} // // // /** // * // * @param type // * @param object // * @return object cast to type // * @throws PACDecodingException // */ // public static <T> T as ( Class<T> type, Object object ) throws PACDecodingException { // if ( !type.isInstance(object) ) { // throw new PACDecodingException("Incompatible object types " + type + " " + object.getClass()); // } // // return type.cast(object); // } // // // /** // * // * @param type // * @param enumeration // * @return next element from enumeration cast to type // * @throws PACDecodingException // */ // public static <T extends Object> T as ( Class<T> type, Enumeration<?> enumeration ) throws PACDecodingException { // return as(type, enumeration.nextElement()); // } // // // /** // * // * @param type // * @param stream // * @return next object from stream cast to type // * @throws PACDecodingException // * @throws IOException // */ // public static <T extends ASN1Primitive> T as ( Class<T> type, ASN1InputStream stream ) throws PACDecodingException, IOException { // return as(type, stream.readObject()); // } // // // /** // * // * @param type // * @param tagged // * @return tagged object contents cast to type // * @throws PACDecodingException // */ // public static <T extends ASN1Primitive> T as ( Class<T> type, ASN1TaggedObject tagged ) throws PACDecodingException { // return as(type, tagged.getObject()); // } // // // /** // * // * @param type // * @param sequence // * @param index // * @return sequence element cast to type // * @throws PACDecodingException // */ // public static <T extends ASN1Primitive> T as ( Class<T> type, DLSequence sequence, int index ) throws PACDecodingException { // return as(type, sequence.getObjectAt(index)); // } // // } // Path: src/main/java/jcifs/pac/kerberos/KerberosRelevantAuthData.java import org.bouncycastle.asn1.DLSequence; import jcifs.pac.ASN1Util; import jcifs.pac.PACDecodingException; import java.io.ByteArrayInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.Map; import javax.security.auth.kerberos.KerberosKey; import org.bouncycastle.asn1.ASN1InputStream; import org.bouncycastle.asn1.ASN1Integer; import org.bouncycastle.asn1.DEROctetString; import org.bouncycastle.asn1.DERTaggedObject; /* * * This library 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 2.1 of the License, or (at your option) any later version. * * This library 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 this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package jcifs.pac.kerberos; @SuppressWarnings ( "javadoc" ) public class KerberosRelevantAuthData extends KerberosAuthData { private List<KerberosAuthData> authorizations; public KerberosRelevantAuthData ( byte[] token, Map<Integer, KerberosKey> keys ) throws PACDecodingException { DLSequence authSequence; try { try ( ASN1InputStream stream = new ASN1InputStream(new ByteArrayInputStream(token)) ) {
authSequence = ASN1Util.as(DLSequence.class, stream);
AgNO3/jcifs-ng
src/main/java/jcifs/pac/kerberos/KerberosApRequest.java
// Path: src/main/java/jcifs/pac/ASN1Util.java // public final class ASN1Util { // // private ASN1Util () {} // // // /** // * // * @param type // * @param object // * @return object cast to type // * @throws PACDecodingException // */ // public static <T> T as ( Class<T> type, Object object ) throws PACDecodingException { // if ( !type.isInstance(object) ) { // throw new PACDecodingException("Incompatible object types " + type + " " + object.getClass()); // } // // return type.cast(object); // } // // // /** // * // * @param type // * @param enumeration // * @return next element from enumeration cast to type // * @throws PACDecodingException // */ // public static <T extends Object> T as ( Class<T> type, Enumeration<?> enumeration ) throws PACDecodingException { // return as(type, enumeration.nextElement()); // } // // // /** // * // * @param type // * @param stream // * @return next object from stream cast to type // * @throws PACDecodingException // * @throws IOException // */ // public static <T extends ASN1Primitive> T as ( Class<T> type, ASN1InputStream stream ) throws PACDecodingException, IOException { // return as(type, stream.readObject()); // } // // // /** // * // * @param type // * @param tagged // * @return tagged object contents cast to type // * @throws PACDecodingException // */ // public static <T extends ASN1Primitive> T as ( Class<T> type, ASN1TaggedObject tagged ) throws PACDecodingException { // return as(type, tagged.getObject()); // } // // // /** // * // * @param type // * @param sequence // * @param index // * @return sequence element cast to type // * @throws PACDecodingException // */ // public static <T extends ASN1Primitive> T as ( Class<T> type, DLSequence sequence, int index ) throws PACDecodingException { // return as(type, sequence.getObjectAt(index)); // } // // }
import jcifs.pac.ASN1Util; import jcifs.pac.PACDecodingException; import java.io.ByteArrayInputStream; import java.io.IOException; import java.math.BigInteger; import java.util.Enumeration; import javax.security.auth.kerberos.KerberosKey; import org.bouncycastle.asn1.ASN1InputStream; import org.bouncycastle.asn1.ASN1Integer; import org.bouncycastle.asn1.ASN1TaggedObject; import org.bouncycastle.asn1.DERApplicationSpecific; import org.bouncycastle.asn1.DERBitString; import org.bouncycastle.asn1.DLSequence;
/* * * This library 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 2.1 of the License, or (at your option) any later version. * * This library 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 this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package jcifs.pac.kerberos; @SuppressWarnings ( "javadoc" ) public class KerberosApRequest { private byte apOptions; private KerberosTicket ticket; public KerberosApRequest ( byte[] token, KerberosKey[] keys ) throws PACDecodingException { if ( token.length <= 0 ) throw new PACDecodingException("Empty kerberos ApReq"); DLSequence sequence; try { try ( ASN1InputStream stream = new ASN1InputStream(new ByteArrayInputStream(token)) ) {
// Path: src/main/java/jcifs/pac/ASN1Util.java // public final class ASN1Util { // // private ASN1Util () {} // // // /** // * // * @param type // * @param object // * @return object cast to type // * @throws PACDecodingException // */ // public static <T> T as ( Class<T> type, Object object ) throws PACDecodingException { // if ( !type.isInstance(object) ) { // throw new PACDecodingException("Incompatible object types " + type + " " + object.getClass()); // } // // return type.cast(object); // } // // // /** // * // * @param type // * @param enumeration // * @return next element from enumeration cast to type // * @throws PACDecodingException // */ // public static <T extends Object> T as ( Class<T> type, Enumeration<?> enumeration ) throws PACDecodingException { // return as(type, enumeration.nextElement()); // } // // // /** // * // * @param type // * @param stream // * @return next object from stream cast to type // * @throws PACDecodingException // * @throws IOException // */ // public static <T extends ASN1Primitive> T as ( Class<T> type, ASN1InputStream stream ) throws PACDecodingException, IOException { // return as(type, stream.readObject()); // } // // // /** // * // * @param type // * @param tagged // * @return tagged object contents cast to type // * @throws PACDecodingException // */ // public static <T extends ASN1Primitive> T as ( Class<T> type, ASN1TaggedObject tagged ) throws PACDecodingException { // return as(type, tagged.getObject()); // } // // // /** // * // * @param type // * @param sequence // * @param index // * @return sequence element cast to type // * @throws PACDecodingException // */ // public static <T extends ASN1Primitive> T as ( Class<T> type, DLSequence sequence, int index ) throws PACDecodingException { // return as(type, sequence.getObjectAt(index)); // } // // } // Path: src/main/java/jcifs/pac/kerberos/KerberosApRequest.java import jcifs.pac.ASN1Util; import jcifs.pac.PACDecodingException; import java.io.ByteArrayInputStream; import java.io.IOException; import java.math.BigInteger; import java.util.Enumeration; import javax.security.auth.kerberos.KerberosKey; import org.bouncycastle.asn1.ASN1InputStream; import org.bouncycastle.asn1.ASN1Integer; import org.bouncycastle.asn1.ASN1TaggedObject; import org.bouncycastle.asn1.DERApplicationSpecific; import org.bouncycastle.asn1.DERBitString; import org.bouncycastle.asn1.DLSequence; /* * * This library 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 2.1 of the License, or (at your option) any later version. * * This library 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 this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package jcifs.pac.kerberos; @SuppressWarnings ( "javadoc" ) public class KerberosApRequest { private byte apOptions; private KerberosTicket ticket; public KerberosApRequest ( byte[] token, KerberosKey[] keys ) throws PACDecodingException { if ( token.length <= 0 ) throw new PACDecodingException("Empty kerberos ApReq"); DLSequence sequence; try { try ( ASN1InputStream stream = new ASN1InputStream(new ByteArrayInputStream(token)) ) {
sequence = ASN1Util.as(DLSequence.class, stream);
AgNO3/jcifs-ng
src/main/java/jcifs/pac/kerberos/KerberosTicket.java
// Path: src/main/java/jcifs/pac/ASN1Util.java // public final class ASN1Util { // // private ASN1Util () {} // // // /** // * // * @param type // * @param object // * @return object cast to type // * @throws PACDecodingException // */ // public static <T> T as ( Class<T> type, Object object ) throws PACDecodingException { // if ( !type.isInstance(object) ) { // throw new PACDecodingException("Incompatible object types " + type + " " + object.getClass()); // } // // return type.cast(object); // } // // // /** // * // * @param type // * @param enumeration // * @return next element from enumeration cast to type // * @throws PACDecodingException // */ // public static <T extends Object> T as ( Class<T> type, Enumeration<?> enumeration ) throws PACDecodingException { // return as(type, enumeration.nextElement()); // } // // // /** // * // * @param type // * @param stream // * @return next object from stream cast to type // * @throws PACDecodingException // * @throws IOException // */ // public static <T extends ASN1Primitive> T as ( Class<T> type, ASN1InputStream stream ) throws PACDecodingException, IOException { // return as(type, stream.readObject()); // } // // // /** // * // * @param type // * @param tagged // * @return tagged object contents cast to type // * @throws PACDecodingException // */ // public static <T extends ASN1Primitive> T as ( Class<T> type, ASN1TaggedObject tagged ) throws PACDecodingException { // return as(type, tagged.getObject()); // } // // // /** // * // * @param type // * @param sequence // * @param index // * @return sequence element cast to type // * @throws PACDecodingException // */ // public static <T extends ASN1Primitive> T as ( Class<T> type, DLSequence sequence, int index ) throws PACDecodingException { // return as(type, sequence.getObjectAt(index)); // } // // }
import org.bouncycastle.asn1.ASN1TaggedObject; import org.bouncycastle.asn1.DERGeneralString; import org.bouncycastle.asn1.DEROctetString; import org.bouncycastle.asn1.DERTaggedObject; import org.bouncycastle.asn1.DLSequence; import jcifs.pac.ASN1Util; import jcifs.pac.PACDecodingException; import java.io.ByteArrayInputStream; import java.io.IOException; import java.math.BigInteger; import java.security.GeneralSecurityException; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import javax.security.auth.kerberos.KerberosKey; import javax.security.auth.login.LoginException; import org.bouncycastle.asn1.ASN1InputStream; import org.bouncycastle.asn1.ASN1Integer;
/* * * This library 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 2.1 of the License, or (at your option) any later version. * * This library 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 this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package jcifs.pac.kerberos; @SuppressWarnings ( "javadoc" ) public class KerberosTicket { private String serverPrincipalName; private String serverRealm; private KerberosEncData encData; public KerberosTicket ( byte[] token, byte apOptions, KerberosKey[] keys ) throws PACDecodingException { if ( token.length <= 0 ) throw new PACDecodingException("Empty kerberos ticket"); DLSequence sequence; try { try ( ASN1InputStream stream = new ASN1InputStream(new ByteArrayInputStream(token)) ) {
// Path: src/main/java/jcifs/pac/ASN1Util.java // public final class ASN1Util { // // private ASN1Util () {} // // // /** // * // * @param type // * @param object // * @return object cast to type // * @throws PACDecodingException // */ // public static <T> T as ( Class<T> type, Object object ) throws PACDecodingException { // if ( !type.isInstance(object) ) { // throw new PACDecodingException("Incompatible object types " + type + " " + object.getClass()); // } // // return type.cast(object); // } // // // /** // * // * @param type // * @param enumeration // * @return next element from enumeration cast to type // * @throws PACDecodingException // */ // public static <T extends Object> T as ( Class<T> type, Enumeration<?> enumeration ) throws PACDecodingException { // return as(type, enumeration.nextElement()); // } // // // /** // * // * @param type // * @param stream // * @return next object from stream cast to type // * @throws PACDecodingException // * @throws IOException // */ // public static <T extends ASN1Primitive> T as ( Class<T> type, ASN1InputStream stream ) throws PACDecodingException, IOException { // return as(type, stream.readObject()); // } // // // /** // * // * @param type // * @param tagged // * @return tagged object contents cast to type // * @throws PACDecodingException // */ // public static <T extends ASN1Primitive> T as ( Class<T> type, ASN1TaggedObject tagged ) throws PACDecodingException { // return as(type, tagged.getObject()); // } // // // /** // * // * @param type // * @param sequence // * @param index // * @return sequence element cast to type // * @throws PACDecodingException // */ // public static <T extends ASN1Primitive> T as ( Class<T> type, DLSequence sequence, int index ) throws PACDecodingException { // return as(type, sequence.getObjectAt(index)); // } // // } // Path: src/main/java/jcifs/pac/kerberos/KerberosTicket.java import org.bouncycastle.asn1.ASN1TaggedObject; import org.bouncycastle.asn1.DERGeneralString; import org.bouncycastle.asn1.DEROctetString; import org.bouncycastle.asn1.DERTaggedObject; import org.bouncycastle.asn1.DLSequence; import jcifs.pac.ASN1Util; import jcifs.pac.PACDecodingException; import java.io.ByteArrayInputStream; import java.io.IOException; import java.math.BigInteger; import java.security.GeneralSecurityException; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import javax.security.auth.kerberos.KerberosKey; import javax.security.auth.login.LoginException; import org.bouncycastle.asn1.ASN1InputStream; import org.bouncycastle.asn1.ASN1Integer; /* * * This library 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 2.1 of the License, or (at your option) any later version. * * This library 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 this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package jcifs.pac.kerberos; @SuppressWarnings ( "javadoc" ) public class KerberosTicket { private String serverPrincipalName; private String serverRealm; private KerberosEncData encData; public KerberosTicket ( byte[] token, byte apOptions, KerberosKey[] keys ) throws PACDecodingException { if ( token.length <= 0 ) throw new PACDecodingException("Empty kerberos ticket"); DLSequence sequence; try { try ( ASN1InputStream stream = new ASN1InputStream(new ByteArrayInputStream(token)) ) {
sequence = ASN1Util.as(DLSequence.class, stream);
AgNO3/jcifs-ng
src/main/java/jcifs/internal/smb2/info/Smb2QueryDirectoryRequest.java
// Path: src/main/java/jcifs/internal/smb2/Smb2Constants.java // public final class Smb2Constants { // // /** // * // */ // private Smb2Constants () {} // // /** // * // */ // public static final int SMB2_HEADER_LENGTH = 64; // // /** // * // */ // public static final int SMB2_NEGOTIATE_SIGNING_ENABLED = 0x0001; // // /** // * // */ // public static final int SMB2_NEGOTIATE_SIGNING_REQUIRED = 0x0002; // // /** // * // */ // public static final int SMB2_DIALECT_0202 = 0x0202; // // /** // * // */ // public static final int SMB2_DIALECT_0210 = 0x0210; // // /** // * // */ // public static final int SMB2_DIALECT_0300 = 0x0300; // // /** // * // */ // public static final int SMB2_DIALECT_0302 = 0x0302; // // /** // * // */ // public static final int SMB2_DIALECT_0311 = 0x0311; // // /** // * // */ // public static final int SMB2_DIALECT_ANY = 0x02FF; // // /** // * // */ // public static final int SMB2_GLOBAL_CAP_DFS = 0x1; // // /** // * // */ // public static final int SMB2_GLOBAL_CAP_LEASING = 0x2; // // /** // * // */ // public static final int SMB2_GLOBAL_CAP_LARGE_MTU = 0x4; // // /** // * // */ // public static final int SMB2_GLOBAL_CAP_MULTI_CHANNEL = 0x8; // // /** // * // */ // public static final int SMB2_GLOBAL_CAP_PERSISTENT_HANDLES = 0x10; // // /** // * // */ // public static final int SMB2_GLOBAL_CAP_DIRECTORY_LEASING = 0x20; // // /** // * // */ // public static final int SMB2_GLOBAL_CAP_ENCRYPTION = 0x40; // // /** // * // */ // public static final byte SMB2_0_INFO_FILE = 1; // // /** // * // */ // public static final byte SMB2_0_INFO_FILESYSTEM = 2; // // /** // * // */ // public static final byte SMB2_0_INFO_SECURITY = 3; // // /** // * // */ // public static final byte SMB2_0_INFO_QUOTA = 4; // // /** // * // */ // public static final byte[] UNSPECIFIED_FILEID = new byte[] { // (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, // (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF // }; // // /** // * // */ // public static final int UNSPECIFIED_TREEID = 0xFFFFFFFF; // // /** // * // */ // public static final long UNSPECIFIED_SESSIONID = 0xFFFFFFFFFFFFFFFFL; // }
import java.nio.charset.StandardCharsets; import jcifs.CIFSContext; import jcifs.Configuration; import jcifs.internal.smb2.RequestWithFileId; import jcifs.internal.smb2.ServerMessageBlock2Request; import jcifs.internal.smb2.Smb2Constants; import jcifs.internal.util.SMBUtil;
/* * © 2017 AgNO3 Gmbh & Co. KG * * This library 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 2.1 of the License, or (at your option) any later version. * * This library 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 this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package jcifs.internal.smb2.info; /** * @author mbechler * */ public class Smb2QueryDirectoryRequest extends ServerMessageBlock2Request<Smb2QueryDirectoryResponse> implements RequestWithFileId { /** * */ public static final byte FILE_DIRECTORY_INFO = 0x1; /** * */ public static final byte FILE_FULL_DIRECTORY_INFO = 0x2; /** * */ public static final byte FILE_BOTH_DIRECTORY_INFO = 0x03; /** * */ public static final byte FILE_NAMES_INFO = 0x0C; /** * */ public static final byte FILE_ID_BOTH_DIRECTORY_INFO = 0x24; /** * */ public static final byte FILE_ID_FULL_DIRECTORY_INFO = 0x26; /** * */ public static final byte SMB2_RESTART_SCANS = 0x1; /** * */ public static final byte SMB2_RETURN_SINGLE_ENTRY = 0x2; /** * */ public static final byte SMB2_INDEX_SPECIFIED = 0x4; /** * */ public static final byte SMB2_REOPEN = 0x10; private byte fileInformationClass = FILE_BOTH_DIRECTORY_INFO; private byte queryFlags; private int fileIndex; private byte[] fileId; private int outputBufferLength; private String fileName; /** * * @param config */ public Smb2QueryDirectoryRequest ( Configuration config ) {
// Path: src/main/java/jcifs/internal/smb2/Smb2Constants.java // public final class Smb2Constants { // // /** // * // */ // private Smb2Constants () {} // // /** // * // */ // public static final int SMB2_HEADER_LENGTH = 64; // // /** // * // */ // public static final int SMB2_NEGOTIATE_SIGNING_ENABLED = 0x0001; // // /** // * // */ // public static final int SMB2_NEGOTIATE_SIGNING_REQUIRED = 0x0002; // // /** // * // */ // public static final int SMB2_DIALECT_0202 = 0x0202; // // /** // * // */ // public static final int SMB2_DIALECT_0210 = 0x0210; // // /** // * // */ // public static final int SMB2_DIALECT_0300 = 0x0300; // // /** // * // */ // public static final int SMB2_DIALECT_0302 = 0x0302; // // /** // * // */ // public static final int SMB2_DIALECT_0311 = 0x0311; // // /** // * // */ // public static final int SMB2_DIALECT_ANY = 0x02FF; // // /** // * // */ // public static final int SMB2_GLOBAL_CAP_DFS = 0x1; // // /** // * // */ // public static final int SMB2_GLOBAL_CAP_LEASING = 0x2; // // /** // * // */ // public static final int SMB2_GLOBAL_CAP_LARGE_MTU = 0x4; // // /** // * // */ // public static final int SMB2_GLOBAL_CAP_MULTI_CHANNEL = 0x8; // // /** // * // */ // public static final int SMB2_GLOBAL_CAP_PERSISTENT_HANDLES = 0x10; // // /** // * // */ // public static final int SMB2_GLOBAL_CAP_DIRECTORY_LEASING = 0x20; // // /** // * // */ // public static final int SMB2_GLOBAL_CAP_ENCRYPTION = 0x40; // // /** // * // */ // public static final byte SMB2_0_INFO_FILE = 1; // // /** // * // */ // public static final byte SMB2_0_INFO_FILESYSTEM = 2; // // /** // * // */ // public static final byte SMB2_0_INFO_SECURITY = 3; // // /** // * // */ // public static final byte SMB2_0_INFO_QUOTA = 4; // // /** // * // */ // public static final byte[] UNSPECIFIED_FILEID = new byte[] { // (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, // (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF // }; // // /** // * // */ // public static final int UNSPECIFIED_TREEID = 0xFFFFFFFF; // // /** // * // */ // public static final long UNSPECIFIED_SESSIONID = 0xFFFFFFFFFFFFFFFFL; // } // Path: src/main/java/jcifs/internal/smb2/info/Smb2QueryDirectoryRequest.java import java.nio.charset.StandardCharsets; import jcifs.CIFSContext; import jcifs.Configuration; import jcifs.internal.smb2.RequestWithFileId; import jcifs.internal.smb2.ServerMessageBlock2Request; import jcifs.internal.smb2.Smb2Constants; import jcifs.internal.util.SMBUtil; /* * © 2017 AgNO3 Gmbh & Co. KG * * This library 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 2.1 of the License, or (at your option) any later version. * * This library 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 this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package jcifs.internal.smb2.info; /** * @author mbechler * */ public class Smb2QueryDirectoryRequest extends ServerMessageBlock2Request<Smb2QueryDirectoryResponse> implements RequestWithFileId { /** * */ public static final byte FILE_DIRECTORY_INFO = 0x1; /** * */ public static final byte FILE_FULL_DIRECTORY_INFO = 0x2; /** * */ public static final byte FILE_BOTH_DIRECTORY_INFO = 0x03; /** * */ public static final byte FILE_NAMES_INFO = 0x0C; /** * */ public static final byte FILE_ID_BOTH_DIRECTORY_INFO = 0x24; /** * */ public static final byte FILE_ID_FULL_DIRECTORY_INFO = 0x26; /** * */ public static final byte SMB2_RESTART_SCANS = 0x1; /** * */ public static final byte SMB2_RETURN_SINGLE_ENTRY = 0x2; /** * */ public static final byte SMB2_INDEX_SPECIFIED = 0x4; /** * */ public static final byte SMB2_REOPEN = 0x10; private byte fileInformationClass = FILE_BOTH_DIRECTORY_INFO; private byte queryFlags; private int fileIndex; private byte[] fileId; private int outputBufferLength; private String fileName; /** * * @param config */ public Smb2QueryDirectoryRequest ( Configuration config ) {
this(config, Smb2Constants.UNSPECIFIED_FILEID);
AgNO3/jcifs-ng
src/main/java/jcifs/internal/smb2/io/Smb2FlushRequest.java
// Path: src/main/java/jcifs/internal/smb2/Smb2Constants.java // public final class Smb2Constants { // // /** // * // */ // private Smb2Constants () {} // // /** // * // */ // public static final int SMB2_HEADER_LENGTH = 64; // // /** // * // */ // public static final int SMB2_NEGOTIATE_SIGNING_ENABLED = 0x0001; // // /** // * // */ // public static final int SMB2_NEGOTIATE_SIGNING_REQUIRED = 0x0002; // // /** // * // */ // public static final int SMB2_DIALECT_0202 = 0x0202; // // /** // * // */ // public static final int SMB2_DIALECT_0210 = 0x0210; // // /** // * // */ // public static final int SMB2_DIALECT_0300 = 0x0300; // // /** // * // */ // public static final int SMB2_DIALECT_0302 = 0x0302; // // /** // * // */ // public static final int SMB2_DIALECT_0311 = 0x0311; // // /** // * // */ // public static final int SMB2_DIALECT_ANY = 0x02FF; // // /** // * // */ // public static final int SMB2_GLOBAL_CAP_DFS = 0x1; // // /** // * // */ // public static final int SMB2_GLOBAL_CAP_LEASING = 0x2; // // /** // * // */ // public static final int SMB2_GLOBAL_CAP_LARGE_MTU = 0x4; // // /** // * // */ // public static final int SMB2_GLOBAL_CAP_MULTI_CHANNEL = 0x8; // // /** // * // */ // public static final int SMB2_GLOBAL_CAP_PERSISTENT_HANDLES = 0x10; // // /** // * // */ // public static final int SMB2_GLOBAL_CAP_DIRECTORY_LEASING = 0x20; // // /** // * // */ // public static final int SMB2_GLOBAL_CAP_ENCRYPTION = 0x40; // // /** // * // */ // public static final byte SMB2_0_INFO_FILE = 1; // // /** // * // */ // public static final byte SMB2_0_INFO_FILESYSTEM = 2; // // /** // * // */ // public static final byte SMB2_0_INFO_SECURITY = 3; // // /** // * // */ // public static final byte SMB2_0_INFO_QUOTA = 4; // // /** // * // */ // public static final byte[] UNSPECIFIED_FILEID = new byte[] { // (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, // (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF // }; // // /** // * // */ // public static final int UNSPECIFIED_TREEID = 0xFFFFFFFF; // // /** // * // */ // public static final long UNSPECIFIED_SESSIONID = 0xFFFFFFFFFFFFFFFFL; // }
import jcifs.CIFSContext; import jcifs.Configuration; import jcifs.internal.smb2.RequestWithFileId; import jcifs.internal.smb2.ServerMessageBlock2Request; import jcifs.internal.smb2.Smb2Constants; import jcifs.internal.util.SMBUtil;
/* * © 2017 AgNO3 Gmbh & Co. KG * * This library 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 2.1 of the License, or (at your option) any later version. * * This library 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 this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package jcifs.internal.smb2.io; /** * @author mbechler * */ public class Smb2FlushRequest extends ServerMessageBlock2Request<Smb2FlushResponse> implements RequestWithFileId { private byte[] fileId; /** * @param config * @param fileId */ public Smb2FlushRequest ( Configuration config, byte[] fileId ) { super(config, SMB2_FLUSH); this.fileId = fileId; } @Override protected Smb2FlushResponse createResponse ( CIFSContext tc, ServerMessageBlock2Request<Smb2FlushResponse> req ) { return new Smb2FlushResponse(tc.getConfig()); } /** * {@inheritDoc} * * @see jcifs.internal.smb2.RequestWithFileId#setFileId(byte[]) */ @Override public void setFileId ( byte[] fileId ) { this.fileId = fileId; } /** * {@inheritDoc} * * @see jcifs.internal.CommonServerMessageBlockRequest#size() */ @Override public int size () {
// Path: src/main/java/jcifs/internal/smb2/Smb2Constants.java // public final class Smb2Constants { // // /** // * // */ // private Smb2Constants () {} // // /** // * // */ // public static final int SMB2_HEADER_LENGTH = 64; // // /** // * // */ // public static final int SMB2_NEGOTIATE_SIGNING_ENABLED = 0x0001; // // /** // * // */ // public static final int SMB2_NEGOTIATE_SIGNING_REQUIRED = 0x0002; // // /** // * // */ // public static final int SMB2_DIALECT_0202 = 0x0202; // // /** // * // */ // public static final int SMB2_DIALECT_0210 = 0x0210; // // /** // * // */ // public static final int SMB2_DIALECT_0300 = 0x0300; // // /** // * // */ // public static final int SMB2_DIALECT_0302 = 0x0302; // // /** // * // */ // public static final int SMB2_DIALECT_0311 = 0x0311; // // /** // * // */ // public static final int SMB2_DIALECT_ANY = 0x02FF; // // /** // * // */ // public static final int SMB2_GLOBAL_CAP_DFS = 0x1; // // /** // * // */ // public static final int SMB2_GLOBAL_CAP_LEASING = 0x2; // // /** // * // */ // public static final int SMB2_GLOBAL_CAP_LARGE_MTU = 0x4; // // /** // * // */ // public static final int SMB2_GLOBAL_CAP_MULTI_CHANNEL = 0x8; // // /** // * // */ // public static final int SMB2_GLOBAL_CAP_PERSISTENT_HANDLES = 0x10; // // /** // * // */ // public static final int SMB2_GLOBAL_CAP_DIRECTORY_LEASING = 0x20; // // /** // * // */ // public static final int SMB2_GLOBAL_CAP_ENCRYPTION = 0x40; // // /** // * // */ // public static final byte SMB2_0_INFO_FILE = 1; // // /** // * // */ // public static final byte SMB2_0_INFO_FILESYSTEM = 2; // // /** // * // */ // public static final byte SMB2_0_INFO_SECURITY = 3; // // /** // * // */ // public static final byte SMB2_0_INFO_QUOTA = 4; // // /** // * // */ // public static final byte[] UNSPECIFIED_FILEID = new byte[] { // (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, // (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF // }; // // /** // * // */ // public static final int UNSPECIFIED_TREEID = 0xFFFFFFFF; // // /** // * // */ // public static final long UNSPECIFIED_SESSIONID = 0xFFFFFFFFFFFFFFFFL; // } // Path: src/main/java/jcifs/internal/smb2/io/Smb2FlushRequest.java import jcifs.CIFSContext; import jcifs.Configuration; import jcifs.internal.smb2.RequestWithFileId; import jcifs.internal.smb2.ServerMessageBlock2Request; import jcifs.internal.smb2.Smb2Constants; import jcifs.internal.util.SMBUtil; /* * © 2017 AgNO3 Gmbh & Co. KG * * This library 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 2.1 of the License, or (at your option) any later version. * * This library 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 this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package jcifs.internal.smb2.io; /** * @author mbechler * */ public class Smb2FlushRequest extends ServerMessageBlock2Request<Smb2FlushResponse> implements RequestWithFileId { private byte[] fileId; /** * @param config * @param fileId */ public Smb2FlushRequest ( Configuration config, byte[] fileId ) { super(config, SMB2_FLUSH); this.fileId = fileId; } @Override protected Smb2FlushResponse createResponse ( CIFSContext tc, ServerMessageBlock2Request<Smb2FlushResponse> req ) { return new Smb2FlushResponse(tc.getConfig()); } /** * {@inheritDoc} * * @see jcifs.internal.smb2.RequestWithFileId#setFileId(byte[]) */ @Override public void setFileId ( byte[] fileId ) { this.fileId = fileId; } /** * {@inheritDoc} * * @see jcifs.internal.CommonServerMessageBlockRequest#size() */ @Override public int size () {
return size8(Smb2Constants.SMB2_HEADER_LENGTH + 24);
AgNO3/jcifs-ng
src/main/java/jcifs/internal/smb2/nego/Smb2NegotiateRequest.java
// Path: src/main/java/jcifs/internal/smb2/Smb2Constants.java // public final class Smb2Constants { // // /** // * // */ // private Smb2Constants () {} // // /** // * // */ // public static final int SMB2_HEADER_LENGTH = 64; // // /** // * // */ // public static final int SMB2_NEGOTIATE_SIGNING_ENABLED = 0x0001; // // /** // * // */ // public static final int SMB2_NEGOTIATE_SIGNING_REQUIRED = 0x0002; // // /** // * // */ // public static final int SMB2_DIALECT_0202 = 0x0202; // // /** // * // */ // public static final int SMB2_DIALECT_0210 = 0x0210; // // /** // * // */ // public static final int SMB2_DIALECT_0300 = 0x0300; // // /** // * // */ // public static final int SMB2_DIALECT_0302 = 0x0302; // // /** // * // */ // public static final int SMB2_DIALECT_0311 = 0x0311; // // /** // * // */ // public static final int SMB2_DIALECT_ANY = 0x02FF; // // /** // * // */ // public static final int SMB2_GLOBAL_CAP_DFS = 0x1; // // /** // * // */ // public static final int SMB2_GLOBAL_CAP_LEASING = 0x2; // // /** // * // */ // public static final int SMB2_GLOBAL_CAP_LARGE_MTU = 0x4; // // /** // * // */ // public static final int SMB2_GLOBAL_CAP_MULTI_CHANNEL = 0x8; // // /** // * // */ // public static final int SMB2_GLOBAL_CAP_PERSISTENT_HANDLES = 0x10; // // /** // * // */ // public static final int SMB2_GLOBAL_CAP_DIRECTORY_LEASING = 0x20; // // /** // * // */ // public static final int SMB2_GLOBAL_CAP_ENCRYPTION = 0x40; // // /** // * // */ // public static final byte SMB2_0_INFO_FILE = 1; // // /** // * // */ // public static final byte SMB2_0_INFO_FILESYSTEM = 2; // // /** // * // */ // public static final byte SMB2_0_INFO_SECURITY = 3; // // /** // * // */ // public static final byte SMB2_0_INFO_QUOTA = 4; // // /** // * // */ // public static final byte[] UNSPECIFIED_FILEID = new byte[] { // (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, // (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF // }; // // /** // * // */ // public static final int UNSPECIFIED_TREEID = 0xFFFFFFFF; // // /** // * // */ // public static final long UNSPECIFIED_SESSIONID = 0xFFFFFFFFFFFFFFFFL; // }
import java.util.LinkedList; import java.util.List; import java.util.Set; import jcifs.CIFSContext; import jcifs.Configuration; import jcifs.DialectVersion; import jcifs.internal.SmbNegotiationRequest; import jcifs.internal.smb2.ServerMessageBlock2Request; import jcifs.internal.smb2.Smb2Constants; import jcifs.internal.util.SMBUtil;
/* * © 2017 AgNO3 Gmbh & Co. KG * * This library 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 2.1 of the License, or (at your option) any later version. * * This library 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 this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package jcifs.internal.smb2.nego; /** * @author mbechler * */ public class Smb2NegotiateRequest extends ServerMessageBlock2Request<Smb2NegotiateResponse> implements SmbNegotiationRequest { private int[] dialects; private int capabilities; private byte[] clientGuid = new byte[16]; private int securityMode; private NegotiateContextRequest[] negotiateContexts; private byte[] preauthSalt; /** * @param config * @param securityMode */ public Smb2NegotiateRequest ( Configuration config, int securityMode ) { super(config, SMB2_NEGOTIATE); this.securityMode = securityMode; if ( !config.isDfsDisabled() ) {
// Path: src/main/java/jcifs/internal/smb2/Smb2Constants.java // public final class Smb2Constants { // // /** // * // */ // private Smb2Constants () {} // // /** // * // */ // public static final int SMB2_HEADER_LENGTH = 64; // // /** // * // */ // public static final int SMB2_NEGOTIATE_SIGNING_ENABLED = 0x0001; // // /** // * // */ // public static final int SMB2_NEGOTIATE_SIGNING_REQUIRED = 0x0002; // // /** // * // */ // public static final int SMB2_DIALECT_0202 = 0x0202; // // /** // * // */ // public static final int SMB2_DIALECT_0210 = 0x0210; // // /** // * // */ // public static final int SMB2_DIALECT_0300 = 0x0300; // // /** // * // */ // public static final int SMB2_DIALECT_0302 = 0x0302; // // /** // * // */ // public static final int SMB2_DIALECT_0311 = 0x0311; // // /** // * // */ // public static final int SMB2_DIALECT_ANY = 0x02FF; // // /** // * // */ // public static final int SMB2_GLOBAL_CAP_DFS = 0x1; // // /** // * // */ // public static final int SMB2_GLOBAL_CAP_LEASING = 0x2; // // /** // * // */ // public static final int SMB2_GLOBAL_CAP_LARGE_MTU = 0x4; // // /** // * // */ // public static final int SMB2_GLOBAL_CAP_MULTI_CHANNEL = 0x8; // // /** // * // */ // public static final int SMB2_GLOBAL_CAP_PERSISTENT_HANDLES = 0x10; // // /** // * // */ // public static final int SMB2_GLOBAL_CAP_DIRECTORY_LEASING = 0x20; // // /** // * // */ // public static final int SMB2_GLOBAL_CAP_ENCRYPTION = 0x40; // // /** // * // */ // public static final byte SMB2_0_INFO_FILE = 1; // // /** // * // */ // public static final byte SMB2_0_INFO_FILESYSTEM = 2; // // /** // * // */ // public static final byte SMB2_0_INFO_SECURITY = 3; // // /** // * // */ // public static final byte SMB2_0_INFO_QUOTA = 4; // // /** // * // */ // public static final byte[] UNSPECIFIED_FILEID = new byte[] { // (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, // (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF // }; // // /** // * // */ // public static final int UNSPECIFIED_TREEID = 0xFFFFFFFF; // // /** // * // */ // public static final long UNSPECIFIED_SESSIONID = 0xFFFFFFFFFFFFFFFFL; // } // Path: src/main/java/jcifs/internal/smb2/nego/Smb2NegotiateRequest.java import java.util.LinkedList; import java.util.List; import java.util.Set; import jcifs.CIFSContext; import jcifs.Configuration; import jcifs.DialectVersion; import jcifs.internal.SmbNegotiationRequest; import jcifs.internal.smb2.ServerMessageBlock2Request; import jcifs.internal.smb2.Smb2Constants; import jcifs.internal.util.SMBUtil; /* * © 2017 AgNO3 Gmbh & Co. KG * * This library 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 2.1 of the License, or (at your option) any later version. * * This library 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 this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package jcifs.internal.smb2.nego; /** * @author mbechler * */ public class Smb2NegotiateRequest extends ServerMessageBlock2Request<Smb2NegotiateResponse> implements SmbNegotiationRequest { private int[] dialects; private int capabilities; private byte[] clientGuid = new byte[16]; private int securityMode; private NegotiateContextRequest[] negotiateContexts; private byte[] preauthSalt; /** * @param config * @param securityMode */ public Smb2NegotiateRequest ( Configuration config, int securityMode ) { super(config, SMB2_NEGOTIATE); this.securityMode = securityMode; if ( !config.isDfsDisabled() ) {
this.capabilities |= Smb2Constants.SMB2_GLOBAL_CAP_DFS;
OpenRedstoneEngineers/OREUtilsV2
OTJP/src/main/java/org/openredstone/OTJP.java
// Path: OTJP/src/main/java/org/openredstone/gen/PlotGenerator.java // public class PlotGenerator extends ChunkGenerator { // public int PlotWidth = 256; // public int PlotHeight = 16; // public int PlotLength = 256; // // public short BlockMain = (short) Material.SANDSTONE.getId(); // public short BlockBorder = (short) Material.SMOOTH_BRICK.getId(); // public short BlockCorner0 = (short) (Material.WOOL.getId() + ((short) 1 >> 8)); // public short BlockCorner1 = (short) Material.NETHERRACK.getId(); // // public short[][] generateExtBlockSections(World world, Random random, int x, int z, BiomeGrid biomes) { // short[][] result = new short[world.getMaxHeight() / 16][]; // // int chunkOffsetX = 16 * x; // int chunkOffsetZ = 16 * z; // int modX, modZ; // // for (int x1 = 0; x1 < 16; ++x1) { // for (int z1 = 0; z1 < 16; ++z1) { // for(int y1 = 0; y1 < PlotHeight; ++y1) { // setBlock(result, x1, y1, z1, BlockMain); // // if (y1 == PlotHeight - 1) { // modX = (chunkOffsetX + x1) % PlotWidth; // modZ = (chunkOffsetZ + z1) % PlotLength; // // if (modX == 0 || modX == 255 || modX == -1 || modZ == 0 || modZ == 255 || modZ == -1) // setBlock(result, x1, y1, z1, BlockBorder); // // if (x1 == 0 && z1 == 0 || x1 == 15 && z1 == 15) // setBlock(result, x1, y1, z1, BlockCorner0); // // if (x1 == 0 && z1 == 15 || x1 == 15 && z1 == 0) // setBlock(result, x1, y1, z1, BlockCorner1); // } // } // } // } // // return result; // } // // void setBlock(short[][] result, int x, int y, int z, short blkid) { // if (result[y >> 4] == null) { // result[y >> 4] = new short[4096]; // } // // result[y >> 4][((y & 0xF) << 8) | (z << 4) | x] = blkid; // } // }
import org.bukkit.generator.ChunkGenerator; import org.bukkit.plugin.java.JavaPlugin; import org.openredstone.gen.PlotGenerator;
/** * ORE's Tiny Java Plugin * Copyright (C) 2013 OpenRedstone * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.openredstone; /** * Main java plugin class. * */ public class OTJP extends JavaPlugin { public ChunkGenerator getDefaultWorldGenerator(String worldName, String id) {
// Path: OTJP/src/main/java/org/openredstone/gen/PlotGenerator.java // public class PlotGenerator extends ChunkGenerator { // public int PlotWidth = 256; // public int PlotHeight = 16; // public int PlotLength = 256; // // public short BlockMain = (short) Material.SANDSTONE.getId(); // public short BlockBorder = (short) Material.SMOOTH_BRICK.getId(); // public short BlockCorner0 = (short) (Material.WOOL.getId() + ((short) 1 >> 8)); // public short BlockCorner1 = (short) Material.NETHERRACK.getId(); // // public short[][] generateExtBlockSections(World world, Random random, int x, int z, BiomeGrid biomes) { // short[][] result = new short[world.getMaxHeight() / 16][]; // // int chunkOffsetX = 16 * x; // int chunkOffsetZ = 16 * z; // int modX, modZ; // // for (int x1 = 0; x1 < 16; ++x1) { // for (int z1 = 0; z1 < 16; ++z1) { // for(int y1 = 0; y1 < PlotHeight; ++y1) { // setBlock(result, x1, y1, z1, BlockMain); // // if (y1 == PlotHeight - 1) { // modX = (chunkOffsetX + x1) % PlotWidth; // modZ = (chunkOffsetZ + z1) % PlotLength; // // if (modX == 0 || modX == 255 || modX == -1 || modZ == 0 || modZ == 255 || modZ == -1) // setBlock(result, x1, y1, z1, BlockBorder); // // if (x1 == 0 && z1 == 0 || x1 == 15 && z1 == 15) // setBlock(result, x1, y1, z1, BlockCorner0); // // if (x1 == 0 && z1 == 15 || x1 == 15 && z1 == 0) // setBlock(result, x1, y1, z1, BlockCorner1); // } // } // } // } // // return result; // } // // void setBlock(short[][] result, int x, int y, int z, short blkid) { // if (result[y >> 4] == null) { // result[y >> 4] = new short[4096]; // } // // result[y >> 4][((y & 0xF) << 8) | (z << 4) | x] = blkid; // } // } // Path: OTJP/src/main/java/org/openredstone/OTJP.java import org.bukkit.generator.ChunkGenerator; import org.bukkit.plugin.java.JavaPlugin; import org.openredstone.gen.PlotGenerator; /** * ORE's Tiny Java Plugin * Copyright (C) 2013 OpenRedstone * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.openredstone; /** * Main java plugin class. * */ public class OTJP extends JavaPlugin { public ChunkGenerator getDefaultWorldGenerator(String worldName, String id) {
return new PlotGenerator();
sdwfqin/AndroidSamples
greendaomvp/src/main/java/com/sdwfqin/greendaosample/view/MainView.java
// Path: greendaomvp/src/main/java/com/sdwfqin/greendaosample/model/entry/Student.java // @Entity // public class Student { // // // 对象的Id,使用Long类型作为EntityId,否则会报错。 // // (autoincrement = true)表示主键会自增,如果false就会使用旧值 // @Id(autoincrement = true) // private long id; // // 在数据库中必须是唯一的 // @Unique // private String name; // // 属性不能为空 // @NotNull // private String sex; // private String address; // // // 编译后自动生成的构造函数、方法等的注释,提示构造函数、方法等不能被修改 // @Generated(hash = 611957646) // public Student(long id, String name, @NotNull String sex, String address) { // this.id = id; // this.name = name; // this.sex = sex; // this.address = address; // } // // @Generated(hash = 1556870573) // public Student() { // } // // public long getId() { // return this.id; // } // // public void setId(long id) { // this.id = id; // } // // public String getName() { // return this.name; // } // // public void setName(String name) { // this.name = name; // } // // public String getSex() { // return this.sex; // } // // public void setSex(String sex) { // this.sex = sex; // } // // public String getAddress() { // return this.address; // } // // public void setAddress(String address) { // this.address = address; // } // // @Override // public String toString() { // return "Student{" + // "id=" + id + // ", name='" + name + '\'' + // ", age='" + sex + '\'' + // ", address='" + address + '\'' + // '}'; // } // }
import com.sdwfqin.greendaosample.model.entry.Student; import java.util.List;
package com.sdwfqin.greendaosample.view; /** * 描述:V层接口 * * @author zhangqin * @date 2017/5/5 */ public interface MainView { /** * 显示加载动画 */ void showProgress(); /** * 隐藏加载动画 */ void hideProgress(); /** * 显示底部弹窗 */ void showBottomSheetDialog(); /** * 更新数据 * * @param student * @param position */
// Path: greendaomvp/src/main/java/com/sdwfqin/greendaosample/model/entry/Student.java // @Entity // public class Student { // // // 对象的Id,使用Long类型作为EntityId,否则会报错。 // // (autoincrement = true)表示主键会自增,如果false就会使用旧值 // @Id(autoincrement = true) // private long id; // // 在数据库中必须是唯一的 // @Unique // private String name; // // 属性不能为空 // @NotNull // private String sex; // private String address; // // // 编译后自动生成的构造函数、方法等的注释,提示构造函数、方法等不能被修改 // @Generated(hash = 611957646) // public Student(long id, String name, @NotNull String sex, String address) { // this.id = id; // this.name = name; // this.sex = sex; // this.address = address; // } // // @Generated(hash = 1556870573) // public Student() { // } // // public long getId() { // return this.id; // } // // public void setId(long id) { // this.id = id; // } // // public String getName() { // return this.name; // } // // public void setName(String name) { // this.name = name; // } // // public String getSex() { // return this.sex; // } // // public void setSex(String sex) { // this.sex = sex; // } // // public String getAddress() { // return this.address; // } // // public void setAddress(String address) { // this.address = address; // } // // @Override // public String toString() { // return "Student{" + // "id=" + id + // ", name='" + name + '\'' + // ", age='" + sex + '\'' + // ", address='" + address + '\'' + // '}'; // } // } // Path: greendaomvp/src/main/java/com/sdwfqin/greendaosample/view/MainView.java import com.sdwfqin.greendaosample.model.entry.Student; import java.util.List; package com.sdwfqin.greendaosample.view; /** * 描述:V层接口 * * @author zhangqin * @date 2017/5/5 */ public interface MainView { /** * 显示加载动画 */ void showProgress(); /** * 隐藏加载动画 */ void hideProgress(); /** * 显示底部弹窗 */ void showBottomSheetDialog(); /** * 更新数据 * * @param student * @param position */
void upData(Student student, int position);
sdwfqin/AndroidSamples
greendaomvp/src/main/java/com/sdwfqin/greendaosample/presenter/MainPresenter.java
// Path: greendaomvp/src/main/java/com/sdwfqin/greendaosample/model/entry/Student.java // @Entity // public class Student { // // // 对象的Id,使用Long类型作为EntityId,否则会报错。 // // (autoincrement = true)表示主键会自增,如果false就会使用旧值 // @Id(autoincrement = true) // private long id; // // 在数据库中必须是唯一的 // @Unique // private String name; // // 属性不能为空 // @NotNull // private String sex; // private String address; // // // 编译后自动生成的构造函数、方法等的注释,提示构造函数、方法等不能被修改 // @Generated(hash = 611957646) // public Student(long id, String name, @NotNull String sex, String address) { // this.id = id; // this.name = name; // this.sex = sex; // this.address = address; // } // // @Generated(hash = 1556870573) // public Student() { // } // // public long getId() { // return this.id; // } // // public void setId(long id) { // this.id = id; // } // // public String getName() { // return this.name; // } // // public void setName(String name) { // this.name = name; // } // // public String getSex() { // return this.sex; // } // // public void setSex(String sex) { // this.sex = sex; // } // // public String getAddress() { // return this.address; // } // // public void setAddress(String address) { // this.address = address; // } // // @Override // public String toString() { // return "Student{" + // "id=" + id + // ", name='" + name + '\'' + // ", age='" + sex + '\'' + // ", address='" + address + '\'' + // '}'; // } // }
import com.sdwfqin.greendaosample.model.entry.Student;
package com.sdwfqin.greendaosample.presenter; /** * 描述:P层接口 * * @author zhangqin * @date 2017/5/5 */ public interface MainPresenter { void onResume();
// Path: greendaomvp/src/main/java/com/sdwfqin/greendaosample/model/entry/Student.java // @Entity // public class Student { // // // 对象的Id,使用Long类型作为EntityId,否则会报错。 // // (autoincrement = true)表示主键会自增,如果false就会使用旧值 // @Id(autoincrement = true) // private long id; // // 在数据库中必须是唯一的 // @Unique // private String name; // // 属性不能为空 // @NotNull // private String sex; // private String address; // // // 编译后自动生成的构造函数、方法等的注释,提示构造函数、方法等不能被修改 // @Generated(hash = 611957646) // public Student(long id, String name, @NotNull String sex, String address) { // this.id = id; // this.name = name; // this.sex = sex; // this.address = address; // } // // @Generated(hash = 1556870573) // public Student() { // } // // public long getId() { // return this.id; // } // // public void setId(long id) { // this.id = id; // } // // public String getName() { // return this.name; // } // // public void setName(String name) { // this.name = name; // } // // public String getSex() { // return this.sex; // } // // public void setSex(String sex) { // this.sex = sex; // } // // public String getAddress() { // return this.address; // } // // public void setAddress(String address) { // this.address = address; // } // // @Override // public String toString() { // return "Student{" + // "id=" + id + // ", name='" + name + '\'' + // ", age='" + sex + '\'' + // ", address='" + address + '\'' + // '}'; // } // } // Path: greendaomvp/src/main/java/com/sdwfqin/greendaosample/presenter/MainPresenter.java import com.sdwfqin.greendaosample.model.entry.Student; package com.sdwfqin.greendaosample.presenter; /** * 描述:P层接口 * * @author zhangqin * @date 2017/5/5 */ public interface MainPresenter { void onResume();
void OnClickUpData(Student student, int position);
sdwfqin/AndroidSamples
mvpseed/src/main/java/com/sdwfqin/mvpseed/base/BaseActivity.java
// Path: mvpseed/src/main/java/com/sdwfqin/mvpseed/di/module/ActivityModule.java // @Module // public class ActivityModule { // private Activity mActivity; // // public ActivityModule(Activity activity) { // this.mActivity = activity; // } // // @Provides // @ActivityScope // public Activity provideActivity() { // return mActivity; // } // }
import android.app.Activity; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.widget.Toast; import com.sdwfqin.mvpseed.di.component.ActivityComponent; import com.sdwfqin.mvpseed.di.component.DaggerActivityComponent; import com.sdwfqin.mvpseed.di.module.ActivityModule; import javax.inject.Inject; import butterknife.ButterKnife; import butterknife.Unbinder;
package com.sdwfqin.mvpseed.base; /** * 描述:Activity的基类 * * @author zhangqin * @date 2017/6/9 */ public abstract class BaseActivity<T extends BasePresenter> extends AppCompatActivity implements BaseView { @Inject protected T mPresenter; protected Activity mContext; private Unbinder mUnBinder; protected ActivityComponent getActivityComponent() { return DaggerActivityComponent.builder() .appComponent(App.getAppComponent()) .activityModule(getActivityModule()) .build(); }
// Path: mvpseed/src/main/java/com/sdwfqin/mvpseed/di/module/ActivityModule.java // @Module // public class ActivityModule { // private Activity mActivity; // // public ActivityModule(Activity activity) { // this.mActivity = activity; // } // // @Provides // @ActivityScope // public Activity provideActivity() { // return mActivity; // } // } // Path: mvpseed/src/main/java/com/sdwfqin/mvpseed/base/BaseActivity.java import android.app.Activity; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.widget.Toast; import com.sdwfqin.mvpseed.di.component.ActivityComponent; import com.sdwfqin.mvpseed.di.component.DaggerActivityComponent; import com.sdwfqin.mvpseed.di.module.ActivityModule; import javax.inject.Inject; import butterknife.ButterKnife; import butterknife.Unbinder; package com.sdwfqin.mvpseed.base; /** * 描述:Activity的基类 * * @author zhangqin * @date 2017/6/9 */ public abstract class BaseActivity<T extends BasePresenter> extends AppCompatActivity implements BaseView { @Inject protected T mPresenter; protected Activity mContext; private Unbinder mUnBinder; protected ActivityComponent getActivityComponent() { return DaggerActivityComponent.builder() .appComponent(App.getAppComponent()) .activityModule(getActivityModule()) .build(); }
protected ActivityModule getActivityModule() {
sdwfqin/AndroidSamples
mvpseed/src/main/java/com/sdwfqin/mvpseed/contract/MainContract.java
// Path: mvpseed/src/main/java/com/sdwfqin/mvpseed/model/bean/TestBean.java // public class TestBean { // // /** // * weatherinfo : {"city":"无锡","cityid":"101190201","temp":"12","WD":"西北风","WS":"2级","SD":"93%","WSE":"2","time":"10:25","isRadar":"0","Radar":"","njd":"暂无实况","qy":"1008"} // */ // // private WeatherinfoBean weatherinfo; // // public WeatherinfoBean getWeatherinfo() { // return weatherinfo; // } // // public void setWeatherinfo(WeatherinfoBean weatherinfo) { // this.weatherinfo = weatherinfo; // } // // @Override // public String toString() { // return "TestBean{" + // "weatherinfo=" + weatherinfo + // '}'; // } // // public static class WeatherinfoBean { // /** // * city : 无锡 // * cityid : 101190201 // * temp : 12 // * WD : 西北风 // * WS : 2级 // * SD : 93% // * WSE : 2 // * time : 10:25 // * isRadar : 0 // * Radar : // * njd : 暂无实况 // * qy : 1008 // */ // // private String city; // private String cityid; // private String temp; // private String WD; // private String WS; // private String SD; // private String WSE; // private String time; // private String isRadar; // private String Radar; // private String njd; // private String qy; // // @Override // public String toString() { // return "WeatherinfoBean{" + // "city='" + city + '\'' + // ", cityid='" + cityid + '\'' + // ", temp='" + temp + '\'' + // ", WD='" + WD + '\'' + // ", WS='" + WS + '\'' + // ", SD='" + SD + '\'' + // ", WSE='" + WSE + '\'' + // ", time='" + time + '\'' + // ", isRadar='" + isRadar + '\'' + // ", Radar='" + Radar + '\'' + // ", njd='" + njd + '\'' + // ", qy='" + qy + '\'' + // '}'; // } // // public String getCity() { // return city; // } // // public void setCity(String city) { // this.city = city; // } // // public String getCityid() { // return cityid; // } // // public void setCityid(String cityid) { // this.cityid = cityid; // } // // public String getTemp() { // return temp; // } // // public void setTemp(String temp) { // this.temp = temp; // } // // public String getWD() { // return WD; // } // // public void setWD(String WD) { // this.WD = WD; // } // // public String getWS() { // return WS; // } // // public void setWS(String WS) { // this.WS = WS; // } // // public String getSD() { // return SD; // } // // public void setSD(String SD) { // this.SD = SD; // } // // public String getWSE() { // return WSE; // } // // public void setWSE(String WSE) { // this.WSE = WSE; // } // // public String getTime() { // return time; // } // // public void setTime(String time) { // this.time = time; // } // // public String getIsRadar() { // return isRadar; // } // // public void setIsRadar(String isRadar) { // this.isRadar = isRadar; // } // // public String getRadar() { // return Radar; // } // // public void setRadar(String Radar) { // this.Radar = Radar; // } // // public String getNjd() { // return njd; // } // // public void setNjd(String njd) { // this.njd = njd; // } // // public String getQy() { // return qy; // } // // public void setQy(String qy) { // this.qy = qy; // } // } // }
import com.sdwfqin.mvpseed.base.BasePresenter; import com.sdwfqin.mvpseed.base.BaseView; import com.sdwfqin.mvpseed.model.bean.TestBean;
package com.sdwfqin.mvpseed.contract; /** * 描述:绑定类 * * @author zhangqin * @date 2017/6/9 */ public interface MainContract { interface View extends BaseView { /** * 设置TextView中的数据 * * @param testBean */
// Path: mvpseed/src/main/java/com/sdwfqin/mvpseed/model/bean/TestBean.java // public class TestBean { // // /** // * weatherinfo : {"city":"无锡","cityid":"101190201","temp":"12","WD":"西北风","WS":"2级","SD":"93%","WSE":"2","time":"10:25","isRadar":"0","Radar":"","njd":"暂无实况","qy":"1008"} // */ // // private WeatherinfoBean weatherinfo; // // public WeatherinfoBean getWeatherinfo() { // return weatherinfo; // } // // public void setWeatherinfo(WeatherinfoBean weatherinfo) { // this.weatherinfo = weatherinfo; // } // // @Override // public String toString() { // return "TestBean{" + // "weatherinfo=" + weatherinfo + // '}'; // } // // public static class WeatherinfoBean { // /** // * city : 无锡 // * cityid : 101190201 // * temp : 12 // * WD : 西北风 // * WS : 2级 // * SD : 93% // * WSE : 2 // * time : 10:25 // * isRadar : 0 // * Radar : // * njd : 暂无实况 // * qy : 1008 // */ // // private String city; // private String cityid; // private String temp; // private String WD; // private String WS; // private String SD; // private String WSE; // private String time; // private String isRadar; // private String Radar; // private String njd; // private String qy; // // @Override // public String toString() { // return "WeatherinfoBean{" + // "city='" + city + '\'' + // ", cityid='" + cityid + '\'' + // ", temp='" + temp + '\'' + // ", WD='" + WD + '\'' + // ", WS='" + WS + '\'' + // ", SD='" + SD + '\'' + // ", WSE='" + WSE + '\'' + // ", time='" + time + '\'' + // ", isRadar='" + isRadar + '\'' + // ", Radar='" + Radar + '\'' + // ", njd='" + njd + '\'' + // ", qy='" + qy + '\'' + // '}'; // } // // public String getCity() { // return city; // } // // public void setCity(String city) { // this.city = city; // } // // public String getCityid() { // return cityid; // } // // public void setCityid(String cityid) { // this.cityid = cityid; // } // // public String getTemp() { // return temp; // } // // public void setTemp(String temp) { // this.temp = temp; // } // // public String getWD() { // return WD; // } // // public void setWD(String WD) { // this.WD = WD; // } // // public String getWS() { // return WS; // } // // public void setWS(String WS) { // this.WS = WS; // } // // public String getSD() { // return SD; // } // // public void setSD(String SD) { // this.SD = SD; // } // // public String getWSE() { // return WSE; // } // // public void setWSE(String WSE) { // this.WSE = WSE; // } // // public String getTime() { // return time; // } // // public void setTime(String time) { // this.time = time; // } // // public String getIsRadar() { // return isRadar; // } // // public void setIsRadar(String isRadar) { // this.isRadar = isRadar; // } // // public String getRadar() { // return Radar; // } // // public void setRadar(String Radar) { // this.Radar = Radar; // } // // public String getNjd() { // return njd; // } // // public void setNjd(String njd) { // this.njd = njd; // } // // public String getQy() { // return qy; // } // // public void setQy(String qy) { // this.qy = qy; // } // } // } // Path: mvpseed/src/main/java/com/sdwfqin/mvpseed/contract/MainContract.java import com.sdwfqin.mvpseed.base.BasePresenter; import com.sdwfqin.mvpseed.base.BaseView; import com.sdwfqin.mvpseed.model.bean.TestBean; package com.sdwfqin.mvpseed.contract; /** * 描述:绑定类 * * @author zhangqin * @date 2017/6/9 */ public interface MainContract { interface View extends BaseView { /** * 设置TextView中的数据 * * @param testBean */
void showTextView(TestBean testBean);
sdwfqin/AndroidSamples
greendaomvp/src/main/java/com/sdwfqin/greendaosample/model/interactor/MainInteractorImpl.java
// Path: greendaomvp/src/main/java/com/sdwfqin/greendaosample/model/entry/Student.java // @Entity // public class Student { // // // 对象的Id,使用Long类型作为EntityId,否则会报错。 // // (autoincrement = true)表示主键会自增,如果false就会使用旧值 // @Id(autoincrement = true) // private long id; // // 在数据库中必须是唯一的 // @Unique // private String name; // // 属性不能为空 // @NotNull // private String sex; // private String address; // // // 编译后自动生成的构造函数、方法等的注释,提示构造函数、方法等不能被修改 // @Generated(hash = 611957646) // public Student(long id, String name, @NotNull String sex, String address) { // this.id = id; // this.name = name; // this.sex = sex; // this.address = address; // } // // @Generated(hash = 1556870573) // public Student() { // } // // public long getId() { // return this.id; // } // // public void setId(long id) { // this.id = id; // } // // public String getName() { // return this.name; // } // // public void setName(String name) { // this.name = name; // } // // public String getSex() { // return this.sex; // } // // public void setSex(String sex) { // this.sex = sex; // } // // public String getAddress() { // return this.address; // } // // public void setAddress(String address) { // this.address = address; // } // // @Override // public String toString() { // return "Student{" + // "id=" + id + // ", name='" + name + '\'' + // ", age='" + sex + '\'' + // ", address='" + address + '\'' + // '}'; // } // }
import android.util.Log; import com.sdwfqin.greendaosample.BaseApplication; import com.sdwfqin.greendaosample.model.entry.Student; import java.util.ArrayList; import java.util.List;
package com.sdwfqin.greendaosample.model.interactor; /** * Created by zhangqin on 2017/5/5. */ public class MainInteractorImpl implements MainInteractor { private static final String TAG = "MainInteractorImpl"; @Override public void initData(OnFinishedListener listener) { Log.e(TAG, "initData: " + "刷新");
// Path: greendaomvp/src/main/java/com/sdwfqin/greendaosample/model/entry/Student.java // @Entity // public class Student { // // // 对象的Id,使用Long类型作为EntityId,否则会报错。 // // (autoincrement = true)表示主键会自增,如果false就会使用旧值 // @Id(autoincrement = true) // private long id; // // 在数据库中必须是唯一的 // @Unique // private String name; // // 属性不能为空 // @NotNull // private String sex; // private String address; // // // 编译后自动生成的构造函数、方法等的注释,提示构造函数、方法等不能被修改 // @Generated(hash = 611957646) // public Student(long id, String name, @NotNull String sex, String address) { // this.id = id; // this.name = name; // this.sex = sex; // this.address = address; // } // // @Generated(hash = 1556870573) // public Student() { // } // // public long getId() { // return this.id; // } // // public void setId(long id) { // this.id = id; // } // // public String getName() { // return this.name; // } // // public void setName(String name) { // this.name = name; // } // // public String getSex() { // return this.sex; // } // // public void setSex(String sex) { // this.sex = sex; // } // // public String getAddress() { // return this.address; // } // // public void setAddress(String address) { // this.address = address; // } // // @Override // public String toString() { // return "Student{" + // "id=" + id + // ", name='" + name + '\'' + // ", age='" + sex + '\'' + // ", address='" + address + '\'' + // '}'; // } // } // Path: greendaomvp/src/main/java/com/sdwfqin/greendaosample/model/interactor/MainInteractorImpl.java import android.util.Log; import com.sdwfqin.greendaosample.BaseApplication; import com.sdwfqin.greendaosample.model.entry.Student; import java.util.ArrayList; import java.util.List; package com.sdwfqin.greendaosample.model.interactor; /** * Created by zhangqin on 2017/5/5. */ public class MainInteractorImpl implements MainInteractor { private static final String TAG = "MainInteractorImpl"; @Override public void initData(OnFinishedListener listener) { Log.e(TAG, "initData: " + "刷新");
List<Student> list = new ArrayList<Student>();
sdwfqin/AndroidSamples
app/src/main/java/com/sdwfqin/sample/view/ViewActivity.java
// Path: app/src/main/java/com/sdwfqin/sample/view/bottomzoom/BottomZoomActivity.java // public class BottomZoomActivity extends AppCompatActivity { // // @BindView(R.id.animator1_btn) // Button animator1Btn; // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_animator1); // ButterKnife.bind(this); // // animator1Btn.setOnClickListener(v -> setButtonSize(300, 300)); // } // // private void setButtonSize(int x, int y) { // // ViewWrapper viewWrapper = new ViewWrapper(animator1Btn); // // // 动画集合,同时执行下面的动画效果 // AnimatorSet set = new AnimatorSet(); // set.playTogether( // ObjectAnimator.ofInt(viewWrapper, "width", // ConvertUtils.dp2px(x)), // ObjectAnimator.ofInt(viewWrapper, "height", // ConvertUtils.dp2px(y)) // ); // // set.setDuration(5000).start(); // } // // /** // * 用一个类来包装原始对象,间接为其提供get和set方法 // * 对象的大小要在xml定死,不然与预想的效果不一样 // */ // private class ViewWrapper { // private View mTarget; // // public ViewWrapper(View target) { // mTarget = target; // } // // public int getWidth() { // return mTarget.getLayoutParams().width; // } // // public void setWidth(int width) { // mTarget.getLayoutParams().width = width; // mTarget.requestLayout(); // } // // public int getHeight() { // return mTarget.getLayoutParams().height; // } // // public void setHeight(int height) { // mTarget.getLayoutParams().height = height; // mTarget.requestLayout(); // } // } // } // // Path: app/src/main/java/com/sdwfqin/sample/view/motionslop/MeTsActivity.java // public class MeTsActivity extends AppCompatActivity { // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_me_ts); // } // } // // Path: app/src/main/java/com/sdwfqin/sample/view/rippleanimation/RippleAnimationActivity.java // public class RippleAnimationActivity extends AppCompatActivity { // // @BindView(R.id.ImageView) // android.widget.ImageView mImageView; // @BindView(R.id.layout_RippleAnimation) // RippleAnimationView mLayoutRippleAnimation; // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_ripple_animation); // ButterKnife.bind(this); // // mImageView = findViewById(R.id.ImageView); // mLayoutRippleAnimation = findViewById(R.id.layout_RippleAnimation); // // mImageView.setOnClickListener(view -> { // if (mLayoutRippleAnimation.isRippleRunning()) { // mLayoutRippleAnimation.stopRippleAnimation(); // } else { // mLayoutRippleAnimation.startRippleAnimation(); // } // }); // } // }
import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.ArrayAdapter; import android.widget.ListView; import com.sdwfqin.sample.R; import com.sdwfqin.sample.view.bottomzoom.BottomZoomActivity; import com.sdwfqin.sample.view.courtesycard.CourtesyCardActivity; import com.sdwfqin.sample.view.delbtn.DeleteButtonActivity; import com.sdwfqin.sample.view.descircle.DesCircleActivity; import com.sdwfqin.sample.view.gesturedetector.GestureDetectorActivity; import com.sdwfqin.sample.view.motionslop.MeTsActivity; import com.sdwfqin.sample.view.paypwdinput.PayPwdInputActivity; import com.sdwfqin.sample.view.rippleanimation.RippleAnimationActivity; import com.sdwfqin.sample.view.scroller.ScrollerActivity; import com.sdwfqin.sample.view.surface.SurfaceActivity; import com.sdwfqin.sample.view.surfacepalette.SurfacePaletteActivity; import com.sdwfqin.sample.view.viewevent.ViewEventActivity; import com.sdwfqin.sample.view.viewposition.ViewPositionActivity; import butterknife.BindView; import butterknife.ButterKnife;
package com.sdwfqin.sample.view; /** * 描述:View相关 * * @author zhangqin */ public class ViewActivity extends AppCompatActivity { @BindView(R.id.list) ListView mViewList; private Context mContext; private String[] mStrings = new String[]{"View的位置参数", "MotionEvent与TouchSlop", "GestureDetector", "Scroller", "View触摸事件分发", "按钮放大(属性动画)", "自定义View1圆", "自定义View2凹凸边缘", "SurfaceView", "SurfaceView画板", "自定义输入密码", "网易云听歌识曲", "长按删除按钮"};
// Path: app/src/main/java/com/sdwfqin/sample/view/bottomzoom/BottomZoomActivity.java // public class BottomZoomActivity extends AppCompatActivity { // // @BindView(R.id.animator1_btn) // Button animator1Btn; // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_animator1); // ButterKnife.bind(this); // // animator1Btn.setOnClickListener(v -> setButtonSize(300, 300)); // } // // private void setButtonSize(int x, int y) { // // ViewWrapper viewWrapper = new ViewWrapper(animator1Btn); // // // 动画集合,同时执行下面的动画效果 // AnimatorSet set = new AnimatorSet(); // set.playTogether( // ObjectAnimator.ofInt(viewWrapper, "width", // ConvertUtils.dp2px(x)), // ObjectAnimator.ofInt(viewWrapper, "height", // ConvertUtils.dp2px(y)) // ); // // set.setDuration(5000).start(); // } // // /** // * 用一个类来包装原始对象,间接为其提供get和set方法 // * 对象的大小要在xml定死,不然与预想的效果不一样 // */ // private class ViewWrapper { // private View mTarget; // // public ViewWrapper(View target) { // mTarget = target; // } // // public int getWidth() { // return mTarget.getLayoutParams().width; // } // // public void setWidth(int width) { // mTarget.getLayoutParams().width = width; // mTarget.requestLayout(); // } // // public int getHeight() { // return mTarget.getLayoutParams().height; // } // // public void setHeight(int height) { // mTarget.getLayoutParams().height = height; // mTarget.requestLayout(); // } // } // } // // Path: app/src/main/java/com/sdwfqin/sample/view/motionslop/MeTsActivity.java // public class MeTsActivity extends AppCompatActivity { // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_me_ts); // } // } // // Path: app/src/main/java/com/sdwfqin/sample/view/rippleanimation/RippleAnimationActivity.java // public class RippleAnimationActivity extends AppCompatActivity { // // @BindView(R.id.ImageView) // android.widget.ImageView mImageView; // @BindView(R.id.layout_RippleAnimation) // RippleAnimationView mLayoutRippleAnimation; // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_ripple_animation); // ButterKnife.bind(this); // // mImageView = findViewById(R.id.ImageView); // mLayoutRippleAnimation = findViewById(R.id.layout_RippleAnimation); // // mImageView.setOnClickListener(view -> { // if (mLayoutRippleAnimation.isRippleRunning()) { // mLayoutRippleAnimation.stopRippleAnimation(); // } else { // mLayoutRippleAnimation.startRippleAnimation(); // } // }); // } // } // Path: app/src/main/java/com/sdwfqin/sample/view/ViewActivity.java import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.ArrayAdapter; import android.widget.ListView; import com.sdwfqin.sample.R; import com.sdwfqin.sample.view.bottomzoom.BottomZoomActivity; import com.sdwfqin.sample.view.courtesycard.CourtesyCardActivity; import com.sdwfqin.sample.view.delbtn.DeleteButtonActivity; import com.sdwfqin.sample.view.descircle.DesCircleActivity; import com.sdwfqin.sample.view.gesturedetector.GestureDetectorActivity; import com.sdwfqin.sample.view.motionslop.MeTsActivity; import com.sdwfqin.sample.view.paypwdinput.PayPwdInputActivity; import com.sdwfqin.sample.view.rippleanimation.RippleAnimationActivity; import com.sdwfqin.sample.view.scroller.ScrollerActivity; import com.sdwfqin.sample.view.surface.SurfaceActivity; import com.sdwfqin.sample.view.surfacepalette.SurfacePaletteActivity; import com.sdwfqin.sample.view.viewevent.ViewEventActivity; import com.sdwfqin.sample.view.viewposition.ViewPositionActivity; import butterknife.BindView; import butterknife.ButterKnife; package com.sdwfqin.sample.view; /** * 描述:View相关 * * @author zhangqin */ public class ViewActivity extends AppCompatActivity { @BindView(R.id.list) ListView mViewList; private Context mContext; private String[] mStrings = new String[]{"View的位置参数", "MotionEvent与TouchSlop", "GestureDetector", "Scroller", "View触摸事件分发", "按钮放大(属性动画)", "自定义View1圆", "自定义View2凹凸边缘", "SurfaceView", "SurfaceView画板", "自定义输入密码", "网易云听歌识曲", "长按删除按钮"};
private Class[] mClasses = new Class[]{ViewPositionActivity.class, MeTsActivity.class,
sdwfqin/AndroidSamples
app/src/main/java/com/sdwfqin/sample/view/ViewActivity.java
// Path: app/src/main/java/com/sdwfqin/sample/view/bottomzoom/BottomZoomActivity.java // public class BottomZoomActivity extends AppCompatActivity { // // @BindView(R.id.animator1_btn) // Button animator1Btn; // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_animator1); // ButterKnife.bind(this); // // animator1Btn.setOnClickListener(v -> setButtonSize(300, 300)); // } // // private void setButtonSize(int x, int y) { // // ViewWrapper viewWrapper = new ViewWrapper(animator1Btn); // // // 动画集合,同时执行下面的动画效果 // AnimatorSet set = new AnimatorSet(); // set.playTogether( // ObjectAnimator.ofInt(viewWrapper, "width", // ConvertUtils.dp2px(x)), // ObjectAnimator.ofInt(viewWrapper, "height", // ConvertUtils.dp2px(y)) // ); // // set.setDuration(5000).start(); // } // // /** // * 用一个类来包装原始对象,间接为其提供get和set方法 // * 对象的大小要在xml定死,不然与预想的效果不一样 // */ // private class ViewWrapper { // private View mTarget; // // public ViewWrapper(View target) { // mTarget = target; // } // // public int getWidth() { // return mTarget.getLayoutParams().width; // } // // public void setWidth(int width) { // mTarget.getLayoutParams().width = width; // mTarget.requestLayout(); // } // // public int getHeight() { // return mTarget.getLayoutParams().height; // } // // public void setHeight(int height) { // mTarget.getLayoutParams().height = height; // mTarget.requestLayout(); // } // } // } // // Path: app/src/main/java/com/sdwfqin/sample/view/motionslop/MeTsActivity.java // public class MeTsActivity extends AppCompatActivity { // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_me_ts); // } // } // // Path: app/src/main/java/com/sdwfqin/sample/view/rippleanimation/RippleAnimationActivity.java // public class RippleAnimationActivity extends AppCompatActivity { // // @BindView(R.id.ImageView) // android.widget.ImageView mImageView; // @BindView(R.id.layout_RippleAnimation) // RippleAnimationView mLayoutRippleAnimation; // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_ripple_animation); // ButterKnife.bind(this); // // mImageView = findViewById(R.id.ImageView); // mLayoutRippleAnimation = findViewById(R.id.layout_RippleAnimation); // // mImageView.setOnClickListener(view -> { // if (mLayoutRippleAnimation.isRippleRunning()) { // mLayoutRippleAnimation.stopRippleAnimation(); // } else { // mLayoutRippleAnimation.startRippleAnimation(); // } // }); // } // }
import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.ArrayAdapter; import android.widget.ListView; import com.sdwfqin.sample.R; import com.sdwfqin.sample.view.bottomzoom.BottomZoomActivity; import com.sdwfqin.sample.view.courtesycard.CourtesyCardActivity; import com.sdwfqin.sample.view.delbtn.DeleteButtonActivity; import com.sdwfqin.sample.view.descircle.DesCircleActivity; import com.sdwfqin.sample.view.gesturedetector.GestureDetectorActivity; import com.sdwfqin.sample.view.motionslop.MeTsActivity; import com.sdwfqin.sample.view.paypwdinput.PayPwdInputActivity; import com.sdwfqin.sample.view.rippleanimation.RippleAnimationActivity; import com.sdwfqin.sample.view.scroller.ScrollerActivity; import com.sdwfqin.sample.view.surface.SurfaceActivity; import com.sdwfqin.sample.view.surfacepalette.SurfacePaletteActivity; import com.sdwfqin.sample.view.viewevent.ViewEventActivity; import com.sdwfqin.sample.view.viewposition.ViewPositionActivity; import butterknife.BindView; import butterknife.ButterKnife;
package com.sdwfqin.sample.view; /** * 描述:View相关 * * @author zhangqin */ public class ViewActivity extends AppCompatActivity { @BindView(R.id.list) ListView mViewList; private Context mContext; private String[] mStrings = new String[]{"View的位置参数", "MotionEvent与TouchSlop", "GestureDetector", "Scroller", "View触摸事件分发", "按钮放大(属性动画)", "自定义View1圆", "自定义View2凹凸边缘", "SurfaceView", "SurfaceView画板", "自定义输入密码", "网易云听歌识曲", "长按删除按钮"}; private Class[] mClasses = new Class[]{ViewPositionActivity.class, MeTsActivity.class, GestureDetectorActivity.class, ScrollerActivity.class, ViewEventActivity.class,
// Path: app/src/main/java/com/sdwfqin/sample/view/bottomzoom/BottomZoomActivity.java // public class BottomZoomActivity extends AppCompatActivity { // // @BindView(R.id.animator1_btn) // Button animator1Btn; // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_animator1); // ButterKnife.bind(this); // // animator1Btn.setOnClickListener(v -> setButtonSize(300, 300)); // } // // private void setButtonSize(int x, int y) { // // ViewWrapper viewWrapper = new ViewWrapper(animator1Btn); // // // 动画集合,同时执行下面的动画效果 // AnimatorSet set = new AnimatorSet(); // set.playTogether( // ObjectAnimator.ofInt(viewWrapper, "width", // ConvertUtils.dp2px(x)), // ObjectAnimator.ofInt(viewWrapper, "height", // ConvertUtils.dp2px(y)) // ); // // set.setDuration(5000).start(); // } // // /** // * 用一个类来包装原始对象,间接为其提供get和set方法 // * 对象的大小要在xml定死,不然与预想的效果不一样 // */ // private class ViewWrapper { // private View mTarget; // // public ViewWrapper(View target) { // mTarget = target; // } // // public int getWidth() { // return mTarget.getLayoutParams().width; // } // // public void setWidth(int width) { // mTarget.getLayoutParams().width = width; // mTarget.requestLayout(); // } // // public int getHeight() { // return mTarget.getLayoutParams().height; // } // // public void setHeight(int height) { // mTarget.getLayoutParams().height = height; // mTarget.requestLayout(); // } // } // } // // Path: app/src/main/java/com/sdwfqin/sample/view/motionslop/MeTsActivity.java // public class MeTsActivity extends AppCompatActivity { // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_me_ts); // } // } // // Path: app/src/main/java/com/sdwfqin/sample/view/rippleanimation/RippleAnimationActivity.java // public class RippleAnimationActivity extends AppCompatActivity { // // @BindView(R.id.ImageView) // android.widget.ImageView mImageView; // @BindView(R.id.layout_RippleAnimation) // RippleAnimationView mLayoutRippleAnimation; // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_ripple_animation); // ButterKnife.bind(this); // // mImageView = findViewById(R.id.ImageView); // mLayoutRippleAnimation = findViewById(R.id.layout_RippleAnimation); // // mImageView.setOnClickListener(view -> { // if (mLayoutRippleAnimation.isRippleRunning()) { // mLayoutRippleAnimation.stopRippleAnimation(); // } else { // mLayoutRippleAnimation.startRippleAnimation(); // } // }); // } // } // Path: app/src/main/java/com/sdwfqin/sample/view/ViewActivity.java import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.ArrayAdapter; import android.widget.ListView; import com.sdwfqin.sample.R; import com.sdwfqin.sample.view.bottomzoom.BottomZoomActivity; import com.sdwfqin.sample.view.courtesycard.CourtesyCardActivity; import com.sdwfqin.sample.view.delbtn.DeleteButtonActivity; import com.sdwfqin.sample.view.descircle.DesCircleActivity; import com.sdwfqin.sample.view.gesturedetector.GestureDetectorActivity; import com.sdwfqin.sample.view.motionslop.MeTsActivity; import com.sdwfqin.sample.view.paypwdinput.PayPwdInputActivity; import com.sdwfqin.sample.view.rippleanimation.RippleAnimationActivity; import com.sdwfqin.sample.view.scroller.ScrollerActivity; import com.sdwfqin.sample.view.surface.SurfaceActivity; import com.sdwfqin.sample.view.surfacepalette.SurfacePaletteActivity; import com.sdwfqin.sample.view.viewevent.ViewEventActivity; import com.sdwfqin.sample.view.viewposition.ViewPositionActivity; import butterknife.BindView; import butterknife.ButterKnife; package com.sdwfqin.sample.view; /** * 描述:View相关 * * @author zhangqin */ public class ViewActivity extends AppCompatActivity { @BindView(R.id.list) ListView mViewList; private Context mContext; private String[] mStrings = new String[]{"View的位置参数", "MotionEvent与TouchSlop", "GestureDetector", "Scroller", "View触摸事件分发", "按钮放大(属性动画)", "自定义View1圆", "自定义View2凹凸边缘", "SurfaceView", "SurfaceView画板", "自定义输入密码", "网易云听歌识曲", "长按删除按钮"}; private Class[] mClasses = new Class[]{ViewPositionActivity.class, MeTsActivity.class, GestureDetectorActivity.class, ScrollerActivity.class, ViewEventActivity.class,
BottomZoomActivity.class, DesCircleActivity.class, CourtesyCardActivity.class, SurfaceActivity.class,
sdwfqin/AndroidSamples
app/src/main/java/com/sdwfqin/sample/view/ViewActivity.java
// Path: app/src/main/java/com/sdwfqin/sample/view/bottomzoom/BottomZoomActivity.java // public class BottomZoomActivity extends AppCompatActivity { // // @BindView(R.id.animator1_btn) // Button animator1Btn; // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_animator1); // ButterKnife.bind(this); // // animator1Btn.setOnClickListener(v -> setButtonSize(300, 300)); // } // // private void setButtonSize(int x, int y) { // // ViewWrapper viewWrapper = new ViewWrapper(animator1Btn); // // // 动画集合,同时执行下面的动画效果 // AnimatorSet set = new AnimatorSet(); // set.playTogether( // ObjectAnimator.ofInt(viewWrapper, "width", // ConvertUtils.dp2px(x)), // ObjectAnimator.ofInt(viewWrapper, "height", // ConvertUtils.dp2px(y)) // ); // // set.setDuration(5000).start(); // } // // /** // * 用一个类来包装原始对象,间接为其提供get和set方法 // * 对象的大小要在xml定死,不然与预想的效果不一样 // */ // private class ViewWrapper { // private View mTarget; // // public ViewWrapper(View target) { // mTarget = target; // } // // public int getWidth() { // return mTarget.getLayoutParams().width; // } // // public void setWidth(int width) { // mTarget.getLayoutParams().width = width; // mTarget.requestLayout(); // } // // public int getHeight() { // return mTarget.getLayoutParams().height; // } // // public void setHeight(int height) { // mTarget.getLayoutParams().height = height; // mTarget.requestLayout(); // } // } // } // // Path: app/src/main/java/com/sdwfqin/sample/view/motionslop/MeTsActivity.java // public class MeTsActivity extends AppCompatActivity { // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_me_ts); // } // } // // Path: app/src/main/java/com/sdwfqin/sample/view/rippleanimation/RippleAnimationActivity.java // public class RippleAnimationActivity extends AppCompatActivity { // // @BindView(R.id.ImageView) // android.widget.ImageView mImageView; // @BindView(R.id.layout_RippleAnimation) // RippleAnimationView mLayoutRippleAnimation; // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_ripple_animation); // ButterKnife.bind(this); // // mImageView = findViewById(R.id.ImageView); // mLayoutRippleAnimation = findViewById(R.id.layout_RippleAnimation); // // mImageView.setOnClickListener(view -> { // if (mLayoutRippleAnimation.isRippleRunning()) { // mLayoutRippleAnimation.stopRippleAnimation(); // } else { // mLayoutRippleAnimation.startRippleAnimation(); // } // }); // } // }
import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.ArrayAdapter; import android.widget.ListView; import com.sdwfqin.sample.R; import com.sdwfqin.sample.view.bottomzoom.BottomZoomActivity; import com.sdwfqin.sample.view.courtesycard.CourtesyCardActivity; import com.sdwfqin.sample.view.delbtn.DeleteButtonActivity; import com.sdwfqin.sample.view.descircle.DesCircleActivity; import com.sdwfqin.sample.view.gesturedetector.GestureDetectorActivity; import com.sdwfqin.sample.view.motionslop.MeTsActivity; import com.sdwfqin.sample.view.paypwdinput.PayPwdInputActivity; import com.sdwfqin.sample.view.rippleanimation.RippleAnimationActivity; import com.sdwfqin.sample.view.scroller.ScrollerActivity; import com.sdwfqin.sample.view.surface.SurfaceActivity; import com.sdwfqin.sample.view.surfacepalette.SurfacePaletteActivity; import com.sdwfqin.sample.view.viewevent.ViewEventActivity; import com.sdwfqin.sample.view.viewposition.ViewPositionActivity; import butterknife.BindView; import butterknife.ButterKnife;
package com.sdwfqin.sample.view; /** * 描述:View相关 * * @author zhangqin */ public class ViewActivity extends AppCompatActivity { @BindView(R.id.list) ListView mViewList; private Context mContext; private String[] mStrings = new String[]{"View的位置参数", "MotionEvent与TouchSlop", "GestureDetector", "Scroller", "View触摸事件分发", "按钮放大(属性动画)", "自定义View1圆", "自定义View2凹凸边缘", "SurfaceView", "SurfaceView画板", "自定义输入密码", "网易云听歌识曲", "长按删除按钮"}; private Class[] mClasses = new Class[]{ViewPositionActivity.class, MeTsActivity.class, GestureDetectorActivity.class, ScrollerActivity.class, ViewEventActivity.class, BottomZoomActivity.class, DesCircleActivity.class, CourtesyCardActivity.class, SurfaceActivity.class, SurfacePaletteActivity.class, PayPwdInputActivity.class,
// Path: app/src/main/java/com/sdwfqin/sample/view/bottomzoom/BottomZoomActivity.java // public class BottomZoomActivity extends AppCompatActivity { // // @BindView(R.id.animator1_btn) // Button animator1Btn; // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_animator1); // ButterKnife.bind(this); // // animator1Btn.setOnClickListener(v -> setButtonSize(300, 300)); // } // // private void setButtonSize(int x, int y) { // // ViewWrapper viewWrapper = new ViewWrapper(animator1Btn); // // // 动画集合,同时执行下面的动画效果 // AnimatorSet set = new AnimatorSet(); // set.playTogether( // ObjectAnimator.ofInt(viewWrapper, "width", // ConvertUtils.dp2px(x)), // ObjectAnimator.ofInt(viewWrapper, "height", // ConvertUtils.dp2px(y)) // ); // // set.setDuration(5000).start(); // } // // /** // * 用一个类来包装原始对象,间接为其提供get和set方法 // * 对象的大小要在xml定死,不然与预想的效果不一样 // */ // private class ViewWrapper { // private View mTarget; // // public ViewWrapper(View target) { // mTarget = target; // } // // public int getWidth() { // return mTarget.getLayoutParams().width; // } // // public void setWidth(int width) { // mTarget.getLayoutParams().width = width; // mTarget.requestLayout(); // } // // public int getHeight() { // return mTarget.getLayoutParams().height; // } // // public void setHeight(int height) { // mTarget.getLayoutParams().height = height; // mTarget.requestLayout(); // } // } // } // // Path: app/src/main/java/com/sdwfqin/sample/view/motionslop/MeTsActivity.java // public class MeTsActivity extends AppCompatActivity { // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_me_ts); // } // } // // Path: app/src/main/java/com/sdwfqin/sample/view/rippleanimation/RippleAnimationActivity.java // public class RippleAnimationActivity extends AppCompatActivity { // // @BindView(R.id.ImageView) // android.widget.ImageView mImageView; // @BindView(R.id.layout_RippleAnimation) // RippleAnimationView mLayoutRippleAnimation; // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_ripple_animation); // ButterKnife.bind(this); // // mImageView = findViewById(R.id.ImageView); // mLayoutRippleAnimation = findViewById(R.id.layout_RippleAnimation); // // mImageView.setOnClickListener(view -> { // if (mLayoutRippleAnimation.isRippleRunning()) { // mLayoutRippleAnimation.stopRippleAnimation(); // } else { // mLayoutRippleAnimation.startRippleAnimation(); // } // }); // } // } // Path: app/src/main/java/com/sdwfqin/sample/view/ViewActivity.java import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.ArrayAdapter; import android.widget.ListView; import com.sdwfqin.sample.R; import com.sdwfqin.sample.view.bottomzoom.BottomZoomActivity; import com.sdwfqin.sample.view.courtesycard.CourtesyCardActivity; import com.sdwfqin.sample.view.delbtn.DeleteButtonActivity; import com.sdwfqin.sample.view.descircle.DesCircleActivity; import com.sdwfqin.sample.view.gesturedetector.GestureDetectorActivity; import com.sdwfqin.sample.view.motionslop.MeTsActivity; import com.sdwfqin.sample.view.paypwdinput.PayPwdInputActivity; import com.sdwfqin.sample.view.rippleanimation.RippleAnimationActivity; import com.sdwfqin.sample.view.scroller.ScrollerActivity; import com.sdwfqin.sample.view.surface.SurfaceActivity; import com.sdwfqin.sample.view.surfacepalette.SurfacePaletteActivity; import com.sdwfqin.sample.view.viewevent.ViewEventActivity; import com.sdwfqin.sample.view.viewposition.ViewPositionActivity; import butterknife.BindView; import butterknife.ButterKnife; package com.sdwfqin.sample.view; /** * 描述:View相关 * * @author zhangqin */ public class ViewActivity extends AppCompatActivity { @BindView(R.id.list) ListView mViewList; private Context mContext; private String[] mStrings = new String[]{"View的位置参数", "MotionEvent与TouchSlop", "GestureDetector", "Scroller", "View触摸事件分发", "按钮放大(属性动画)", "自定义View1圆", "自定义View2凹凸边缘", "SurfaceView", "SurfaceView画板", "自定义输入密码", "网易云听歌识曲", "长按删除按钮"}; private Class[] mClasses = new Class[]{ViewPositionActivity.class, MeTsActivity.class, GestureDetectorActivity.class, ScrollerActivity.class, ViewEventActivity.class, BottomZoomActivity.class, DesCircleActivity.class, CourtesyCardActivity.class, SurfaceActivity.class, SurfacePaletteActivity.class, PayPwdInputActivity.class,
RippleAnimationActivity.class, DeleteButtonActivity.class};
google/firing-range
src/tests/urldom/Redirect.java
// Path: src/utils/Responses.java // @Immutable // public final class Responses { // // private Responses() {} // // /** // * Sends a "normal" response, with all the standard headers. // */ // public static void sendNormalPage(HttpServletResponse response, String body) throws IOException { // response.setHeader(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate"); // response.setHeader(HttpHeaders.PRAGMA, "no-cache"); // response.setDateHeader(HttpHeaders.EXPIRES, 0); // response.setHeader(HttpHeaders.CONTENT_TYPE, "text/html; charset=utf-8"); // response.setStatus(200); // response.getWriter().write(body); // } // // /** // * Sends an XSS response. // */ // public static void sendXssed(HttpServletResponse response, String body) throws IOException { // sendXssed(response, body, "text/html; charset=utf-8"); // } // // /** // * Sends an HTML XSSed response with the given status. // */ // public static void sendXssed(HttpServletResponse response, String body, int status) // throws IOException { // sendXssed(response, body, "text/html; charset=utf-8", status); // } // // /** // * Sends an XSS response of a given type. // */ // public static void sendXssed(HttpServletResponse response, String body, String contentType) // throws IOException { // sendXssed(response, body, contentType, 200); // } // // /** // * Sends an XSS response of a given type. // */ // public static void sendXssed(HttpServletResponse response, String body, String contentType, // int status) throws IOException { // response.setHeader(HttpHeaders.X_XSS_PROTECTION, "0"); // response.setHeader(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate"); // response.setHeader(HttpHeaders.PRAGMA, "no-cache"); // response.setDateHeader(HttpHeaders.EXPIRES, 0); // response.setHeader(HttpHeaders.CONTENT_TYPE, contentType); // response.setStatus(status); // response.getWriter().write(body); // } // // /** // * Sends an error to the user with the given {@code status} and body. // */ // public static void sendError(HttpServletResponse response, String body, int status) // throws IOException { // Preconditions.checkArgument(status > 300); // response.setStatus(status); // response.setHeader(HttpHeaders.CONTENT_TYPE, "text/plain"); // response.getWriter().write(Escaper.escapeHtml(body)); // } // // /** // * Sends a response with the content type text/javascript. // */ // public static void sendJavaScript(HttpServletResponse response, String body) // throws IOException { // response.setHeader(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate"); // response.setHeader(HttpHeaders.PRAGMA, "no-cache"); // response.setDateHeader(HttpHeaders.EXPIRES, 0); // response.setHeader(HttpHeaders.CONTENT_TYPE, "text/javascript"); // response.setStatus(200); // response.getWriter().write(body); // } // // /** // * Sends a redirect to the user. // */ // public static void sendRedirect(HttpServletResponse response, String location) { // response.setStatus(302); // response.setHeader(HttpHeaders.LOCATION, location); // } // }
import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Strings; import com.google.testing.security.firingrange.utils.Responses; import java.io.IOException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
/* * Copyright 2016 Google Inc. All rights reserved. * * 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 com.google.testing.security.firingrange.tests.urldom; /** * Provides open redirection service except to URI with JavaScript URI scheme. */ public class Redirect extends HttpServlet { @VisibleForTesting static final String REDIRECT_PARAM = "url"; @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { String redirectParam = Strings.nullToEmpty(request.getParameter(REDIRECT_PARAM)); if (!redirectParam.isEmpty()) {
// Path: src/utils/Responses.java // @Immutable // public final class Responses { // // private Responses() {} // // /** // * Sends a "normal" response, with all the standard headers. // */ // public static void sendNormalPage(HttpServletResponse response, String body) throws IOException { // response.setHeader(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate"); // response.setHeader(HttpHeaders.PRAGMA, "no-cache"); // response.setDateHeader(HttpHeaders.EXPIRES, 0); // response.setHeader(HttpHeaders.CONTENT_TYPE, "text/html; charset=utf-8"); // response.setStatus(200); // response.getWriter().write(body); // } // // /** // * Sends an XSS response. // */ // public static void sendXssed(HttpServletResponse response, String body) throws IOException { // sendXssed(response, body, "text/html; charset=utf-8"); // } // // /** // * Sends an HTML XSSed response with the given status. // */ // public static void sendXssed(HttpServletResponse response, String body, int status) // throws IOException { // sendXssed(response, body, "text/html; charset=utf-8", status); // } // // /** // * Sends an XSS response of a given type. // */ // public static void sendXssed(HttpServletResponse response, String body, String contentType) // throws IOException { // sendXssed(response, body, contentType, 200); // } // // /** // * Sends an XSS response of a given type. // */ // public static void sendXssed(HttpServletResponse response, String body, String contentType, // int status) throws IOException { // response.setHeader(HttpHeaders.X_XSS_PROTECTION, "0"); // response.setHeader(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate"); // response.setHeader(HttpHeaders.PRAGMA, "no-cache"); // response.setDateHeader(HttpHeaders.EXPIRES, 0); // response.setHeader(HttpHeaders.CONTENT_TYPE, contentType); // response.setStatus(status); // response.getWriter().write(body); // } // // /** // * Sends an error to the user with the given {@code status} and body. // */ // public static void sendError(HttpServletResponse response, String body, int status) // throws IOException { // Preconditions.checkArgument(status > 300); // response.setStatus(status); // response.setHeader(HttpHeaders.CONTENT_TYPE, "text/plain"); // response.getWriter().write(Escaper.escapeHtml(body)); // } // // /** // * Sends a response with the content type text/javascript. // */ // public static void sendJavaScript(HttpServletResponse response, String body) // throws IOException { // response.setHeader(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate"); // response.setHeader(HttpHeaders.PRAGMA, "no-cache"); // response.setDateHeader(HttpHeaders.EXPIRES, 0); // response.setHeader(HttpHeaders.CONTENT_TYPE, "text/javascript"); // response.setStatus(200); // response.getWriter().write(body); // } // // /** // * Sends a redirect to the user. // */ // public static void sendRedirect(HttpServletResponse response, String location) { // response.setStatus(302); // response.setHeader(HttpHeaders.LOCATION, location); // } // } // Path: src/tests/urldom/Redirect.java import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Strings; import com.google.testing.security.firingrange.utils.Responses; import java.io.IOException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /* * Copyright 2016 Google Inc. All rights reserved. * * 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 com.google.testing.security.firingrange.tests.urldom; /** * Provides open redirection service except to URI with JavaScript URI scheme. */ public class Redirect extends HttpServlet { @VisibleForTesting static final String REDIRECT_PARAM = "url"; @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { String redirectParam = Strings.nullToEmpty(request.getParameter(REDIRECT_PARAM)); if (!redirectParam.isEmpty()) {
Responses.sendRedirect(response, redirectParam);
google/firing-range
src/tests/tags/Expression.java
// Path: src/utils/Responses.java // @Immutable // public final class Responses { // // private Responses() {} // // /** // * Sends a "normal" response, with all the standard headers. // */ // public static void sendNormalPage(HttpServletResponse response, String body) throws IOException { // response.setHeader(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate"); // response.setHeader(HttpHeaders.PRAGMA, "no-cache"); // response.setDateHeader(HttpHeaders.EXPIRES, 0); // response.setHeader(HttpHeaders.CONTENT_TYPE, "text/html; charset=utf-8"); // response.setStatus(200); // response.getWriter().write(body); // } // // /** // * Sends an XSS response. // */ // public static void sendXssed(HttpServletResponse response, String body) throws IOException { // sendXssed(response, body, "text/html; charset=utf-8"); // } // // /** // * Sends an HTML XSSed response with the given status. // */ // public static void sendXssed(HttpServletResponse response, String body, int status) // throws IOException { // sendXssed(response, body, "text/html; charset=utf-8", status); // } // // /** // * Sends an XSS response of a given type. // */ // public static void sendXssed(HttpServletResponse response, String body, String contentType) // throws IOException { // sendXssed(response, body, contentType, 200); // } // // /** // * Sends an XSS response of a given type. // */ // public static void sendXssed(HttpServletResponse response, String body, String contentType, // int status) throws IOException { // response.setHeader(HttpHeaders.X_XSS_PROTECTION, "0"); // response.setHeader(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate"); // response.setHeader(HttpHeaders.PRAGMA, "no-cache"); // response.setDateHeader(HttpHeaders.EXPIRES, 0); // response.setHeader(HttpHeaders.CONTENT_TYPE, contentType); // response.setStatus(status); // response.getWriter().write(body); // } // // /** // * Sends an error to the user with the given {@code status} and body. // */ // public static void sendError(HttpServletResponse response, String body, int status) // throws IOException { // Preconditions.checkArgument(status > 300); // response.setStatus(status); // response.setHeader(HttpHeaders.CONTENT_TYPE, "text/plain"); // response.getWriter().write(Escaper.escapeHtml(body)); // } // // /** // * Sends a response with the content type text/javascript. // */ // public static void sendJavaScript(HttpServletResponse response, String body) // throws IOException { // response.setHeader(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate"); // response.setHeader(HttpHeaders.PRAGMA, "no-cache"); // response.setDateHeader(HttpHeaders.EXPIRES, 0); // response.setHeader(HttpHeaders.CONTENT_TYPE, "text/javascript"); // response.setStatus(200); // response.getWriter().write(body); // } // // /** // * Sends a redirect to the user. // */ // public static void sendRedirect(HttpServletResponse response, String location) { // response.setStatus(302); // response.setHeader(HttpHeaders.LOCATION, location); // } // }
import com.google.testing.security.firingrange.utils.Responses; import org.jsoup.Jsoup; import org.jsoup.nodes.Attribute; import org.jsoup.nodes.Attributes; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.io.IOException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
/* *Copyright 2014 Google Inc. All rights reserved. * * 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 com.google.testing.security.firingrange.tests.tags; /** * A class only allowing tags, but filtering out event handlers. It only allows style as a property, * but explicitly blocks the word "expression" in the style. */ public class Expression extends HttpServlet { @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { if (request.getParameter("q") == null) {
// Path: src/utils/Responses.java // @Immutable // public final class Responses { // // private Responses() {} // // /** // * Sends a "normal" response, with all the standard headers. // */ // public static void sendNormalPage(HttpServletResponse response, String body) throws IOException { // response.setHeader(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate"); // response.setHeader(HttpHeaders.PRAGMA, "no-cache"); // response.setDateHeader(HttpHeaders.EXPIRES, 0); // response.setHeader(HttpHeaders.CONTENT_TYPE, "text/html; charset=utf-8"); // response.setStatus(200); // response.getWriter().write(body); // } // // /** // * Sends an XSS response. // */ // public static void sendXssed(HttpServletResponse response, String body) throws IOException { // sendXssed(response, body, "text/html; charset=utf-8"); // } // // /** // * Sends an HTML XSSed response with the given status. // */ // public static void sendXssed(HttpServletResponse response, String body, int status) // throws IOException { // sendXssed(response, body, "text/html; charset=utf-8", status); // } // // /** // * Sends an XSS response of a given type. // */ // public static void sendXssed(HttpServletResponse response, String body, String contentType) // throws IOException { // sendXssed(response, body, contentType, 200); // } // // /** // * Sends an XSS response of a given type. // */ // public static void sendXssed(HttpServletResponse response, String body, String contentType, // int status) throws IOException { // response.setHeader(HttpHeaders.X_XSS_PROTECTION, "0"); // response.setHeader(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate"); // response.setHeader(HttpHeaders.PRAGMA, "no-cache"); // response.setDateHeader(HttpHeaders.EXPIRES, 0); // response.setHeader(HttpHeaders.CONTENT_TYPE, contentType); // response.setStatus(status); // response.getWriter().write(body); // } // // /** // * Sends an error to the user with the given {@code status} and body. // */ // public static void sendError(HttpServletResponse response, String body, int status) // throws IOException { // Preconditions.checkArgument(status > 300); // response.setStatus(status); // response.setHeader(HttpHeaders.CONTENT_TYPE, "text/plain"); // response.getWriter().write(Escaper.escapeHtml(body)); // } // // /** // * Sends a response with the content type text/javascript. // */ // public static void sendJavaScript(HttpServletResponse response, String body) // throws IOException { // response.setHeader(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate"); // response.setHeader(HttpHeaders.PRAGMA, "no-cache"); // response.setDateHeader(HttpHeaders.EXPIRES, 0); // response.setHeader(HttpHeaders.CONTENT_TYPE, "text/javascript"); // response.setStatus(200); // response.getWriter().write(body); // } // // /** // * Sends a redirect to the user. // */ // public static void sendRedirect(HttpServletResponse response, String location) { // response.setStatus(302); // response.setHeader(HttpHeaders.LOCATION, location); // } // } // Path: src/tests/tags/Expression.java import com.google.testing.security.firingrange.utils.Responses; import org.jsoup.Jsoup; import org.jsoup.nodes.Attribute; import org.jsoup.nodes.Attributes; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.io.IOException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /* *Copyright 2014 Google Inc. All rights reserved. * * 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 com.google.testing.security.firingrange.tests.tags; /** * A class only allowing tags, but filtering out event handlers. It only allows style as a property, * but explicitly blocks the word "expression" in the style. */ public class Expression extends HttpServlet { @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { if (request.getParameter("q") == null) {
Responses.sendError(response, "Missing q parameter", 400);
google/firing-range
src/tests/cors/AllowInsecureScheme.java
// Path: src/utils/Requests.java // public final class Requests { // /** Prevents instantiation. */ // private Requests() {} // // /** // * Gets the base URL of the servlet. // */ // public static String getBaseUrl(HttpServletRequest request) { // String base = request.getScheme() + "://" + request.getServerName(); // if (request.getServerPort() == -1 // || (request.getServerPort() == 80 && request.getScheme().equals("http")) // || (request.getServerPort() == 443 && request.getScheme().equals("https"))) { // return base; // } // return base + ":" + request.getServerPort(); // } // }
import com.google.testing.security.firingrange.utils.Requests; import javax.servlet.http.HttpServletRequest; import com.google.common.base.Strings;
/* * Copyright 2017 Google Inc. All rights reserved. * * 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 com.google.testing.security.firingrange.tests.cors; /** * Servlet that doesn't reflect arbitrary origins in the {@code Access-Control-Allow-Origin} header * but allows setting an HTTP scheme on an HTTPS resource. */ public final class AllowInsecureScheme extends AllowOriginServlet { @Override protected String getAllowOriginValue(HttpServletRequest request) { String origin = Strings.nullToEmpty(request.getHeader("Origin")); String scheme = origin.startsWith("http:") ? "http" : "https";
// Path: src/utils/Requests.java // public final class Requests { // /** Prevents instantiation. */ // private Requests() {} // // /** // * Gets the base URL of the servlet. // */ // public static String getBaseUrl(HttpServletRequest request) { // String base = request.getScheme() + "://" + request.getServerName(); // if (request.getServerPort() == -1 // || (request.getServerPort() == 80 && request.getScheme().equals("http")) // || (request.getServerPort() == 443 && request.getScheme().equals("https"))) { // return base; // } // return base + ":" + request.getServerPort(); // } // } // Path: src/tests/cors/AllowInsecureScheme.java import com.google.testing.security.firingrange.utils.Requests; import javax.servlet.http.HttpServletRequest; import com.google.common.base.Strings; /* * Copyright 2017 Google Inc. All rights reserved. * * 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 com.google.testing.security.firingrange.tests.cors; /** * Servlet that doesn't reflect arbitrary origins in the {@code Access-Control-Allow-Origin} header * but allows setting an HTTP scheme on an HTTPS resource. */ public final class AllowInsecureScheme extends AllowOriginServlet { @Override protected String getAllowOriginValue(HttpServletRequest request) { String origin = Strings.nullToEmpty(request.getHeader("Origin")); String scheme = origin.startsWith("http:") ? "http" : "https";
String baseUrl = Requests.getBaseUrl(request);
google/firing-range
src/tests/tags/Multiline.java
// Path: src/utils/Responses.java // @Immutable // public final class Responses { // // private Responses() {} // // /** // * Sends a "normal" response, with all the standard headers. // */ // public static void sendNormalPage(HttpServletResponse response, String body) throws IOException { // response.setHeader(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate"); // response.setHeader(HttpHeaders.PRAGMA, "no-cache"); // response.setDateHeader(HttpHeaders.EXPIRES, 0); // response.setHeader(HttpHeaders.CONTENT_TYPE, "text/html; charset=utf-8"); // response.setStatus(200); // response.getWriter().write(body); // } // // /** // * Sends an XSS response. // */ // public static void sendXssed(HttpServletResponse response, String body) throws IOException { // sendXssed(response, body, "text/html; charset=utf-8"); // } // // /** // * Sends an HTML XSSed response with the given status. // */ // public static void sendXssed(HttpServletResponse response, String body, int status) // throws IOException { // sendXssed(response, body, "text/html; charset=utf-8", status); // } // // /** // * Sends an XSS response of a given type. // */ // public static void sendXssed(HttpServletResponse response, String body, String contentType) // throws IOException { // sendXssed(response, body, contentType, 200); // } // // /** // * Sends an XSS response of a given type. // */ // public static void sendXssed(HttpServletResponse response, String body, String contentType, // int status) throws IOException { // response.setHeader(HttpHeaders.X_XSS_PROTECTION, "0"); // response.setHeader(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate"); // response.setHeader(HttpHeaders.PRAGMA, "no-cache"); // response.setDateHeader(HttpHeaders.EXPIRES, 0); // response.setHeader(HttpHeaders.CONTENT_TYPE, contentType); // response.setStatus(status); // response.getWriter().write(body); // } // // /** // * Sends an error to the user with the given {@code status} and body. // */ // public static void sendError(HttpServletResponse response, String body, int status) // throws IOException { // Preconditions.checkArgument(status > 300); // response.setStatus(status); // response.setHeader(HttpHeaders.CONTENT_TYPE, "text/plain"); // response.getWriter().write(Escaper.escapeHtml(body)); // } // // /** // * Sends a response with the content type text/javascript. // */ // public static void sendJavaScript(HttpServletResponse response, String body) // throws IOException { // response.setHeader(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate"); // response.setHeader(HttpHeaders.PRAGMA, "no-cache"); // response.setDateHeader(HttpHeaders.EXPIRES, 0); // response.setHeader(HttpHeaders.CONTENT_TYPE, "text/javascript"); // response.setStatus(200); // response.getWriter().write(body); // } // // /** // * Sends a redirect to the user. // */ // public static void sendRedirect(HttpServletResponse response, String location) { // response.setStatus(302); // response.setHeader(HttpHeaders.LOCATION, location); // } // }
import com.google.common.base.Strings; import com.google.testing.security.firingrange.utils.Responses; import java.io.IOException; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
/* *Copyright 2014 Google Inc. All rights reserved. * * 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 com.google.testing.security.firingrange.tests.tags; /** * This servlet will filter any tag but will be pierced by multiline requests. * Sample Payload: \r\n\r\n<script>alert(/1/)</script> */ public class Multiline extends HttpServlet { private static final Pattern TAG_FILTER = Pattern.compile("^.*<.*>.*$"); @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { String query = Strings.nullToEmpty(request.getParameter("q")); Matcher matcher = TAG_FILTER.matcher(query); if (matcher.matches()) { String error = "Invalid input, contains tags."; response.sendError(400, error); return; } String body = String.format("<html><body>%s</body></html>", query);
// Path: src/utils/Responses.java // @Immutable // public final class Responses { // // private Responses() {} // // /** // * Sends a "normal" response, with all the standard headers. // */ // public static void sendNormalPage(HttpServletResponse response, String body) throws IOException { // response.setHeader(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate"); // response.setHeader(HttpHeaders.PRAGMA, "no-cache"); // response.setDateHeader(HttpHeaders.EXPIRES, 0); // response.setHeader(HttpHeaders.CONTENT_TYPE, "text/html; charset=utf-8"); // response.setStatus(200); // response.getWriter().write(body); // } // // /** // * Sends an XSS response. // */ // public static void sendXssed(HttpServletResponse response, String body) throws IOException { // sendXssed(response, body, "text/html; charset=utf-8"); // } // // /** // * Sends an HTML XSSed response with the given status. // */ // public static void sendXssed(HttpServletResponse response, String body, int status) // throws IOException { // sendXssed(response, body, "text/html; charset=utf-8", status); // } // // /** // * Sends an XSS response of a given type. // */ // public static void sendXssed(HttpServletResponse response, String body, String contentType) // throws IOException { // sendXssed(response, body, contentType, 200); // } // // /** // * Sends an XSS response of a given type. // */ // public static void sendXssed(HttpServletResponse response, String body, String contentType, // int status) throws IOException { // response.setHeader(HttpHeaders.X_XSS_PROTECTION, "0"); // response.setHeader(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate"); // response.setHeader(HttpHeaders.PRAGMA, "no-cache"); // response.setDateHeader(HttpHeaders.EXPIRES, 0); // response.setHeader(HttpHeaders.CONTENT_TYPE, contentType); // response.setStatus(status); // response.getWriter().write(body); // } // // /** // * Sends an error to the user with the given {@code status} and body. // */ // public static void sendError(HttpServletResponse response, String body, int status) // throws IOException { // Preconditions.checkArgument(status > 300); // response.setStatus(status); // response.setHeader(HttpHeaders.CONTENT_TYPE, "text/plain"); // response.getWriter().write(Escaper.escapeHtml(body)); // } // // /** // * Sends a response with the content type text/javascript. // */ // public static void sendJavaScript(HttpServletResponse response, String body) // throws IOException { // response.setHeader(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate"); // response.setHeader(HttpHeaders.PRAGMA, "no-cache"); // response.setDateHeader(HttpHeaders.EXPIRES, 0); // response.setHeader(HttpHeaders.CONTENT_TYPE, "text/javascript"); // response.setStatus(200); // response.getWriter().write(body); // } // // /** // * Sends a redirect to the user. // */ // public static void sendRedirect(HttpServletResponse response, String location) { // response.setStatus(302); // response.setHeader(HttpHeaders.LOCATION, location); // } // } // Path: src/tests/tags/Multiline.java import com.google.common.base.Strings; import com.google.testing.security.firingrange.utils.Responses; import java.io.IOException; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /* *Copyright 2014 Google Inc. All rights reserved. * * 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 com.google.testing.security.firingrange.tests.tags; /** * This servlet will filter any tag but will be pierced by multiline requests. * Sample Payload: \r\n\r\n<script>alert(/1/)</script> */ public class Multiline extends HttpServlet { private static final Pattern TAG_FILTER = Pattern.compile("^.*<.*>.*$"); @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { String query = Strings.nullToEmpty(request.getParameter("q")); Matcher matcher = TAG_FILTER.matcher(query); if (matcher.matches()) { String error = "Invalid input, contains tags."; response.sendError(400, error); return; } String body = String.format("<html><body>%s</body></html>", query);
Responses.sendXssed(response, body);
google/firing-range
src/tests/reverseclickjacking/UniversalReverseClickjackingJsonpEndpoint.java
// Path: src/utils/Responses.java // @Immutable // public final class Responses { // // private Responses() {} // // /** // * Sends a "normal" response, with all the standard headers. // */ // public static void sendNormalPage(HttpServletResponse response, String body) throws IOException { // response.setHeader(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate"); // response.setHeader(HttpHeaders.PRAGMA, "no-cache"); // response.setDateHeader(HttpHeaders.EXPIRES, 0); // response.setHeader(HttpHeaders.CONTENT_TYPE, "text/html; charset=utf-8"); // response.setStatus(200); // response.getWriter().write(body); // } // // /** // * Sends an XSS response. // */ // public static void sendXssed(HttpServletResponse response, String body) throws IOException { // sendXssed(response, body, "text/html; charset=utf-8"); // } // // /** // * Sends an HTML XSSed response with the given status. // */ // public static void sendXssed(HttpServletResponse response, String body, int status) // throws IOException { // sendXssed(response, body, "text/html; charset=utf-8", status); // } // // /** // * Sends an XSS response of a given type. // */ // public static void sendXssed(HttpServletResponse response, String body, String contentType) // throws IOException { // sendXssed(response, body, contentType, 200); // } // // /** // * Sends an XSS response of a given type. // */ // public static void sendXssed(HttpServletResponse response, String body, String contentType, // int status) throws IOException { // response.setHeader(HttpHeaders.X_XSS_PROTECTION, "0"); // response.setHeader(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate"); // response.setHeader(HttpHeaders.PRAGMA, "no-cache"); // response.setDateHeader(HttpHeaders.EXPIRES, 0); // response.setHeader(HttpHeaders.CONTENT_TYPE, contentType); // response.setStatus(status); // response.getWriter().write(body); // } // // /** // * Sends an error to the user with the given {@code status} and body. // */ // public static void sendError(HttpServletResponse response, String body, int status) // throws IOException { // Preconditions.checkArgument(status > 300); // response.setStatus(status); // response.setHeader(HttpHeaders.CONTENT_TYPE, "text/plain"); // response.getWriter().write(Escaper.escapeHtml(body)); // } // // /** // * Sends a response with the content type text/javascript. // */ // public static void sendJavaScript(HttpServletResponse response, String body) // throws IOException { // response.setHeader(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate"); // response.setHeader(HttpHeaders.PRAGMA, "no-cache"); // response.setDateHeader(HttpHeaders.EXPIRES, 0); // response.setHeader(HttpHeaders.CONTENT_TYPE, "text/javascript"); // response.setStatus(200); // response.getWriter().write(body); // } // // /** // * Sends a redirect to the user. // */ // public static void sendRedirect(HttpServletResponse response, String location) { // response.setStatus(302); // response.setHeader(HttpHeaders.LOCATION, location); // } // }
import com.google.common.base.Strings; import com.google.testing.security.firingrange.utils.Responses; import java.io.IOException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
/* * Copyright 2014 Google Inc. All rights reserved. * * 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 com.google.testing.security.firingrange.tests.reverseclickjacking; /** * A sample JSONP endpoint and test case for URC, where the value of a parameter in the request is * used as a callback function. */ public class UniversalReverseClickjackingJsonpEndpoint extends HttpServlet { static final String CALLBACK_REGEX = "[a-zA-Z0-9][a-zA-Z0-9\\._]*"; static final String ECHOED_PARAM = "callback"; static final int MAX_CALLBACK_LENGTH = 100; @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { String echoedParam = Strings.nullToEmpty(request.getParameter(ECHOED_PARAM)); if (!echoedParam.matches(CALLBACK_REGEX) || echoedParam.length() > MAX_CALLBACK_LENGTH) {
// Path: src/utils/Responses.java // @Immutable // public final class Responses { // // private Responses() {} // // /** // * Sends a "normal" response, with all the standard headers. // */ // public static void sendNormalPage(HttpServletResponse response, String body) throws IOException { // response.setHeader(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate"); // response.setHeader(HttpHeaders.PRAGMA, "no-cache"); // response.setDateHeader(HttpHeaders.EXPIRES, 0); // response.setHeader(HttpHeaders.CONTENT_TYPE, "text/html; charset=utf-8"); // response.setStatus(200); // response.getWriter().write(body); // } // // /** // * Sends an XSS response. // */ // public static void sendXssed(HttpServletResponse response, String body) throws IOException { // sendXssed(response, body, "text/html; charset=utf-8"); // } // // /** // * Sends an HTML XSSed response with the given status. // */ // public static void sendXssed(HttpServletResponse response, String body, int status) // throws IOException { // sendXssed(response, body, "text/html; charset=utf-8", status); // } // // /** // * Sends an XSS response of a given type. // */ // public static void sendXssed(HttpServletResponse response, String body, String contentType) // throws IOException { // sendXssed(response, body, contentType, 200); // } // // /** // * Sends an XSS response of a given type. // */ // public static void sendXssed(HttpServletResponse response, String body, String contentType, // int status) throws IOException { // response.setHeader(HttpHeaders.X_XSS_PROTECTION, "0"); // response.setHeader(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate"); // response.setHeader(HttpHeaders.PRAGMA, "no-cache"); // response.setDateHeader(HttpHeaders.EXPIRES, 0); // response.setHeader(HttpHeaders.CONTENT_TYPE, contentType); // response.setStatus(status); // response.getWriter().write(body); // } // // /** // * Sends an error to the user with the given {@code status} and body. // */ // public static void sendError(HttpServletResponse response, String body, int status) // throws IOException { // Preconditions.checkArgument(status > 300); // response.setStatus(status); // response.setHeader(HttpHeaders.CONTENT_TYPE, "text/plain"); // response.getWriter().write(Escaper.escapeHtml(body)); // } // // /** // * Sends a response with the content type text/javascript. // */ // public static void sendJavaScript(HttpServletResponse response, String body) // throws IOException { // response.setHeader(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate"); // response.setHeader(HttpHeaders.PRAGMA, "no-cache"); // response.setDateHeader(HttpHeaders.EXPIRES, 0); // response.setHeader(HttpHeaders.CONTENT_TYPE, "text/javascript"); // response.setStatus(200); // response.getWriter().write(body); // } // // /** // * Sends a redirect to the user. // */ // public static void sendRedirect(HttpServletResponse response, String location) { // response.setStatus(302); // response.setHeader(HttpHeaders.LOCATION, location); // } // } // Path: src/tests/reverseclickjacking/UniversalReverseClickjackingJsonpEndpoint.java import com.google.common.base.Strings; import com.google.testing.security.firingrange.utils.Responses; import java.io.IOException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /* * Copyright 2014 Google Inc. All rights reserved. * * 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 com.google.testing.security.firingrange.tests.reverseclickjacking; /** * A sample JSONP endpoint and test case for URC, where the value of a parameter in the request is * used as a callback function. */ public class UniversalReverseClickjackingJsonpEndpoint extends HttpServlet { static final String CALLBACK_REGEX = "[a-zA-Z0-9][a-zA-Z0-9\\._]*"; static final String ECHOED_PARAM = "callback"; static final int MAX_CALLBACK_LENGTH = 100; @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { String echoedParam = Strings.nullToEmpty(request.getParameter(ECHOED_PARAM)); if (!echoedParam.matches(CALLBACK_REGEX) || echoedParam.length() > MAX_CALLBACK_LENGTH) {
Responses.sendError(response,
google/firing-range
src/tests/tags/TagServlet.java
// Path: src/utils/Responses.java // @Immutable // public final class Responses { // // private Responses() {} // // /** // * Sends a "normal" response, with all the standard headers. // */ // public static void sendNormalPage(HttpServletResponse response, String body) throws IOException { // response.setHeader(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate"); // response.setHeader(HttpHeaders.PRAGMA, "no-cache"); // response.setDateHeader(HttpHeaders.EXPIRES, 0); // response.setHeader(HttpHeaders.CONTENT_TYPE, "text/html; charset=utf-8"); // response.setStatus(200); // response.getWriter().write(body); // } // // /** // * Sends an XSS response. // */ // public static void sendXssed(HttpServletResponse response, String body) throws IOException { // sendXssed(response, body, "text/html; charset=utf-8"); // } // // /** // * Sends an HTML XSSed response with the given status. // */ // public static void sendXssed(HttpServletResponse response, String body, int status) // throws IOException { // sendXssed(response, body, "text/html; charset=utf-8", status); // } // // /** // * Sends an XSS response of a given type. // */ // public static void sendXssed(HttpServletResponse response, String body, String contentType) // throws IOException { // sendXssed(response, body, contentType, 200); // } // // /** // * Sends an XSS response of a given type. // */ // public static void sendXssed(HttpServletResponse response, String body, String contentType, // int status) throws IOException { // response.setHeader(HttpHeaders.X_XSS_PROTECTION, "0"); // response.setHeader(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate"); // response.setHeader(HttpHeaders.PRAGMA, "no-cache"); // response.setDateHeader(HttpHeaders.EXPIRES, 0); // response.setHeader(HttpHeaders.CONTENT_TYPE, contentType); // response.setStatus(status); // response.getWriter().write(body); // } // // /** // * Sends an error to the user with the given {@code status} and body. // */ // public static void sendError(HttpServletResponse response, String body, int status) // throws IOException { // Preconditions.checkArgument(status > 300); // response.setStatus(status); // response.setHeader(HttpHeaders.CONTENT_TYPE, "text/plain"); // response.getWriter().write(Escaper.escapeHtml(body)); // } // // /** // * Sends a response with the content type text/javascript. // */ // public static void sendJavaScript(HttpServletResponse response, String body) // throws IOException { // response.setHeader(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate"); // response.setHeader(HttpHeaders.PRAGMA, "no-cache"); // response.setDateHeader(HttpHeaders.EXPIRES, 0); // response.setHeader(HttpHeaders.CONTENT_TYPE, "text/javascript"); // response.setStatus(200); // response.getWriter().write(body); // } // // /** // * Sends a redirect to the user. // */ // public static void sendRedirect(HttpServletResponse response, String location) { // response.setStatus(302); // response.setHeader(HttpHeaders.LOCATION, location); // } // }
import com.google.testing.security.firingrange.utils.Responses; import org.jsoup.Jsoup; import org.jsoup.nodes.Attribute; import org.jsoup.nodes.Attributes; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.io.IOException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
/* *Copyright 2014 Google Inc. All rights reserved. * * 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 com.google.testing.security.firingrange.tests.tags; /** * A class only allowing a given set of tags and properties of those tags as its input payload. */ public class TagServlet extends HttpServlet { @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { if (request.getParameter("q") == null) {
// Path: src/utils/Responses.java // @Immutable // public final class Responses { // // private Responses() {} // // /** // * Sends a "normal" response, with all the standard headers. // */ // public static void sendNormalPage(HttpServletResponse response, String body) throws IOException { // response.setHeader(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate"); // response.setHeader(HttpHeaders.PRAGMA, "no-cache"); // response.setDateHeader(HttpHeaders.EXPIRES, 0); // response.setHeader(HttpHeaders.CONTENT_TYPE, "text/html; charset=utf-8"); // response.setStatus(200); // response.getWriter().write(body); // } // // /** // * Sends an XSS response. // */ // public static void sendXssed(HttpServletResponse response, String body) throws IOException { // sendXssed(response, body, "text/html; charset=utf-8"); // } // // /** // * Sends an HTML XSSed response with the given status. // */ // public static void sendXssed(HttpServletResponse response, String body, int status) // throws IOException { // sendXssed(response, body, "text/html; charset=utf-8", status); // } // // /** // * Sends an XSS response of a given type. // */ // public static void sendXssed(HttpServletResponse response, String body, String contentType) // throws IOException { // sendXssed(response, body, contentType, 200); // } // // /** // * Sends an XSS response of a given type. // */ // public static void sendXssed(HttpServletResponse response, String body, String contentType, // int status) throws IOException { // response.setHeader(HttpHeaders.X_XSS_PROTECTION, "0"); // response.setHeader(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate"); // response.setHeader(HttpHeaders.PRAGMA, "no-cache"); // response.setDateHeader(HttpHeaders.EXPIRES, 0); // response.setHeader(HttpHeaders.CONTENT_TYPE, contentType); // response.setStatus(status); // response.getWriter().write(body); // } // // /** // * Sends an error to the user with the given {@code status} and body. // */ // public static void sendError(HttpServletResponse response, String body, int status) // throws IOException { // Preconditions.checkArgument(status > 300); // response.setStatus(status); // response.setHeader(HttpHeaders.CONTENT_TYPE, "text/plain"); // response.getWriter().write(Escaper.escapeHtml(body)); // } // // /** // * Sends a response with the content type text/javascript. // */ // public static void sendJavaScript(HttpServletResponse response, String body) // throws IOException { // response.setHeader(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate"); // response.setHeader(HttpHeaders.PRAGMA, "no-cache"); // response.setDateHeader(HttpHeaders.EXPIRES, 0); // response.setHeader(HttpHeaders.CONTENT_TYPE, "text/javascript"); // response.setStatus(200); // response.getWriter().write(body); // } // // /** // * Sends a redirect to the user. // */ // public static void sendRedirect(HttpServletResponse response, String location) { // response.setStatus(302); // response.setHeader(HttpHeaders.LOCATION, location); // } // } // Path: src/tests/tags/TagServlet.java import com.google.testing.security.firingrange.utils.Responses; import org.jsoup.Jsoup; import org.jsoup.nodes.Attribute; import org.jsoup.nodes.Attributes; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.io.IOException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /* *Copyright 2014 Google Inc. All rights reserved. * * 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 com.google.testing.security.firingrange.tests.tags; /** * A class only allowing a given set of tags and properties of those tags as its input payload. */ public class TagServlet extends HttpServlet { @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { if (request.getParameter("q") == null) {
Responses.sendError(response, "Missing q parameter", 400);
google/firing-range
src/tests/reflected/JsonContentSniffingCallback.java
// Path: src/utils/Responses.java // @Immutable // public final class Responses { // // private Responses() {} // // /** // * Sends a "normal" response, with all the standard headers. // */ // public static void sendNormalPage(HttpServletResponse response, String body) throws IOException { // response.setHeader(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate"); // response.setHeader(HttpHeaders.PRAGMA, "no-cache"); // response.setDateHeader(HttpHeaders.EXPIRES, 0); // response.setHeader(HttpHeaders.CONTENT_TYPE, "text/html; charset=utf-8"); // response.setStatus(200); // response.getWriter().write(body); // } // // /** // * Sends an XSS response. // */ // public static void sendXssed(HttpServletResponse response, String body) throws IOException { // sendXssed(response, body, "text/html; charset=utf-8"); // } // // /** // * Sends an HTML XSSed response with the given status. // */ // public static void sendXssed(HttpServletResponse response, String body, int status) // throws IOException { // sendXssed(response, body, "text/html; charset=utf-8", status); // } // // /** // * Sends an XSS response of a given type. // */ // public static void sendXssed(HttpServletResponse response, String body, String contentType) // throws IOException { // sendXssed(response, body, contentType, 200); // } // // /** // * Sends an XSS response of a given type. // */ // public static void sendXssed(HttpServletResponse response, String body, String contentType, // int status) throws IOException { // response.setHeader(HttpHeaders.X_XSS_PROTECTION, "0"); // response.setHeader(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate"); // response.setHeader(HttpHeaders.PRAGMA, "no-cache"); // response.setDateHeader(HttpHeaders.EXPIRES, 0); // response.setHeader(HttpHeaders.CONTENT_TYPE, contentType); // response.setStatus(status); // response.getWriter().write(body); // } // // /** // * Sends an error to the user with the given {@code status} and body. // */ // public static void sendError(HttpServletResponse response, String body, int status) // throws IOException { // Preconditions.checkArgument(status > 300); // response.setStatus(status); // response.setHeader(HttpHeaders.CONTENT_TYPE, "text/plain"); // response.getWriter().write(Escaper.escapeHtml(body)); // } // // /** // * Sends a response with the content type text/javascript. // */ // public static void sendJavaScript(HttpServletResponse response, String body) // throws IOException { // response.setHeader(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate"); // response.setHeader(HttpHeaders.PRAGMA, "no-cache"); // response.setDateHeader(HttpHeaders.EXPIRES, 0); // response.setHeader(HttpHeaders.CONTENT_TYPE, "text/javascript"); // response.setStatus(200); // response.getWriter().write(body); // } // // /** // * Sends a redirect to the user. // */ // public static void sendRedirect(HttpServletResponse response, String location) { // response.setStatus(302); // response.setHeader(HttpHeaders.LOCATION, location); // } // }
import com.google.common.base.Strings; import com.google.testing.security.firingrange.utils.Responses; import java.io.IOException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
/* *Copyright 2014 Google Inc. All rights reserved. * * 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 com.google.testing.security.firingrange.tests.reflected; /** * Handles reflected XSS on JSON via content sniffing in a secret callback argument. */ public class JsonContentSniffingCallback extends HttpServlet { private static final String ECHOED_PARAM = "callback"; @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { String echoedParam = Strings.nullToEmpty(request.getParameter(ECHOED_PARAM)); String json; if (echoedParam.isEmpty()) { json = "{'foobar':'foo'}"; } else { json = echoedParam + "({'foobar':'foo'});"; }
// Path: src/utils/Responses.java // @Immutable // public final class Responses { // // private Responses() {} // // /** // * Sends a "normal" response, with all the standard headers. // */ // public static void sendNormalPage(HttpServletResponse response, String body) throws IOException { // response.setHeader(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate"); // response.setHeader(HttpHeaders.PRAGMA, "no-cache"); // response.setDateHeader(HttpHeaders.EXPIRES, 0); // response.setHeader(HttpHeaders.CONTENT_TYPE, "text/html; charset=utf-8"); // response.setStatus(200); // response.getWriter().write(body); // } // // /** // * Sends an XSS response. // */ // public static void sendXssed(HttpServletResponse response, String body) throws IOException { // sendXssed(response, body, "text/html; charset=utf-8"); // } // // /** // * Sends an HTML XSSed response with the given status. // */ // public static void sendXssed(HttpServletResponse response, String body, int status) // throws IOException { // sendXssed(response, body, "text/html; charset=utf-8", status); // } // // /** // * Sends an XSS response of a given type. // */ // public static void sendXssed(HttpServletResponse response, String body, String contentType) // throws IOException { // sendXssed(response, body, contentType, 200); // } // // /** // * Sends an XSS response of a given type. // */ // public static void sendXssed(HttpServletResponse response, String body, String contentType, // int status) throws IOException { // response.setHeader(HttpHeaders.X_XSS_PROTECTION, "0"); // response.setHeader(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate"); // response.setHeader(HttpHeaders.PRAGMA, "no-cache"); // response.setDateHeader(HttpHeaders.EXPIRES, 0); // response.setHeader(HttpHeaders.CONTENT_TYPE, contentType); // response.setStatus(status); // response.getWriter().write(body); // } // // /** // * Sends an error to the user with the given {@code status} and body. // */ // public static void sendError(HttpServletResponse response, String body, int status) // throws IOException { // Preconditions.checkArgument(status > 300); // response.setStatus(status); // response.setHeader(HttpHeaders.CONTENT_TYPE, "text/plain"); // response.getWriter().write(Escaper.escapeHtml(body)); // } // // /** // * Sends a response with the content type text/javascript. // */ // public static void sendJavaScript(HttpServletResponse response, String body) // throws IOException { // response.setHeader(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate"); // response.setHeader(HttpHeaders.PRAGMA, "no-cache"); // response.setDateHeader(HttpHeaders.EXPIRES, 0); // response.setHeader(HttpHeaders.CONTENT_TYPE, "text/javascript"); // response.setStatus(200); // response.getWriter().write(body); // } // // /** // * Sends a redirect to the user. // */ // public static void sendRedirect(HttpServletResponse response, String location) { // response.setStatus(302); // response.setHeader(HttpHeaders.LOCATION, location); // } // } // Path: src/tests/reflected/JsonContentSniffingCallback.java import com.google.common.base.Strings; import com.google.testing.security.firingrange.utils.Responses; import java.io.IOException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /* *Copyright 2014 Google Inc. All rights reserved. * * 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 com.google.testing.security.firingrange.tests.reflected; /** * Handles reflected XSS on JSON via content sniffing in a secret callback argument. */ public class JsonContentSniffingCallback extends HttpServlet { private static final String ECHOED_PARAM = "callback"; @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { String echoedParam = Strings.nullToEmpty(request.getParameter(ECHOED_PARAM)); String json; if (echoedParam.isEmpty()) { json = "{'foobar':'foo'}"; } else { json = echoedParam + "({'foobar':'foo'});"; }
Responses.sendXssed(response, json, "application/json");
google/firing-range
src/tests/urldom/JsonpEndpoint.java
// Path: src/utils/Responses.java // @Immutable // public final class Responses { // // private Responses() {} // // /** // * Sends a "normal" response, with all the standard headers. // */ // public static void sendNormalPage(HttpServletResponse response, String body) throws IOException { // response.setHeader(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate"); // response.setHeader(HttpHeaders.PRAGMA, "no-cache"); // response.setDateHeader(HttpHeaders.EXPIRES, 0); // response.setHeader(HttpHeaders.CONTENT_TYPE, "text/html; charset=utf-8"); // response.setStatus(200); // response.getWriter().write(body); // } // // /** // * Sends an XSS response. // */ // public static void sendXssed(HttpServletResponse response, String body) throws IOException { // sendXssed(response, body, "text/html; charset=utf-8"); // } // // /** // * Sends an HTML XSSed response with the given status. // */ // public static void sendXssed(HttpServletResponse response, String body, int status) // throws IOException { // sendXssed(response, body, "text/html; charset=utf-8", status); // } // // /** // * Sends an XSS response of a given type. // */ // public static void sendXssed(HttpServletResponse response, String body, String contentType) // throws IOException { // sendXssed(response, body, contentType, 200); // } // // /** // * Sends an XSS response of a given type. // */ // public static void sendXssed(HttpServletResponse response, String body, String contentType, // int status) throws IOException { // response.setHeader(HttpHeaders.X_XSS_PROTECTION, "0"); // response.setHeader(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate"); // response.setHeader(HttpHeaders.PRAGMA, "no-cache"); // response.setDateHeader(HttpHeaders.EXPIRES, 0); // response.setHeader(HttpHeaders.CONTENT_TYPE, contentType); // response.setStatus(status); // response.getWriter().write(body); // } // // /** // * Sends an error to the user with the given {@code status} and body. // */ // public static void sendError(HttpServletResponse response, String body, int status) // throws IOException { // Preconditions.checkArgument(status > 300); // response.setStatus(status); // response.setHeader(HttpHeaders.CONTENT_TYPE, "text/plain"); // response.getWriter().write(Escaper.escapeHtml(body)); // } // // /** // * Sends a response with the content type text/javascript. // */ // public static void sendJavaScript(HttpServletResponse response, String body) // throws IOException { // response.setHeader(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate"); // response.setHeader(HttpHeaders.PRAGMA, "no-cache"); // response.setDateHeader(HttpHeaders.EXPIRES, 0); // response.setHeader(HttpHeaders.CONTENT_TYPE, "text/javascript"); // response.setStatus(200); // response.getWriter().write(body); // } // // /** // * Sends a redirect to the user. // */ // public static void sendRedirect(HttpServletResponse response, String location) { // response.setStatus(302); // response.setHeader(HttpHeaders.LOCATION, location); // } // }
import com.google.common.base.Strings; import com.google.testing.security.firingrange.utils.Responses; import java.io.IOException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
/* * Copyright 2016 Google Inc. All rights reserved. * * 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 com.google.testing.security.firingrange.tests.urldom; /** * Provides JSONP Endpoint service. */ public class JsonpEndpoint extends HttpServlet { static final String CALLBACK_REGEX = "[a-zA-Z0-9][a-zA-Z0-9\\._]*"; static final String ECHOED_PARAM = "callback"; static final int MAX_CALLBACK_LENGTH = 100; @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { String echoedParam = Strings.nullToEmpty(request.getParameter(ECHOED_PARAM)); if (!echoedParam.matches(CALLBACK_REGEX) || echoedParam.length() > MAX_CALLBACK_LENGTH) {
// Path: src/utils/Responses.java // @Immutable // public final class Responses { // // private Responses() {} // // /** // * Sends a "normal" response, with all the standard headers. // */ // public static void sendNormalPage(HttpServletResponse response, String body) throws IOException { // response.setHeader(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate"); // response.setHeader(HttpHeaders.PRAGMA, "no-cache"); // response.setDateHeader(HttpHeaders.EXPIRES, 0); // response.setHeader(HttpHeaders.CONTENT_TYPE, "text/html; charset=utf-8"); // response.setStatus(200); // response.getWriter().write(body); // } // // /** // * Sends an XSS response. // */ // public static void sendXssed(HttpServletResponse response, String body) throws IOException { // sendXssed(response, body, "text/html; charset=utf-8"); // } // // /** // * Sends an HTML XSSed response with the given status. // */ // public static void sendXssed(HttpServletResponse response, String body, int status) // throws IOException { // sendXssed(response, body, "text/html; charset=utf-8", status); // } // // /** // * Sends an XSS response of a given type. // */ // public static void sendXssed(HttpServletResponse response, String body, String contentType) // throws IOException { // sendXssed(response, body, contentType, 200); // } // // /** // * Sends an XSS response of a given type. // */ // public static void sendXssed(HttpServletResponse response, String body, String contentType, // int status) throws IOException { // response.setHeader(HttpHeaders.X_XSS_PROTECTION, "0"); // response.setHeader(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate"); // response.setHeader(HttpHeaders.PRAGMA, "no-cache"); // response.setDateHeader(HttpHeaders.EXPIRES, 0); // response.setHeader(HttpHeaders.CONTENT_TYPE, contentType); // response.setStatus(status); // response.getWriter().write(body); // } // // /** // * Sends an error to the user with the given {@code status} and body. // */ // public static void sendError(HttpServletResponse response, String body, int status) // throws IOException { // Preconditions.checkArgument(status > 300); // response.setStatus(status); // response.setHeader(HttpHeaders.CONTENT_TYPE, "text/plain"); // response.getWriter().write(Escaper.escapeHtml(body)); // } // // /** // * Sends a response with the content type text/javascript. // */ // public static void sendJavaScript(HttpServletResponse response, String body) // throws IOException { // response.setHeader(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate"); // response.setHeader(HttpHeaders.PRAGMA, "no-cache"); // response.setDateHeader(HttpHeaders.EXPIRES, 0); // response.setHeader(HttpHeaders.CONTENT_TYPE, "text/javascript"); // response.setStatus(200); // response.getWriter().write(body); // } // // /** // * Sends a redirect to the user. // */ // public static void sendRedirect(HttpServletResponse response, String location) { // response.setStatus(302); // response.setHeader(HttpHeaders.LOCATION, location); // } // } // Path: src/tests/urldom/JsonpEndpoint.java import com.google.common.base.Strings; import com.google.testing.security.firingrange.utils.Responses; import java.io.IOException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /* * Copyright 2016 Google Inc. All rights reserved. * * 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 com.google.testing.security.firingrange.tests.urldom; /** * Provides JSONP Endpoint service. */ public class JsonpEndpoint extends HttpServlet { static final String CALLBACK_REGEX = "[a-zA-Z0-9][a-zA-Z0-9\\._]*"; static final String ECHOED_PARAM = "callback"; static final int MAX_CALLBACK_LENGTH = 100; @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { String echoedParam = Strings.nullToEmpty(request.getParameter(ECHOED_PARAM)); if (!echoedParam.matches(CALLBACK_REGEX) || echoedParam.length() > MAX_CALLBACK_LENGTH) {
Responses.sendError(response,
Elvynia/formation-exercices
src/fr/formation/exo2/objets/Representant.java
// Path: src/fr/formation/exo2/Constants.java // public class Constants { // // /** // * Préfixe du libellé des factures de frais de déplacement pour les indépendants. // */ // public static final String TRAVEL_FEES = "Frais de déplacement"; // // /** // * Salaire par unité pour un employé dans la production. // */ // public static final int EMPLOYE_PRODUCER_UNITCOST = 5; // // /** // * Prime mensuelle pour un représentant. // */ // public static final int EMPLOYE_REPRESENTANT_PRIME = 800; // // /** // * Prime bonus pour les employés manipulant des produits à risque. // */ // public static final int EMPLOYE_RISK_PRIME = 200; // // /** // * Prime mensuelle pour un vendeur. // */ // public static final int EMPLOYE_SALES_PRIME = 400; // // /** // * Pourcentage du chiffre d'affaire permettant de calculer le salaire d'un // * vendeur. // */ // public static final int EMPLOYE_SALES_TURNOVER_PART = 20; // // /** // * Salaire horaire pour les employés de la manutention. // */ // public static final int EMPLOYE_WAREHOUSE_HOURCOST = 65; // }
import java.util.Date; import fr.formation.exo2.Constants;
package fr.formation.exo2.objets; /** * Employé à la fois vendeur et représentant de la société. * * @author hb-asus * */ public class Representant extends Salesman { /** * Constructeur. * * @param name * le nom de l'employé. * @param firstName * le prénom de l'employé. * @param age * l'age de l'employé. * @param hireDate * la date à laquelle l'employé a été embauché. * @param turnover * le chiffre d'affaires permettant de calculer le salaire. */ public Representant(String name, String firstName, int age, Date hireDate, int turnover) { // Appel au constructeur de la classe parent Salesman. super(name, firstName, age, hireDate, turnover); } /** * {@inheritDoc} Calcul à partir du chiffre d'affaires et ajout d'une prime * mensuelle fixe. */ @Override public int calculateSalary() {
// Path: src/fr/formation/exo2/Constants.java // public class Constants { // // /** // * Préfixe du libellé des factures de frais de déplacement pour les indépendants. // */ // public static final String TRAVEL_FEES = "Frais de déplacement"; // // /** // * Salaire par unité pour un employé dans la production. // */ // public static final int EMPLOYE_PRODUCER_UNITCOST = 5; // // /** // * Prime mensuelle pour un représentant. // */ // public static final int EMPLOYE_REPRESENTANT_PRIME = 800; // // /** // * Prime bonus pour les employés manipulant des produits à risque. // */ // public static final int EMPLOYE_RISK_PRIME = 200; // // /** // * Prime mensuelle pour un vendeur. // */ // public static final int EMPLOYE_SALES_PRIME = 400; // // /** // * Pourcentage du chiffre d'affaire permettant de calculer le salaire d'un // * vendeur. // */ // public static final int EMPLOYE_SALES_TURNOVER_PART = 20; // // /** // * Salaire horaire pour les employés de la manutention. // */ // public static final int EMPLOYE_WAREHOUSE_HOURCOST = 65; // } // Path: src/fr/formation/exo2/objets/Representant.java import java.util.Date; import fr.formation.exo2.Constants; package fr.formation.exo2.objets; /** * Employé à la fois vendeur et représentant de la société. * * @author hb-asus * */ public class Representant extends Salesman { /** * Constructeur. * * @param name * le nom de l'employé. * @param firstName * le prénom de l'employé. * @param age * l'age de l'employé. * @param hireDate * la date à laquelle l'employé a été embauché. * @param turnover * le chiffre d'affaires permettant de calculer le salaire. */ public Representant(String name, String firstName, int age, Date hireDate, int turnover) { // Appel au constructeur de la classe parent Salesman. super(name, firstName, age, hireDate, turnover); } /** * {@inheritDoc} Calcul à partir du chiffre d'affaires et ajout d'une prime * mensuelle fixe. */ @Override public int calculateSalary() {
return this.calculateTurnoverPart() + Constants.EMPLOYE_REPRESENTANT_PRIME;
Elvynia/formation-exercices
src/fr/formation/exo2/objets/Salesman.java
// Path: src/fr/formation/exo2/Constants.java // public class Constants { // // /** // * Préfixe du libellé des factures de frais de déplacement pour les indépendants. // */ // public static final String TRAVEL_FEES = "Frais de déplacement"; // // /** // * Salaire par unité pour un employé dans la production. // */ // public static final int EMPLOYE_PRODUCER_UNITCOST = 5; // // /** // * Prime mensuelle pour un représentant. // */ // public static final int EMPLOYE_REPRESENTANT_PRIME = 800; // // /** // * Prime bonus pour les employés manipulant des produits à risque. // */ // public static final int EMPLOYE_RISK_PRIME = 200; // // /** // * Prime mensuelle pour un vendeur. // */ // public static final int EMPLOYE_SALES_PRIME = 400; // // /** // * Pourcentage du chiffre d'affaire permettant de calculer le salaire d'un // * vendeur. // */ // public static final int EMPLOYE_SALES_TURNOVER_PART = 20; // // /** // * Salaire horaire pour les employés de la manutention. // */ // public static final int EMPLOYE_WAREHOUSE_HOURCOST = 65; // }
import java.util.Date; import fr.formation.exo2.Constants;
package fr.formation.exo2.objets; /** * Employé vendeur. * * @author hb-asus * */ public class Salesman extends Employee { // Propriété spécifique au vendeur. int turnover; /** * Constructeur. * * @param name * le nom de l'employé. * @param firstName * le prénom de l'employé. * @param age * l'age de l'employé. * @param hireDate * la date à laquelle l'employé a été embauché. * @param turnover * le chiffre d'affaires permettant de calculer le salaire. */ public Salesman(String name, String firstName, int age, Date hireDate, int turnover) { // Appel au constructeur de la classe parent Employee. super(name, firstName, age, hireDate); this.turnover = turnover; } /** * {@inheritDoc} Calcul à partir du chiffre d'affaires et ajout d'une prime * mensuelle fixe. */ @Override public int calculateSalary() {
// Path: src/fr/formation/exo2/Constants.java // public class Constants { // // /** // * Préfixe du libellé des factures de frais de déplacement pour les indépendants. // */ // public static final String TRAVEL_FEES = "Frais de déplacement"; // // /** // * Salaire par unité pour un employé dans la production. // */ // public static final int EMPLOYE_PRODUCER_UNITCOST = 5; // // /** // * Prime mensuelle pour un représentant. // */ // public static final int EMPLOYE_REPRESENTANT_PRIME = 800; // // /** // * Prime bonus pour les employés manipulant des produits à risque. // */ // public static final int EMPLOYE_RISK_PRIME = 200; // // /** // * Prime mensuelle pour un vendeur. // */ // public static final int EMPLOYE_SALES_PRIME = 400; // // /** // * Pourcentage du chiffre d'affaire permettant de calculer le salaire d'un // * vendeur. // */ // public static final int EMPLOYE_SALES_TURNOVER_PART = 20; // // /** // * Salaire horaire pour les employés de la manutention. // */ // public static final int EMPLOYE_WAREHOUSE_HOURCOST = 65; // } // Path: src/fr/formation/exo2/objets/Salesman.java import java.util.Date; import fr.formation.exo2.Constants; package fr.formation.exo2.objets; /** * Employé vendeur. * * @author hb-asus * */ public class Salesman extends Employee { // Propriété spécifique au vendeur. int turnover; /** * Constructeur. * * @param name * le nom de l'employé. * @param firstName * le prénom de l'employé. * @param age * l'age de l'employé. * @param hireDate * la date à laquelle l'employé a été embauché. * @param turnover * le chiffre d'affaires permettant de calculer le salaire. */ public Salesman(String name, String firstName, int age, Date hireDate, int turnover) { // Appel au constructeur de la classe parent Employee. super(name, firstName, age, hireDate); this.turnover = turnover; } /** * {@inheritDoc} Calcul à partir du chiffre d'affaires et ajout d'une prime * mensuelle fixe. */ @Override public int calculateSalary() {
return this.calculateTurnoverPart() + Constants.EMPLOYE_SALES_PRIME;
Elvynia/formation-exercices
src/fr/formation/exo2/objets/Producer.java
// Path: src/fr/formation/exo2/Constants.java // public class Constants { // // /** // * Préfixe du libellé des factures de frais de déplacement pour les indépendants. // */ // public static final String TRAVEL_FEES = "Frais de déplacement"; // // /** // * Salaire par unité pour un employé dans la production. // */ // public static final int EMPLOYE_PRODUCER_UNITCOST = 5; // // /** // * Prime mensuelle pour un représentant. // */ // public static final int EMPLOYE_REPRESENTANT_PRIME = 800; // // /** // * Prime bonus pour les employés manipulant des produits à risque. // */ // public static final int EMPLOYE_RISK_PRIME = 200; // // /** // * Prime mensuelle pour un vendeur. // */ // public static final int EMPLOYE_SALES_PRIME = 400; // // /** // * Pourcentage du chiffre d'affaire permettant de calculer le salaire d'un // * vendeur. // */ // public static final int EMPLOYE_SALES_TURNOVER_PART = 20; // // /** // * Salaire horaire pour les employés de la manutention. // */ // public static final int EMPLOYE_WAREHOUSE_HOURCOST = 65; // }
import java.util.Date; import fr.formation.exo2.Constants;
package fr.formation.exo2.objets; /** * Employé dans le domaine de la production. * * @author hb-asus * */ public class Producer extends Employee { // Propriété spécifique à un employé dans la production. int unitProduced; /** * Constructeur. * * @param name * le nom de l'employé. * @param firstName * le prénom de l'employé. * @param age * l'age de l'employé. * @param hireDate * la date à laquelle l'employé a été embauché. * @param unitProduced * le nombre d'unités produites par l'employé pour le mois * courant. */ public Producer(String name, String firstName, int age, Date hireDate, int unitProduced) { // Appel au constructeur de la classe parent Employee. super(name, firstName, age, hireDate); this.unitProduced = unitProduced; } /** * {@inheritDoc} Calcul du salaire à partir du nombre d'unités produites et * du coup d'une unité. */ @Override public int calculateSalary() {
// Path: src/fr/formation/exo2/Constants.java // public class Constants { // // /** // * Préfixe du libellé des factures de frais de déplacement pour les indépendants. // */ // public static final String TRAVEL_FEES = "Frais de déplacement"; // // /** // * Salaire par unité pour un employé dans la production. // */ // public static final int EMPLOYE_PRODUCER_UNITCOST = 5; // // /** // * Prime mensuelle pour un représentant. // */ // public static final int EMPLOYE_REPRESENTANT_PRIME = 800; // // /** // * Prime bonus pour les employés manipulant des produits à risque. // */ // public static final int EMPLOYE_RISK_PRIME = 200; // // /** // * Prime mensuelle pour un vendeur. // */ // public static final int EMPLOYE_SALES_PRIME = 400; // // /** // * Pourcentage du chiffre d'affaire permettant de calculer le salaire d'un // * vendeur. // */ // public static final int EMPLOYE_SALES_TURNOVER_PART = 20; // // /** // * Salaire horaire pour les employés de la manutention. // */ // public static final int EMPLOYE_WAREHOUSE_HOURCOST = 65; // } // Path: src/fr/formation/exo2/objets/Producer.java import java.util.Date; import fr.formation.exo2.Constants; package fr.formation.exo2.objets; /** * Employé dans le domaine de la production. * * @author hb-asus * */ public class Producer extends Employee { // Propriété spécifique à un employé dans la production. int unitProduced; /** * Constructeur. * * @param name * le nom de l'employé. * @param firstName * le prénom de l'employé. * @param age * l'age de l'employé. * @param hireDate * la date à laquelle l'employé a été embauché. * @param unitProduced * le nombre d'unités produites par l'employé pour le mois * courant. */ public Producer(String name, String firstName, int age, Date hireDate, int unitProduced) { // Appel au constructeur de la classe parent Employee. super(name, firstName, age, hireDate); this.unitProduced = unitProduced; } /** * {@inheritDoc} Calcul du salaire à partir du nombre d'unités produites et * du coup d'une unité. */ @Override public int calculateSalary() {
return this.unitProduced * Constants.EMPLOYE_PRODUCER_UNITCOST;
Elvynia/formation-exercices
src/fr/formation/exo11/parser/CsvParser.java
// Path: src/fr/formation/exo11/HEADER.java // public enum HEADER { // TYPE("Type"), YEAR("Année"), SCORE("Cote"); // // public final String column; // // private HEADER(String column) { // this.column = column; // } // } // // Path: src/fr/formation/exo11/domain/RoundPlate.java // public class RoundPlate extends Utensil implements Plate { // // private float radius; // // @Override // public float calcArea() { // return (float) (Math.pow(this.radius, 2) * Math.PI); // } // // @Override // public void setScore(Object obj) { // this.setRadius(Float.parseFloat(obj.toString())); // } // // public float getRadius() { // return radius; // } // // public void setRadius(float radius) { // this.radius = radius; // } // // @Override // public String toString() { // return super.toString().replace("Ustensile", "Assiette ronde"); // } // // } // // Path: src/fr/formation/exo11/domain/Spoon.java // public class Spoon extends Utensil { // // private float length; // // public float getLength() { // return length; // } // // public void setLength(float length) { // this.length = length; // } // // @Override // public void setScore(Object obj) { // this.setLength(Float.parseFloat(obj.toString())); // } // // @Override // public String toString() { // return super.toString().replace("Ustensile", "Cuillère"); // } // // } // // Path: src/fr/formation/exo11/domain/SquarePlate.java // public class SquarePlate extends Utensil implements Plate { // // private float score; // // @Override // public float calcArea() { // return (float) Math.pow(score, 2); // } // // public float getScore() { // return score; // } // // @Override // public void setScore(Object score) { // this.score = Float.parseFloat(score.toString()); // } // // @Override // public String toString() { // return super.toString().replace("Ustensile", "Assiette carré"); // } // // } // // Path: src/fr/formation/exo11/domain/Utensil.java // public abstract class Utensil { // private LocalDate creation; // // public abstract void setScore(Object obj); // // /** // * Calcul générique de la valeur d'un ustensile si il a plus de 50 ans // * (sinon sa valeur est 0). // * // * @param current la date à partir de laquelle calculer l'année en cours. // * @return int la valeur calculée. // */ // public int calcValue(LocalDate current) { // final int age = current.getYear() - this.creation.getYear(); // return age > 50 ? age - 50 : 0; // } // // public LocalDate getCreation() { // return creation; // } // // public void setCreation(LocalDate creation) { // this.creation = creation; // } // // @Override // public String toString() { // final StringBuilder sb = new StringBuilder("Ustensile["); // sb.append("Fabrication->"); // sb.append(this.creation); // return sb.toString(); // } // // }
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.time.LocalDate; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import fr.formation.exo11.HEADER; import fr.formation.exo11.domain.RoundPlate; import fr.formation.exo11.domain.Spoon; import fr.formation.exo11.domain.SquarePlate; import fr.formation.exo11.domain.Utensil;
package fr.formation.exo11.parser; public class CsvParser implements Parser { private static final String CSV_SEPARATOR = ","; private static final Logger LOGGER = LoggerFactory .getLogger(CsvParser.class); private InputStream inputData;
// Path: src/fr/formation/exo11/HEADER.java // public enum HEADER { // TYPE("Type"), YEAR("Année"), SCORE("Cote"); // // public final String column; // // private HEADER(String column) { // this.column = column; // } // } // // Path: src/fr/formation/exo11/domain/RoundPlate.java // public class RoundPlate extends Utensil implements Plate { // // private float radius; // // @Override // public float calcArea() { // return (float) (Math.pow(this.radius, 2) * Math.PI); // } // // @Override // public void setScore(Object obj) { // this.setRadius(Float.parseFloat(obj.toString())); // } // // public float getRadius() { // return radius; // } // // public void setRadius(float radius) { // this.radius = radius; // } // // @Override // public String toString() { // return super.toString().replace("Ustensile", "Assiette ronde"); // } // // } // // Path: src/fr/formation/exo11/domain/Spoon.java // public class Spoon extends Utensil { // // private float length; // // public float getLength() { // return length; // } // // public void setLength(float length) { // this.length = length; // } // // @Override // public void setScore(Object obj) { // this.setLength(Float.parseFloat(obj.toString())); // } // // @Override // public String toString() { // return super.toString().replace("Ustensile", "Cuillère"); // } // // } // // Path: src/fr/formation/exo11/domain/SquarePlate.java // public class SquarePlate extends Utensil implements Plate { // // private float score; // // @Override // public float calcArea() { // return (float) Math.pow(score, 2); // } // // public float getScore() { // return score; // } // // @Override // public void setScore(Object score) { // this.score = Float.parseFloat(score.toString()); // } // // @Override // public String toString() { // return super.toString().replace("Ustensile", "Assiette carré"); // } // // } // // Path: src/fr/formation/exo11/domain/Utensil.java // public abstract class Utensil { // private LocalDate creation; // // public abstract void setScore(Object obj); // // /** // * Calcul générique de la valeur d'un ustensile si il a plus de 50 ans // * (sinon sa valeur est 0). // * // * @param current la date à partir de laquelle calculer l'année en cours. // * @return int la valeur calculée. // */ // public int calcValue(LocalDate current) { // final int age = current.getYear() - this.creation.getYear(); // return age > 50 ? age - 50 : 0; // } // // public LocalDate getCreation() { // return creation; // } // // public void setCreation(LocalDate creation) { // this.creation = creation; // } // // @Override // public String toString() { // final StringBuilder sb = new StringBuilder("Ustensile["); // sb.append("Fabrication->"); // sb.append(this.creation); // return sb.toString(); // } // // } // Path: src/fr/formation/exo11/parser/CsvParser.java import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.time.LocalDate; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import fr.formation.exo11.HEADER; import fr.formation.exo11.domain.RoundPlate; import fr.formation.exo11.domain.Spoon; import fr.formation.exo11.domain.SquarePlate; import fr.formation.exo11.domain.Utensil; package fr.formation.exo11.parser; public class CsvParser implements Parser { private static final String CSV_SEPARATOR = ","; private static final Logger LOGGER = LoggerFactory .getLogger(CsvParser.class); private InputStream inputData;
private Map<HEADER, Integer> headerMap;
Elvynia/formation-exercices
src/fr/formation/exo11/parser/CsvParser.java
// Path: src/fr/formation/exo11/HEADER.java // public enum HEADER { // TYPE("Type"), YEAR("Année"), SCORE("Cote"); // // public final String column; // // private HEADER(String column) { // this.column = column; // } // } // // Path: src/fr/formation/exo11/domain/RoundPlate.java // public class RoundPlate extends Utensil implements Plate { // // private float radius; // // @Override // public float calcArea() { // return (float) (Math.pow(this.radius, 2) * Math.PI); // } // // @Override // public void setScore(Object obj) { // this.setRadius(Float.parseFloat(obj.toString())); // } // // public float getRadius() { // return radius; // } // // public void setRadius(float radius) { // this.radius = radius; // } // // @Override // public String toString() { // return super.toString().replace("Ustensile", "Assiette ronde"); // } // // } // // Path: src/fr/formation/exo11/domain/Spoon.java // public class Spoon extends Utensil { // // private float length; // // public float getLength() { // return length; // } // // public void setLength(float length) { // this.length = length; // } // // @Override // public void setScore(Object obj) { // this.setLength(Float.parseFloat(obj.toString())); // } // // @Override // public String toString() { // return super.toString().replace("Ustensile", "Cuillère"); // } // // } // // Path: src/fr/formation/exo11/domain/SquarePlate.java // public class SquarePlate extends Utensil implements Plate { // // private float score; // // @Override // public float calcArea() { // return (float) Math.pow(score, 2); // } // // public float getScore() { // return score; // } // // @Override // public void setScore(Object score) { // this.score = Float.parseFloat(score.toString()); // } // // @Override // public String toString() { // return super.toString().replace("Ustensile", "Assiette carré"); // } // // } // // Path: src/fr/formation/exo11/domain/Utensil.java // public abstract class Utensil { // private LocalDate creation; // // public abstract void setScore(Object obj); // // /** // * Calcul générique de la valeur d'un ustensile si il a plus de 50 ans // * (sinon sa valeur est 0). // * // * @param current la date à partir de laquelle calculer l'année en cours. // * @return int la valeur calculée. // */ // public int calcValue(LocalDate current) { // final int age = current.getYear() - this.creation.getYear(); // return age > 50 ? age - 50 : 0; // } // // public LocalDate getCreation() { // return creation; // } // // public void setCreation(LocalDate creation) { // this.creation = creation; // } // // @Override // public String toString() { // final StringBuilder sb = new StringBuilder("Ustensile["); // sb.append("Fabrication->"); // sb.append(this.creation); // return sb.toString(); // } // // }
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.time.LocalDate; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import fr.formation.exo11.HEADER; import fr.formation.exo11.domain.RoundPlate; import fr.formation.exo11.domain.Spoon; import fr.formation.exo11.domain.SquarePlate; import fr.formation.exo11.domain.Utensil;
package fr.formation.exo11.parser; public class CsvParser implements Parser { private static final String CSV_SEPARATOR = ","; private static final Logger LOGGER = LoggerFactory .getLogger(CsvParser.class); private InputStream inputData; private Map<HEADER, Integer> headerMap; @Override
// Path: src/fr/formation/exo11/HEADER.java // public enum HEADER { // TYPE("Type"), YEAR("Année"), SCORE("Cote"); // // public final String column; // // private HEADER(String column) { // this.column = column; // } // } // // Path: src/fr/formation/exo11/domain/RoundPlate.java // public class RoundPlate extends Utensil implements Plate { // // private float radius; // // @Override // public float calcArea() { // return (float) (Math.pow(this.radius, 2) * Math.PI); // } // // @Override // public void setScore(Object obj) { // this.setRadius(Float.parseFloat(obj.toString())); // } // // public float getRadius() { // return radius; // } // // public void setRadius(float radius) { // this.radius = radius; // } // // @Override // public String toString() { // return super.toString().replace("Ustensile", "Assiette ronde"); // } // // } // // Path: src/fr/formation/exo11/domain/Spoon.java // public class Spoon extends Utensil { // // private float length; // // public float getLength() { // return length; // } // // public void setLength(float length) { // this.length = length; // } // // @Override // public void setScore(Object obj) { // this.setLength(Float.parseFloat(obj.toString())); // } // // @Override // public String toString() { // return super.toString().replace("Ustensile", "Cuillère"); // } // // } // // Path: src/fr/formation/exo11/domain/SquarePlate.java // public class SquarePlate extends Utensil implements Plate { // // private float score; // // @Override // public float calcArea() { // return (float) Math.pow(score, 2); // } // // public float getScore() { // return score; // } // // @Override // public void setScore(Object score) { // this.score = Float.parseFloat(score.toString()); // } // // @Override // public String toString() { // return super.toString().replace("Ustensile", "Assiette carré"); // } // // } // // Path: src/fr/formation/exo11/domain/Utensil.java // public abstract class Utensil { // private LocalDate creation; // // public abstract void setScore(Object obj); // // /** // * Calcul générique de la valeur d'un ustensile si il a plus de 50 ans // * (sinon sa valeur est 0). // * // * @param current la date à partir de laquelle calculer l'année en cours. // * @return int la valeur calculée. // */ // public int calcValue(LocalDate current) { // final int age = current.getYear() - this.creation.getYear(); // return age > 50 ? age - 50 : 0; // } // // public LocalDate getCreation() { // return creation; // } // // public void setCreation(LocalDate creation) { // this.creation = creation; // } // // @Override // public String toString() { // final StringBuilder sb = new StringBuilder("Ustensile["); // sb.append("Fabrication->"); // sb.append(this.creation); // return sb.toString(); // } // // } // Path: src/fr/formation/exo11/parser/CsvParser.java import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.time.LocalDate; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import fr.formation.exo11.HEADER; import fr.formation.exo11.domain.RoundPlate; import fr.formation.exo11.domain.Spoon; import fr.formation.exo11.domain.SquarePlate; import fr.formation.exo11.domain.Utensil; package fr.formation.exo11.parser; public class CsvParser implements Parser { private static final String CSV_SEPARATOR = ","; private static final Logger LOGGER = LoggerFactory .getLogger(CsvParser.class); private InputStream inputData; private Map<HEADER, Integer> headerMap; @Override
public List<Utensil> parse() {
Elvynia/formation-exercices
src/fr/formation/exo11/parser/CsvParser.java
// Path: src/fr/formation/exo11/HEADER.java // public enum HEADER { // TYPE("Type"), YEAR("Année"), SCORE("Cote"); // // public final String column; // // private HEADER(String column) { // this.column = column; // } // } // // Path: src/fr/formation/exo11/domain/RoundPlate.java // public class RoundPlate extends Utensil implements Plate { // // private float radius; // // @Override // public float calcArea() { // return (float) (Math.pow(this.radius, 2) * Math.PI); // } // // @Override // public void setScore(Object obj) { // this.setRadius(Float.parseFloat(obj.toString())); // } // // public float getRadius() { // return radius; // } // // public void setRadius(float radius) { // this.radius = radius; // } // // @Override // public String toString() { // return super.toString().replace("Ustensile", "Assiette ronde"); // } // // } // // Path: src/fr/formation/exo11/domain/Spoon.java // public class Spoon extends Utensil { // // private float length; // // public float getLength() { // return length; // } // // public void setLength(float length) { // this.length = length; // } // // @Override // public void setScore(Object obj) { // this.setLength(Float.parseFloat(obj.toString())); // } // // @Override // public String toString() { // return super.toString().replace("Ustensile", "Cuillère"); // } // // } // // Path: src/fr/formation/exo11/domain/SquarePlate.java // public class SquarePlate extends Utensil implements Plate { // // private float score; // // @Override // public float calcArea() { // return (float) Math.pow(score, 2); // } // // public float getScore() { // return score; // } // // @Override // public void setScore(Object score) { // this.score = Float.parseFloat(score.toString()); // } // // @Override // public String toString() { // return super.toString().replace("Ustensile", "Assiette carré"); // } // // } // // Path: src/fr/formation/exo11/domain/Utensil.java // public abstract class Utensil { // private LocalDate creation; // // public abstract void setScore(Object obj); // // /** // * Calcul générique de la valeur d'un ustensile si il a plus de 50 ans // * (sinon sa valeur est 0). // * // * @param current la date à partir de laquelle calculer l'année en cours. // * @return int la valeur calculée. // */ // public int calcValue(LocalDate current) { // final int age = current.getYear() - this.creation.getYear(); // return age > 50 ? age - 50 : 0; // } // // public LocalDate getCreation() { // return creation; // } // // public void setCreation(LocalDate creation) { // this.creation = creation; // } // // @Override // public String toString() { // final StringBuilder sb = new StringBuilder("Ustensile["); // sb.append("Fabrication->"); // sb.append(this.creation); // return sb.toString(); // } // // }
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.time.LocalDate; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import fr.formation.exo11.HEADER; import fr.formation.exo11.domain.RoundPlate; import fr.formation.exo11.domain.Spoon; import fr.formation.exo11.domain.SquarePlate; import fr.formation.exo11.domain.Utensil;
public List<Utensil> parse() { List<Utensil> result = new ArrayList<>(); try (BufferedReader reader = new BufferedReader( new InputStreamReader(this.inputData))) { String line; LOGGER.debug("Début lecture du flux :"); boolean firstLine = true; while ((line = reader.readLine()) != null) { if (firstLine) { this.buildHeaders(line); firstLine = false; } else { result.add(this.buildUtensil(line)); } LOGGER.debug(line); } } catch (IOException e) { LOGGER.error("Erreur pendant la lecture du fichier :", e); System.exit(-1); } return result; } private Utensil buildUtensil(String line) { Utensil utensil = null; final String[] data = line.split(CSV_SEPARATOR); // Construire l'instance avec la colonne Type. final String type = data[this.headerMap.get(HEADER.TYPE)]; switch (type) { case "Assiette ronde":
// Path: src/fr/formation/exo11/HEADER.java // public enum HEADER { // TYPE("Type"), YEAR("Année"), SCORE("Cote"); // // public final String column; // // private HEADER(String column) { // this.column = column; // } // } // // Path: src/fr/formation/exo11/domain/RoundPlate.java // public class RoundPlate extends Utensil implements Plate { // // private float radius; // // @Override // public float calcArea() { // return (float) (Math.pow(this.radius, 2) * Math.PI); // } // // @Override // public void setScore(Object obj) { // this.setRadius(Float.parseFloat(obj.toString())); // } // // public float getRadius() { // return radius; // } // // public void setRadius(float radius) { // this.radius = radius; // } // // @Override // public String toString() { // return super.toString().replace("Ustensile", "Assiette ronde"); // } // // } // // Path: src/fr/formation/exo11/domain/Spoon.java // public class Spoon extends Utensil { // // private float length; // // public float getLength() { // return length; // } // // public void setLength(float length) { // this.length = length; // } // // @Override // public void setScore(Object obj) { // this.setLength(Float.parseFloat(obj.toString())); // } // // @Override // public String toString() { // return super.toString().replace("Ustensile", "Cuillère"); // } // // } // // Path: src/fr/formation/exo11/domain/SquarePlate.java // public class SquarePlate extends Utensil implements Plate { // // private float score; // // @Override // public float calcArea() { // return (float) Math.pow(score, 2); // } // // public float getScore() { // return score; // } // // @Override // public void setScore(Object score) { // this.score = Float.parseFloat(score.toString()); // } // // @Override // public String toString() { // return super.toString().replace("Ustensile", "Assiette carré"); // } // // } // // Path: src/fr/formation/exo11/domain/Utensil.java // public abstract class Utensil { // private LocalDate creation; // // public abstract void setScore(Object obj); // // /** // * Calcul générique de la valeur d'un ustensile si il a plus de 50 ans // * (sinon sa valeur est 0). // * // * @param current la date à partir de laquelle calculer l'année en cours. // * @return int la valeur calculée. // */ // public int calcValue(LocalDate current) { // final int age = current.getYear() - this.creation.getYear(); // return age > 50 ? age - 50 : 0; // } // // public LocalDate getCreation() { // return creation; // } // // public void setCreation(LocalDate creation) { // this.creation = creation; // } // // @Override // public String toString() { // final StringBuilder sb = new StringBuilder("Ustensile["); // sb.append("Fabrication->"); // sb.append(this.creation); // return sb.toString(); // } // // } // Path: src/fr/formation/exo11/parser/CsvParser.java import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.time.LocalDate; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import fr.formation.exo11.HEADER; import fr.formation.exo11.domain.RoundPlate; import fr.formation.exo11.domain.Spoon; import fr.formation.exo11.domain.SquarePlate; import fr.formation.exo11.domain.Utensil; public List<Utensil> parse() { List<Utensil> result = new ArrayList<>(); try (BufferedReader reader = new BufferedReader( new InputStreamReader(this.inputData))) { String line; LOGGER.debug("Début lecture du flux :"); boolean firstLine = true; while ((line = reader.readLine()) != null) { if (firstLine) { this.buildHeaders(line); firstLine = false; } else { result.add(this.buildUtensil(line)); } LOGGER.debug(line); } } catch (IOException e) { LOGGER.error("Erreur pendant la lecture du fichier :", e); System.exit(-1); } return result; } private Utensil buildUtensil(String line) { Utensil utensil = null; final String[] data = line.split(CSV_SEPARATOR); // Construire l'instance avec la colonne Type. final String type = data[this.headerMap.get(HEADER.TYPE)]; switch (type) { case "Assiette ronde":
utensil = new RoundPlate();
Elvynia/formation-exercices
src/fr/formation/exo11/parser/CsvParser.java
// Path: src/fr/formation/exo11/HEADER.java // public enum HEADER { // TYPE("Type"), YEAR("Année"), SCORE("Cote"); // // public final String column; // // private HEADER(String column) { // this.column = column; // } // } // // Path: src/fr/formation/exo11/domain/RoundPlate.java // public class RoundPlate extends Utensil implements Plate { // // private float radius; // // @Override // public float calcArea() { // return (float) (Math.pow(this.radius, 2) * Math.PI); // } // // @Override // public void setScore(Object obj) { // this.setRadius(Float.parseFloat(obj.toString())); // } // // public float getRadius() { // return radius; // } // // public void setRadius(float radius) { // this.radius = radius; // } // // @Override // public String toString() { // return super.toString().replace("Ustensile", "Assiette ronde"); // } // // } // // Path: src/fr/formation/exo11/domain/Spoon.java // public class Spoon extends Utensil { // // private float length; // // public float getLength() { // return length; // } // // public void setLength(float length) { // this.length = length; // } // // @Override // public void setScore(Object obj) { // this.setLength(Float.parseFloat(obj.toString())); // } // // @Override // public String toString() { // return super.toString().replace("Ustensile", "Cuillère"); // } // // } // // Path: src/fr/formation/exo11/domain/SquarePlate.java // public class SquarePlate extends Utensil implements Plate { // // private float score; // // @Override // public float calcArea() { // return (float) Math.pow(score, 2); // } // // public float getScore() { // return score; // } // // @Override // public void setScore(Object score) { // this.score = Float.parseFloat(score.toString()); // } // // @Override // public String toString() { // return super.toString().replace("Ustensile", "Assiette carré"); // } // // } // // Path: src/fr/formation/exo11/domain/Utensil.java // public abstract class Utensil { // private LocalDate creation; // // public abstract void setScore(Object obj); // // /** // * Calcul générique de la valeur d'un ustensile si il a plus de 50 ans // * (sinon sa valeur est 0). // * // * @param current la date à partir de laquelle calculer l'année en cours. // * @return int la valeur calculée. // */ // public int calcValue(LocalDate current) { // final int age = current.getYear() - this.creation.getYear(); // return age > 50 ? age - 50 : 0; // } // // public LocalDate getCreation() { // return creation; // } // // public void setCreation(LocalDate creation) { // this.creation = creation; // } // // @Override // public String toString() { // final StringBuilder sb = new StringBuilder("Ustensile["); // sb.append("Fabrication->"); // sb.append(this.creation); // return sb.toString(); // } // // }
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.time.LocalDate; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import fr.formation.exo11.HEADER; import fr.formation.exo11.domain.RoundPlate; import fr.formation.exo11.domain.Spoon; import fr.formation.exo11.domain.SquarePlate; import fr.formation.exo11.domain.Utensil;
new InputStreamReader(this.inputData))) { String line; LOGGER.debug("Début lecture du flux :"); boolean firstLine = true; while ((line = reader.readLine()) != null) { if (firstLine) { this.buildHeaders(line); firstLine = false; } else { result.add(this.buildUtensil(line)); } LOGGER.debug(line); } } catch (IOException e) { LOGGER.error("Erreur pendant la lecture du fichier :", e); System.exit(-1); } return result; } private Utensil buildUtensil(String line) { Utensil utensil = null; final String[] data = line.split(CSV_SEPARATOR); // Construire l'instance avec la colonne Type. final String type = data[this.headerMap.get(HEADER.TYPE)]; switch (type) { case "Assiette ronde": utensil = new RoundPlate(); break; case "Assiette carré":
// Path: src/fr/formation/exo11/HEADER.java // public enum HEADER { // TYPE("Type"), YEAR("Année"), SCORE("Cote"); // // public final String column; // // private HEADER(String column) { // this.column = column; // } // } // // Path: src/fr/formation/exo11/domain/RoundPlate.java // public class RoundPlate extends Utensil implements Plate { // // private float radius; // // @Override // public float calcArea() { // return (float) (Math.pow(this.radius, 2) * Math.PI); // } // // @Override // public void setScore(Object obj) { // this.setRadius(Float.parseFloat(obj.toString())); // } // // public float getRadius() { // return radius; // } // // public void setRadius(float radius) { // this.radius = radius; // } // // @Override // public String toString() { // return super.toString().replace("Ustensile", "Assiette ronde"); // } // // } // // Path: src/fr/formation/exo11/domain/Spoon.java // public class Spoon extends Utensil { // // private float length; // // public float getLength() { // return length; // } // // public void setLength(float length) { // this.length = length; // } // // @Override // public void setScore(Object obj) { // this.setLength(Float.parseFloat(obj.toString())); // } // // @Override // public String toString() { // return super.toString().replace("Ustensile", "Cuillère"); // } // // } // // Path: src/fr/formation/exo11/domain/SquarePlate.java // public class SquarePlate extends Utensil implements Plate { // // private float score; // // @Override // public float calcArea() { // return (float) Math.pow(score, 2); // } // // public float getScore() { // return score; // } // // @Override // public void setScore(Object score) { // this.score = Float.parseFloat(score.toString()); // } // // @Override // public String toString() { // return super.toString().replace("Ustensile", "Assiette carré"); // } // // } // // Path: src/fr/formation/exo11/domain/Utensil.java // public abstract class Utensil { // private LocalDate creation; // // public abstract void setScore(Object obj); // // /** // * Calcul générique de la valeur d'un ustensile si il a plus de 50 ans // * (sinon sa valeur est 0). // * // * @param current la date à partir de laquelle calculer l'année en cours. // * @return int la valeur calculée. // */ // public int calcValue(LocalDate current) { // final int age = current.getYear() - this.creation.getYear(); // return age > 50 ? age - 50 : 0; // } // // public LocalDate getCreation() { // return creation; // } // // public void setCreation(LocalDate creation) { // this.creation = creation; // } // // @Override // public String toString() { // final StringBuilder sb = new StringBuilder("Ustensile["); // sb.append("Fabrication->"); // sb.append(this.creation); // return sb.toString(); // } // // } // Path: src/fr/formation/exo11/parser/CsvParser.java import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.time.LocalDate; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import fr.formation.exo11.HEADER; import fr.formation.exo11.domain.RoundPlate; import fr.formation.exo11.domain.Spoon; import fr.formation.exo11.domain.SquarePlate; import fr.formation.exo11.domain.Utensil; new InputStreamReader(this.inputData))) { String line; LOGGER.debug("Début lecture du flux :"); boolean firstLine = true; while ((line = reader.readLine()) != null) { if (firstLine) { this.buildHeaders(line); firstLine = false; } else { result.add(this.buildUtensil(line)); } LOGGER.debug(line); } } catch (IOException e) { LOGGER.error("Erreur pendant la lecture du fichier :", e); System.exit(-1); } return result; } private Utensil buildUtensil(String line) { Utensil utensil = null; final String[] data = line.split(CSV_SEPARATOR); // Construire l'instance avec la colonne Type. final String type = data[this.headerMap.get(HEADER.TYPE)]; switch (type) { case "Assiette ronde": utensil = new RoundPlate(); break; case "Assiette carré":
utensil = new SquarePlate();
Elvynia/formation-exercices
src/fr/formation/exo11/parser/CsvParser.java
// Path: src/fr/formation/exo11/HEADER.java // public enum HEADER { // TYPE("Type"), YEAR("Année"), SCORE("Cote"); // // public final String column; // // private HEADER(String column) { // this.column = column; // } // } // // Path: src/fr/formation/exo11/domain/RoundPlate.java // public class RoundPlate extends Utensil implements Plate { // // private float radius; // // @Override // public float calcArea() { // return (float) (Math.pow(this.radius, 2) * Math.PI); // } // // @Override // public void setScore(Object obj) { // this.setRadius(Float.parseFloat(obj.toString())); // } // // public float getRadius() { // return radius; // } // // public void setRadius(float radius) { // this.radius = radius; // } // // @Override // public String toString() { // return super.toString().replace("Ustensile", "Assiette ronde"); // } // // } // // Path: src/fr/formation/exo11/domain/Spoon.java // public class Spoon extends Utensil { // // private float length; // // public float getLength() { // return length; // } // // public void setLength(float length) { // this.length = length; // } // // @Override // public void setScore(Object obj) { // this.setLength(Float.parseFloat(obj.toString())); // } // // @Override // public String toString() { // return super.toString().replace("Ustensile", "Cuillère"); // } // // } // // Path: src/fr/formation/exo11/domain/SquarePlate.java // public class SquarePlate extends Utensil implements Plate { // // private float score; // // @Override // public float calcArea() { // return (float) Math.pow(score, 2); // } // // public float getScore() { // return score; // } // // @Override // public void setScore(Object score) { // this.score = Float.parseFloat(score.toString()); // } // // @Override // public String toString() { // return super.toString().replace("Ustensile", "Assiette carré"); // } // // } // // Path: src/fr/formation/exo11/domain/Utensil.java // public abstract class Utensil { // private LocalDate creation; // // public abstract void setScore(Object obj); // // /** // * Calcul générique de la valeur d'un ustensile si il a plus de 50 ans // * (sinon sa valeur est 0). // * // * @param current la date à partir de laquelle calculer l'année en cours. // * @return int la valeur calculée. // */ // public int calcValue(LocalDate current) { // final int age = current.getYear() - this.creation.getYear(); // return age > 50 ? age - 50 : 0; // } // // public LocalDate getCreation() { // return creation; // } // // public void setCreation(LocalDate creation) { // this.creation = creation; // } // // @Override // public String toString() { // final StringBuilder sb = new StringBuilder("Ustensile["); // sb.append("Fabrication->"); // sb.append(this.creation); // return sb.toString(); // } // // }
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.time.LocalDate; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import fr.formation.exo11.HEADER; import fr.formation.exo11.domain.RoundPlate; import fr.formation.exo11.domain.Spoon; import fr.formation.exo11.domain.SquarePlate; import fr.formation.exo11.domain.Utensil;
boolean firstLine = true; while ((line = reader.readLine()) != null) { if (firstLine) { this.buildHeaders(line); firstLine = false; } else { result.add(this.buildUtensil(line)); } LOGGER.debug(line); } } catch (IOException e) { LOGGER.error("Erreur pendant la lecture du fichier :", e); System.exit(-1); } return result; } private Utensil buildUtensil(String line) { Utensil utensil = null; final String[] data = line.split(CSV_SEPARATOR); // Construire l'instance avec la colonne Type. final String type = data[this.headerMap.get(HEADER.TYPE)]; switch (type) { case "Assiette ronde": utensil = new RoundPlate(); break; case "Assiette carré": utensil = new SquarePlate(); break; case "cuillière":
// Path: src/fr/formation/exo11/HEADER.java // public enum HEADER { // TYPE("Type"), YEAR("Année"), SCORE("Cote"); // // public final String column; // // private HEADER(String column) { // this.column = column; // } // } // // Path: src/fr/formation/exo11/domain/RoundPlate.java // public class RoundPlate extends Utensil implements Plate { // // private float radius; // // @Override // public float calcArea() { // return (float) (Math.pow(this.radius, 2) * Math.PI); // } // // @Override // public void setScore(Object obj) { // this.setRadius(Float.parseFloat(obj.toString())); // } // // public float getRadius() { // return radius; // } // // public void setRadius(float radius) { // this.radius = radius; // } // // @Override // public String toString() { // return super.toString().replace("Ustensile", "Assiette ronde"); // } // // } // // Path: src/fr/formation/exo11/domain/Spoon.java // public class Spoon extends Utensil { // // private float length; // // public float getLength() { // return length; // } // // public void setLength(float length) { // this.length = length; // } // // @Override // public void setScore(Object obj) { // this.setLength(Float.parseFloat(obj.toString())); // } // // @Override // public String toString() { // return super.toString().replace("Ustensile", "Cuillère"); // } // // } // // Path: src/fr/formation/exo11/domain/SquarePlate.java // public class SquarePlate extends Utensil implements Plate { // // private float score; // // @Override // public float calcArea() { // return (float) Math.pow(score, 2); // } // // public float getScore() { // return score; // } // // @Override // public void setScore(Object score) { // this.score = Float.parseFloat(score.toString()); // } // // @Override // public String toString() { // return super.toString().replace("Ustensile", "Assiette carré"); // } // // } // // Path: src/fr/formation/exo11/domain/Utensil.java // public abstract class Utensil { // private LocalDate creation; // // public abstract void setScore(Object obj); // // /** // * Calcul générique de la valeur d'un ustensile si il a plus de 50 ans // * (sinon sa valeur est 0). // * // * @param current la date à partir de laquelle calculer l'année en cours. // * @return int la valeur calculée. // */ // public int calcValue(LocalDate current) { // final int age = current.getYear() - this.creation.getYear(); // return age > 50 ? age - 50 : 0; // } // // public LocalDate getCreation() { // return creation; // } // // public void setCreation(LocalDate creation) { // this.creation = creation; // } // // @Override // public String toString() { // final StringBuilder sb = new StringBuilder("Ustensile["); // sb.append("Fabrication->"); // sb.append(this.creation); // return sb.toString(); // } // // } // Path: src/fr/formation/exo11/parser/CsvParser.java import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.time.LocalDate; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import fr.formation.exo11.HEADER; import fr.formation.exo11.domain.RoundPlate; import fr.formation.exo11.domain.Spoon; import fr.formation.exo11.domain.SquarePlate; import fr.formation.exo11.domain.Utensil; boolean firstLine = true; while ((line = reader.readLine()) != null) { if (firstLine) { this.buildHeaders(line); firstLine = false; } else { result.add(this.buildUtensil(line)); } LOGGER.debug(line); } } catch (IOException e) { LOGGER.error("Erreur pendant la lecture du fichier :", e); System.exit(-1); } return result; } private Utensil buildUtensil(String line) { Utensil utensil = null; final String[] data = line.split(CSV_SEPARATOR); // Construire l'instance avec la colonne Type. final String type = data[this.headerMap.get(HEADER.TYPE)]; switch (type) { case "Assiette ronde": utensil = new RoundPlate(); break; case "Assiette carré": utensil = new SquarePlate(); break; case "cuillière":
utensil = new Spoon();
Elvynia/formation-exercices
src/fr/formation/exo2/objets/Warehouseman.java
// Path: src/fr/formation/exo2/Constants.java // public class Constants { // // /** // * Préfixe du libellé des factures de frais de déplacement pour les indépendants. // */ // public static final String TRAVEL_FEES = "Frais de déplacement"; // // /** // * Salaire par unité pour un employé dans la production. // */ // public static final int EMPLOYE_PRODUCER_UNITCOST = 5; // // /** // * Prime mensuelle pour un représentant. // */ // public static final int EMPLOYE_REPRESENTANT_PRIME = 800; // // /** // * Prime bonus pour les employés manipulant des produits à risque. // */ // public static final int EMPLOYE_RISK_PRIME = 200; // // /** // * Prime mensuelle pour un vendeur. // */ // public static final int EMPLOYE_SALES_PRIME = 400; // // /** // * Pourcentage du chiffre d'affaire permettant de calculer le salaire d'un // * vendeur. // */ // public static final int EMPLOYE_SALES_TURNOVER_PART = 20; // // /** // * Salaire horaire pour les employés de la manutention. // */ // public static final int EMPLOYE_WAREHOUSE_HOURCOST = 65; // }
import java.util.Date; import fr.formation.exo2.Constants;
package fr.formation.exo2.objets; /** * Employé dans le domaine de la manutention. * * @author hb-asus * */ public class Warehouseman extends Employee { // Propriété spécifique à un employé manutentionnaire. int workHours; /** * Constructeur. * * @param name * le nom de l'employé. * @param firstName * le prénom de l'employé. * @param age * l'age de l'employé. * @param hireDate * la date à laquelle l'employé a été embauché. * @param unitProduced * le nombre d'unités produites par l'employé pour le mois * courant. */ public Warehouseman(String name, String firstName, int age, Date hireDate, int workHours) { // Appel au constructeur de la classe parent Employee. super(name, firstName, age, hireDate); this.workHours = workHours; } /** * {@inheritDoc} Calcul à partir du nombre d'heure et du coût d'une heure de * travail. */ @Override public int calculateSalary() {
// Path: src/fr/formation/exo2/Constants.java // public class Constants { // // /** // * Préfixe du libellé des factures de frais de déplacement pour les indépendants. // */ // public static final String TRAVEL_FEES = "Frais de déplacement"; // // /** // * Salaire par unité pour un employé dans la production. // */ // public static final int EMPLOYE_PRODUCER_UNITCOST = 5; // // /** // * Prime mensuelle pour un représentant. // */ // public static final int EMPLOYE_REPRESENTANT_PRIME = 800; // // /** // * Prime bonus pour les employés manipulant des produits à risque. // */ // public static final int EMPLOYE_RISK_PRIME = 200; // // /** // * Prime mensuelle pour un vendeur. // */ // public static final int EMPLOYE_SALES_PRIME = 400; // // /** // * Pourcentage du chiffre d'affaire permettant de calculer le salaire d'un // * vendeur. // */ // public static final int EMPLOYE_SALES_TURNOVER_PART = 20; // // /** // * Salaire horaire pour les employés de la manutention. // */ // public static final int EMPLOYE_WAREHOUSE_HOURCOST = 65; // } // Path: src/fr/formation/exo2/objets/Warehouseman.java import java.util.Date; import fr.formation.exo2.Constants; package fr.formation.exo2.objets; /** * Employé dans le domaine de la manutention. * * @author hb-asus * */ public class Warehouseman extends Employee { // Propriété spécifique à un employé manutentionnaire. int workHours; /** * Constructeur. * * @param name * le nom de l'employé. * @param firstName * le prénom de l'employé. * @param age * l'age de l'employé. * @param hireDate * la date à laquelle l'employé a été embauché. * @param unitProduced * le nombre d'unités produites par l'employé pour le mois * courant. */ public Warehouseman(String name, String firstName, int age, Date hireDate, int workHours) { // Appel au constructeur de la classe parent Employee. super(name, firstName, age, hireDate); this.workHours = workHours; } /** * {@inheritDoc} Calcul à partir du nombre d'heure et du coût d'une heure de * travail. */ @Override public int calculateSalary() {
return this.workHours * Constants.EMPLOYE_WAREHOUSE_HOURCOST;
Elvynia/formation-exercices
src/fr/formation/exo2/objets/WarehousemanWithRisk.java
// Path: src/fr/formation/exo2/Constants.java // public class Constants { // // /** // * Préfixe du libellé des factures de frais de déplacement pour les indépendants. // */ // public static final String TRAVEL_FEES = "Frais de déplacement"; // // /** // * Salaire par unité pour un employé dans la production. // */ // public static final int EMPLOYE_PRODUCER_UNITCOST = 5; // // /** // * Prime mensuelle pour un représentant. // */ // public static final int EMPLOYE_REPRESENTANT_PRIME = 800; // // /** // * Prime bonus pour les employés manipulant des produits à risque. // */ // public static final int EMPLOYE_RISK_PRIME = 200; // // /** // * Prime mensuelle pour un vendeur. // */ // public static final int EMPLOYE_SALES_PRIME = 400; // // /** // * Pourcentage du chiffre d'affaire permettant de calculer le salaire d'un // * vendeur. // */ // public static final int EMPLOYE_SALES_TURNOVER_PART = 20; // // /** // * Salaire horaire pour les employés de la manutention. // */ // public static final int EMPLOYE_WAREHOUSE_HOURCOST = 65; // }
import java.util.Date; import fr.formation.exo2.Constants;
package fr.formation.exo2.objets; /** * Employé dans le domaine de la manutention et manipulant des produits à * risque. * * @author hb-asus * */ public class WarehousemanWithRisk extends Warehouseman { /** * Constructeur. * * @param name * le nom de l'employé. * @param firstName * le prénom de l'employé. * @param age * l'age de l'employé. * @param hireDate * la date à laquelle l'employé a été embauché. * @param workHours * le nombre d'heures travaillées dans le mois. */ public WarehousemanWithRisk(String name, String firstName, int age, Date hireDate, int workHours) { // Appel au constructeur de la classe parent Warehouseman. super(name, firstName, age, hireDate, workHours); } /** * {@inheritDoc} Ajout de la prime de risque. */ @Override public int calculateSalary() {
// Path: src/fr/formation/exo2/Constants.java // public class Constants { // // /** // * Préfixe du libellé des factures de frais de déplacement pour les indépendants. // */ // public static final String TRAVEL_FEES = "Frais de déplacement"; // // /** // * Salaire par unité pour un employé dans la production. // */ // public static final int EMPLOYE_PRODUCER_UNITCOST = 5; // // /** // * Prime mensuelle pour un représentant. // */ // public static final int EMPLOYE_REPRESENTANT_PRIME = 800; // // /** // * Prime bonus pour les employés manipulant des produits à risque. // */ // public static final int EMPLOYE_RISK_PRIME = 200; // // /** // * Prime mensuelle pour un vendeur. // */ // public static final int EMPLOYE_SALES_PRIME = 400; // // /** // * Pourcentage du chiffre d'affaire permettant de calculer le salaire d'un // * vendeur. // */ // public static final int EMPLOYE_SALES_TURNOVER_PART = 20; // // /** // * Salaire horaire pour les employés de la manutention. // */ // public static final int EMPLOYE_WAREHOUSE_HOURCOST = 65; // } // Path: src/fr/formation/exo2/objets/WarehousemanWithRisk.java import java.util.Date; import fr.formation.exo2.Constants; package fr.formation.exo2.objets; /** * Employé dans le domaine de la manutention et manipulant des produits à * risque. * * @author hb-asus * */ public class WarehousemanWithRisk extends Warehouseman { /** * Constructeur. * * @param name * le nom de l'employé. * @param firstName * le prénom de l'employé. * @param age * l'age de l'employé. * @param hireDate * la date à laquelle l'employé a été embauché. * @param workHours * le nombre d'heures travaillées dans le mois. */ public WarehousemanWithRisk(String name, String firstName, int age, Date hireDate, int workHours) { // Appel au constructeur de la classe parent Warehouseman. super(name, firstName, age, hireDate, workHours); } /** * {@inheritDoc} Ajout de la prime de risque. */ @Override public int calculateSalary() {
return super.calculateSalary() + Constants.EMPLOYE_RISK_PRIME;
Elvynia/formation-exercices
src/fr/formation/exo2/objets/ProducerWithRisk.java
// Path: src/fr/formation/exo2/Constants.java // public class Constants { // // /** // * Préfixe du libellé des factures de frais de déplacement pour les indépendants. // */ // public static final String TRAVEL_FEES = "Frais de déplacement"; // // /** // * Salaire par unité pour un employé dans la production. // */ // public static final int EMPLOYE_PRODUCER_UNITCOST = 5; // // /** // * Prime mensuelle pour un représentant. // */ // public static final int EMPLOYE_REPRESENTANT_PRIME = 800; // // /** // * Prime bonus pour les employés manipulant des produits à risque. // */ // public static final int EMPLOYE_RISK_PRIME = 200; // // /** // * Prime mensuelle pour un vendeur. // */ // public static final int EMPLOYE_SALES_PRIME = 400; // // /** // * Pourcentage du chiffre d'affaire permettant de calculer le salaire d'un // * vendeur. // */ // public static final int EMPLOYE_SALES_TURNOVER_PART = 20; // // /** // * Salaire horaire pour les employés de la manutention. // */ // public static final int EMPLOYE_WAREHOUSE_HOURCOST = 65; // }
import java.util.Date; import fr.formation.exo2.Constants;
package fr.formation.exo2.objets; /** * Employé dans le domaine de la production et manipulant des produits à risque. * * @author hb-asus * */ public class ProducerWithRisk extends Producer { /** * Constructeur. * * @param name * le nom de l'employé. * @param firstName * le prénom de l'employé. * @param age * l'age de l'employé. * @param hireDate * la date à laquelle l'employé a été embauché. * @param unitProduced * le nombre d'unités produites par l'employé pour le mois * courant. */ public ProducerWithRisk(String name, String firstName, int age, Date hireDate, int unitProduced) { // Appel au constructeur de la classe parent Producer. super(name, firstName, age, hireDate, unitProduced); } /** * {@inheritDoc} Ajout de la prime de risque. */ @Override public int calculateSalary() {
// Path: src/fr/formation/exo2/Constants.java // public class Constants { // // /** // * Préfixe du libellé des factures de frais de déplacement pour les indépendants. // */ // public static final String TRAVEL_FEES = "Frais de déplacement"; // // /** // * Salaire par unité pour un employé dans la production. // */ // public static final int EMPLOYE_PRODUCER_UNITCOST = 5; // // /** // * Prime mensuelle pour un représentant. // */ // public static final int EMPLOYE_REPRESENTANT_PRIME = 800; // // /** // * Prime bonus pour les employés manipulant des produits à risque. // */ // public static final int EMPLOYE_RISK_PRIME = 200; // // /** // * Prime mensuelle pour un vendeur. // */ // public static final int EMPLOYE_SALES_PRIME = 400; // // /** // * Pourcentage du chiffre d'affaire permettant de calculer le salaire d'un // * vendeur. // */ // public static final int EMPLOYE_SALES_TURNOVER_PART = 20; // // /** // * Salaire horaire pour les employés de la manutention. // */ // public static final int EMPLOYE_WAREHOUSE_HOURCOST = 65; // } // Path: src/fr/formation/exo2/objets/ProducerWithRisk.java import java.util.Date; import fr.formation.exo2.Constants; package fr.formation.exo2.objets; /** * Employé dans le domaine de la production et manipulant des produits à risque. * * @author hb-asus * */ public class ProducerWithRisk extends Producer { /** * Constructeur. * * @param name * le nom de l'employé. * @param firstName * le prénom de l'employé. * @param age * l'age de l'employé. * @param hireDate * la date à laquelle l'employé a été embauché. * @param unitProduced * le nombre d'unités produites par l'employé pour le mois * courant. */ public ProducerWithRisk(String name, String firstName, int age, Date hireDate, int unitProduced) { // Appel au constructeur de la classe parent Producer. super(name, firstName, age, hireDate, unitProduced); } /** * {@inheritDoc} Ajout de la prime de risque. */ @Override public int calculateSalary() {
return super.calculateSalary() + Constants.EMPLOYE_RISK_PRIME;
Elvynia/formation-exercices
src/fr/formation/exo2/objets/Freelance.java
// Path: src/fr/formation/exo2/Constants.java // public class Constants { // // /** // * Préfixe du libellé des factures de frais de déplacement pour les indépendants. // */ // public static final String TRAVEL_FEES = "Frais de déplacement"; // // /** // * Salaire par unité pour un employé dans la production. // */ // public static final int EMPLOYE_PRODUCER_UNITCOST = 5; // // /** // * Prime mensuelle pour un représentant. // */ // public static final int EMPLOYE_REPRESENTANT_PRIME = 800; // // /** // * Prime bonus pour les employés manipulant des produits à risque. // */ // public static final int EMPLOYE_RISK_PRIME = 200; // // /** // * Prime mensuelle pour un vendeur. // */ // public static final int EMPLOYE_SALES_PRIME = 400; // // /** // * Pourcentage du chiffre d'affaire permettant de calculer le salaire d'un // * vendeur. // */ // public static final int EMPLOYE_SALES_TURNOVER_PART = 20; // // /** // * Salaire horaire pour les employés de la manutention. // */ // public static final int EMPLOYE_WAREHOUSE_HOURCOST = 65; // }
import java.util.ArrayList; import java.util.List; import fr.formation.exo2.Constants;
package fr.formation.exo2.objets; public class Freelance implements Payrole { private String name; private String siren; private final List<Invoice> invoices; public Freelance() { this.invoices = new ArrayList<>(); } /** * {@inheritDoc} */ @Override public int calculateSalary() { int result = 0; for (final Invoice invoice : this.invoices) {
// Path: src/fr/formation/exo2/Constants.java // public class Constants { // // /** // * Préfixe du libellé des factures de frais de déplacement pour les indépendants. // */ // public static final String TRAVEL_FEES = "Frais de déplacement"; // // /** // * Salaire par unité pour un employé dans la production. // */ // public static final int EMPLOYE_PRODUCER_UNITCOST = 5; // // /** // * Prime mensuelle pour un représentant. // */ // public static final int EMPLOYE_REPRESENTANT_PRIME = 800; // // /** // * Prime bonus pour les employés manipulant des produits à risque. // */ // public static final int EMPLOYE_RISK_PRIME = 200; // // /** // * Prime mensuelle pour un vendeur. // */ // public static final int EMPLOYE_SALES_PRIME = 400; // // /** // * Pourcentage du chiffre d'affaire permettant de calculer le salaire d'un // * vendeur. // */ // public static final int EMPLOYE_SALES_TURNOVER_PART = 20; // // /** // * Salaire horaire pour les employés de la manutention. // */ // public static final int EMPLOYE_WAREHOUSE_HOURCOST = 65; // } // Path: src/fr/formation/exo2/objets/Freelance.java import java.util.ArrayList; import java.util.List; import fr.formation.exo2.Constants; package fr.formation.exo2.objets; public class Freelance implements Payrole { private String name; private String siren; private final List<Invoice> invoices; public Freelance() { this.invoices = new ArrayList<>(); } /** * {@inheritDoc} */ @Override public int calculateSalary() { int result = 0; for (final Invoice invoice : this.invoices) {
if (!invoice.getLabel().startsWith(Constants.TRAVEL_FEES)) {
JProffa/JProffa
Profiler/src/main/java/net/jproffa/profiler/ProfilerTransformer.java
// Path: ProfileData/src/main/java/net/jproffa/profiledata/ProfileData.java // public class ProfileData { // // /** // * Holds information how many times basic block has been called. Indexes are the ones returned by addBasicBlock(). // */ // public static long[] callsToBasicBlock; // private static int basicBlockAmount = 0; // /** // * How costly a basic block is. Naive way to count it is by assuming every bytecodes cost is 1 and multiply by // * amount of bytecodes in the basic block. // */ // public static long[] basicBlockCost; // private static List<Long> basicBlockCostAccumulator = new ArrayList<Long>(); // private static List<String> basicBlockDesc = new ArrayList<String>(); // private static Map<String, Integer> methodStarterBlockMap = new HashMap<String, Integer>(); // // private static boolean profilingEnabled = false; // // /** // * Adds basic block with default cost (1). // * // * @return Index of basic block in arrays. // */ // public static int addBasicBlock() { // return addBasicBlock(1L); // } // // /** // * Adds a new basic block. // * // * @param cost Cost of the basic block. // * @return Index of the basic block in the arrays. // */ // public static int addBasicBlock(long cost) { // return addBasicBlock(cost, "", false); // } // // /** // * Adds a new basic block with a description. // * // * @param cost Cost of the basic block. // * @param desc Description of the basic block. // * @return Index of the basic block in the arrays. // */ // public static synchronized int addBasicBlock(long cost, String desc, boolean starter) { // basicBlockAmount++; // basicBlockCostAccumulator.add(cost); // basicBlockDesc.add(desc == null ? "" : desc); // if (starter) { // methodStarterBlockMap.put(desc, basicBlockAmount - 1); // } // return basicBlockAmount - 1; // } // // public static void incrementCallsToBasicBlock(int index) { // if (profilingEnabled) { // callsToBasicBlock[index] += 1; // } // } // // /** // * Reset callsToBasicBlock arrays elements to 0. // */ // public static synchronized void resetCounters() { // if (callsToBasicBlock == null) { // initialize(); // } // for (int i = 0; i < callsToBasicBlock.length; i++) { // callsToBasicBlock[i] = 0L; // } // } // // /** // * Initialize arrays from added basic blocks. Needs to be called before using the arrays. // */ // public static synchronized void initialize() { // long[] newCallsToBasicBlock = new long[basicBlockAmount]; // if (callsToBasicBlock != null) { // System.arraycopy(callsToBasicBlock, 0, newCallsToBasicBlock, 0, callsToBasicBlock.length); // } // callsToBasicBlock = newCallsToBasicBlock; // // basicBlockCost = new long[basicBlockCostAccumulator.size()]; // for (int i = 0; i < basicBlockCostAccumulator.size(); i++) { // basicBlockCost[i] = basicBlockCostAccumulator.get(i); // } // } // // public static long[] getCallsToBasicBlock() { // return callsToBasicBlock; // } // // public static int getBasicBlockAmount() { // return basicBlockAmount; // } // // public static long[] getBasicBlockCost() { // return basicBlockCost; // } // // public static List<String> getBasicBlockDesc() { // return basicBlockDesc; // } // // // /** // * Are counter increments allowed. // * // * @return // */ // public static boolean isProfilingEnabled() { // return profilingEnabled; // } // // /** // * Disallow counter increments. // */ // public static void disableProfiling() { // profilingEnabled = false; // } // // /** // * Allow counter increments. // */ // public static void enableProfiling() { // profilingEnabled = true; // } // // public static Map<String, Integer> getMethodStarterBlockMap() { // return methodStarterBlockMap; // } // }
import net.jproffa.profiledata.ProfileData; import org.apache.log4j.Logger; import static org.objectweb.asm.Opcodes.*; import org.objectweb.asm.tree.*; import java.lang.instrument.ClassFileTransformer; import java.lang.instrument.IllegalClassFormatException; import java.security.ProtectionDomain; import java.util.*; import static org.objectweb.asm.tree.AbstractInsnNode.*;
if (ClassBlacklist.isBlacklisted(className)) { return null; } logger.info("Class: " + className); ClassNode classNode = Util.initClassNode(classfileBuffer); // Add counter increment codes in the beginning of basic blocks for (MethodNode methodNode : (List<MethodNode>) classNode.methods) { boolean isNative = (methodNode.access & ACC_NATIVE) != 0; if (isNative) { logger.info("Native method found: " + methodNode.name); continue; } logger.info(" Method: " + methodNode.name + methodNode.desc); InsnList insns = methodNode.instructions; logger.trace(Util.getInsnListString(insns)); // Increase max stack size to allow counter increments methodNode.maxStack += 1; Set<AbstractInsnNode> basicBlockBeginnings = findBasicBlockBeginnings(insns); ArrayList<LinkedList<AbstractInsnNode>> basicBlocks = findBasicBlockInsns(basicBlockBeginnings); insertCountersToBasicBlocks(methodNode, basicBlocks); } byte[] bytecode = Util.generateBytecode(classNode); //String filename = className.substring(className.lastIndexOf('/') + 1); //Util.writeByteArrayToFile(filename + ".class", bytecode); // Initialize counter arrays if (!Agent.isRetransforming()) {
// Path: ProfileData/src/main/java/net/jproffa/profiledata/ProfileData.java // public class ProfileData { // // /** // * Holds information how many times basic block has been called. Indexes are the ones returned by addBasicBlock(). // */ // public static long[] callsToBasicBlock; // private static int basicBlockAmount = 0; // /** // * How costly a basic block is. Naive way to count it is by assuming every bytecodes cost is 1 and multiply by // * amount of bytecodes in the basic block. // */ // public static long[] basicBlockCost; // private static List<Long> basicBlockCostAccumulator = new ArrayList<Long>(); // private static List<String> basicBlockDesc = new ArrayList<String>(); // private static Map<String, Integer> methodStarterBlockMap = new HashMap<String, Integer>(); // // private static boolean profilingEnabled = false; // // /** // * Adds basic block with default cost (1). // * // * @return Index of basic block in arrays. // */ // public static int addBasicBlock() { // return addBasicBlock(1L); // } // // /** // * Adds a new basic block. // * // * @param cost Cost of the basic block. // * @return Index of the basic block in the arrays. // */ // public static int addBasicBlock(long cost) { // return addBasicBlock(cost, "", false); // } // // /** // * Adds a new basic block with a description. // * // * @param cost Cost of the basic block. // * @param desc Description of the basic block. // * @return Index of the basic block in the arrays. // */ // public static synchronized int addBasicBlock(long cost, String desc, boolean starter) { // basicBlockAmount++; // basicBlockCostAccumulator.add(cost); // basicBlockDesc.add(desc == null ? "" : desc); // if (starter) { // methodStarterBlockMap.put(desc, basicBlockAmount - 1); // } // return basicBlockAmount - 1; // } // // public static void incrementCallsToBasicBlock(int index) { // if (profilingEnabled) { // callsToBasicBlock[index] += 1; // } // } // // /** // * Reset callsToBasicBlock arrays elements to 0. // */ // public static synchronized void resetCounters() { // if (callsToBasicBlock == null) { // initialize(); // } // for (int i = 0; i < callsToBasicBlock.length; i++) { // callsToBasicBlock[i] = 0L; // } // } // // /** // * Initialize arrays from added basic blocks. Needs to be called before using the arrays. // */ // public static synchronized void initialize() { // long[] newCallsToBasicBlock = new long[basicBlockAmount]; // if (callsToBasicBlock != null) { // System.arraycopy(callsToBasicBlock, 0, newCallsToBasicBlock, 0, callsToBasicBlock.length); // } // callsToBasicBlock = newCallsToBasicBlock; // // basicBlockCost = new long[basicBlockCostAccumulator.size()]; // for (int i = 0; i < basicBlockCostAccumulator.size(); i++) { // basicBlockCost[i] = basicBlockCostAccumulator.get(i); // } // } // // public static long[] getCallsToBasicBlock() { // return callsToBasicBlock; // } // // public static int getBasicBlockAmount() { // return basicBlockAmount; // } // // public static long[] getBasicBlockCost() { // return basicBlockCost; // } // // public static List<String> getBasicBlockDesc() { // return basicBlockDesc; // } // // // /** // * Are counter increments allowed. // * // * @return // */ // public static boolean isProfilingEnabled() { // return profilingEnabled; // } // // /** // * Disallow counter increments. // */ // public static void disableProfiling() { // profilingEnabled = false; // } // // /** // * Allow counter increments. // */ // public static void enableProfiling() { // profilingEnabled = true; // } // // public static Map<String, Integer> getMethodStarterBlockMap() { // return methodStarterBlockMap; // } // } // Path: Profiler/src/main/java/net/jproffa/profiler/ProfilerTransformer.java import net.jproffa.profiledata.ProfileData; import org.apache.log4j.Logger; import static org.objectweb.asm.Opcodes.*; import org.objectweb.asm.tree.*; import java.lang.instrument.ClassFileTransformer; import java.lang.instrument.IllegalClassFormatException; import java.security.ProtectionDomain; import java.util.*; import static org.objectweb.asm.tree.AbstractInsnNode.*; if (ClassBlacklist.isBlacklisted(className)) { return null; } logger.info("Class: " + className); ClassNode classNode = Util.initClassNode(classfileBuffer); // Add counter increment codes in the beginning of basic blocks for (MethodNode methodNode : (List<MethodNode>) classNode.methods) { boolean isNative = (methodNode.access & ACC_NATIVE) != 0; if (isNative) { logger.info("Native method found: " + methodNode.name); continue; } logger.info(" Method: " + methodNode.name + methodNode.desc); InsnList insns = methodNode.instructions; logger.trace(Util.getInsnListString(insns)); // Increase max stack size to allow counter increments methodNode.maxStack += 1; Set<AbstractInsnNode> basicBlockBeginnings = findBasicBlockBeginnings(insns); ArrayList<LinkedList<AbstractInsnNode>> basicBlocks = findBasicBlockInsns(basicBlockBeginnings); insertCountersToBasicBlocks(methodNode, basicBlocks); } byte[] bytecode = Util.generateBytecode(classNode); //String filename = className.substring(className.lastIndexOf('/') + 1); //Util.writeByteArrayToFile(filename + ".class", bytecode); // Initialize counter arrays if (!Agent.isRetransforming()) {
ProfileData.initialize();
JProffa/JProffa
Java7TestProject/src/test/java/net/jproffa/test/Java7VerifierTest.java
// Path: Profiler/src/main/java/net/jproffa/profiler/WithProfiling.java // public final class WithProfiling implements TestRule { // private final boolean shouldEnableProfiling; // // private WithProfiling(boolean shouldEnableProfiling) { // this.shouldEnableProfiling = shouldEnableProfiling; // } // // public static void in(Runnable inner) { // Util.loadAgent(); // ProfileData.resetCounters(); // ProfileData.enableProfiling(); // try { // inner.run(); // } finally { // ProfileData.disableProfiling(); // } // } // // public static void in(RunnableEx inner) throws Exception { // Util.loadAgent(); // ProfileData.resetCounters(); // ProfileData.enableProfiling(); // try { // inner.run(); // } finally { // ProfileData.disableProfiling(); // } // } // // public static <V> V in(Callable<V> inner) throws Exception { // Util.loadAgent(); // ProfileData.resetCounters(); // ProfileData.enableProfiling(); // try { // return inner.call(); // } finally { // ProfileData.disableProfiling(); // } // } // // /** // * Returns a JUnit rule that sets up and enables profiling before each test. // */ // public static WithProfiling rule() { // return new WithProfiling(true); // } // // /** // * Returns a JUnit rule that sets up and optionally enables profiling before each test. // * // * <p> // * If {@code enableProfiling} is false, it only ensures the profiler is initialized // * but disables profiling before each test. The test may use // * {@code WithProfiling.in(...)} to profile things itself. // * Note that you should need this rarely as the rule blacklists the test class // * anyway, so code in it does not count towards the profiling score. // */ // public static WithProfiling rule(boolean enableProfiling) { // return new WithProfiling(enableProfiling); // } // // @Override // public Statement apply(final Statement base, final Description description) { // return new Statement() { // @Override // public void evaluate() throws Throwable { // Util.loadAgent(); // ClassBlacklist.add(description.getTestClass()); // ProfileData.resetCounters(); // if (shouldEnableProfiling) { // ProfileData.enableProfiling(); // } else { // ProfileData.disableProfiling(); // } // try { // base.evaluate(); // } finally { // ProfileData.disableProfiling(); // } // } // }; // } // } // // Path: Java7TestProject/src/main/java/net/jproffa/testproject/TestedClass.java // public class TestedClass { // public static long factorial(long n) { // long result = 1; // for (int i = 1; i <= n; ++i) { // result = result * i; // } // return result; // } // }
import net.jproffa.profiler.WithProfiling; import net.jproffa.testproject.TestedClass; import org.junit.Test;
package net.jproffa.test; public class Java7VerifierTest { @Test public void testProfilingReallySimpleCodeUnderJava7() {
// Path: Profiler/src/main/java/net/jproffa/profiler/WithProfiling.java // public final class WithProfiling implements TestRule { // private final boolean shouldEnableProfiling; // // private WithProfiling(boolean shouldEnableProfiling) { // this.shouldEnableProfiling = shouldEnableProfiling; // } // // public static void in(Runnable inner) { // Util.loadAgent(); // ProfileData.resetCounters(); // ProfileData.enableProfiling(); // try { // inner.run(); // } finally { // ProfileData.disableProfiling(); // } // } // // public static void in(RunnableEx inner) throws Exception { // Util.loadAgent(); // ProfileData.resetCounters(); // ProfileData.enableProfiling(); // try { // inner.run(); // } finally { // ProfileData.disableProfiling(); // } // } // // public static <V> V in(Callable<V> inner) throws Exception { // Util.loadAgent(); // ProfileData.resetCounters(); // ProfileData.enableProfiling(); // try { // return inner.call(); // } finally { // ProfileData.disableProfiling(); // } // } // // /** // * Returns a JUnit rule that sets up and enables profiling before each test. // */ // public static WithProfiling rule() { // return new WithProfiling(true); // } // // /** // * Returns a JUnit rule that sets up and optionally enables profiling before each test. // * // * <p> // * If {@code enableProfiling} is false, it only ensures the profiler is initialized // * but disables profiling before each test. The test may use // * {@code WithProfiling.in(...)} to profile things itself. // * Note that you should need this rarely as the rule blacklists the test class // * anyway, so code in it does not count towards the profiling score. // */ // public static WithProfiling rule(boolean enableProfiling) { // return new WithProfiling(enableProfiling); // } // // @Override // public Statement apply(final Statement base, final Description description) { // return new Statement() { // @Override // public void evaluate() throws Throwable { // Util.loadAgent(); // ClassBlacklist.add(description.getTestClass()); // ProfileData.resetCounters(); // if (shouldEnableProfiling) { // ProfileData.enableProfiling(); // } else { // ProfileData.disableProfiling(); // } // try { // base.evaluate(); // } finally { // ProfileData.disableProfiling(); // } // } // }; // } // } // // Path: Java7TestProject/src/main/java/net/jproffa/testproject/TestedClass.java // public class TestedClass { // public static long factorial(long n) { // long result = 1; // for (int i = 1; i <= n; ++i) { // result = result * i; // } // return result; // } // } // Path: Java7TestProject/src/test/java/net/jproffa/test/Java7VerifierTest.java import net.jproffa.profiler.WithProfiling; import net.jproffa.testproject.TestedClass; import org.junit.Test; package net.jproffa.test; public class Java7VerifierTest { @Test public void testProfilingReallySimpleCodeUnderJava7() {
WithProfiling.in(new Runnable() {
JProffa/JProffa
Java7TestProject/src/test/java/net/jproffa/test/Java7VerifierTest.java
// Path: Profiler/src/main/java/net/jproffa/profiler/WithProfiling.java // public final class WithProfiling implements TestRule { // private final boolean shouldEnableProfiling; // // private WithProfiling(boolean shouldEnableProfiling) { // this.shouldEnableProfiling = shouldEnableProfiling; // } // // public static void in(Runnable inner) { // Util.loadAgent(); // ProfileData.resetCounters(); // ProfileData.enableProfiling(); // try { // inner.run(); // } finally { // ProfileData.disableProfiling(); // } // } // // public static void in(RunnableEx inner) throws Exception { // Util.loadAgent(); // ProfileData.resetCounters(); // ProfileData.enableProfiling(); // try { // inner.run(); // } finally { // ProfileData.disableProfiling(); // } // } // // public static <V> V in(Callable<V> inner) throws Exception { // Util.loadAgent(); // ProfileData.resetCounters(); // ProfileData.enableProfiling(); // try { // return inner.call(); // } finally { // ProfileData.disableProfiling(); // } // } // // /** // * Returns a JUnit rule that sets up and enables profiling before each test. // */ // public static WithProfiling rule() { // return new WithProfiling(true); // } // // /** // * Returns a JUnit rule that sets up and optionally enables profiling before each test. // * // * <p> // * If {@code enableProfiling} is false, it only ensures the profiler is initialized // * but disables profiling before each test. The test may use // * {@code WithProfiling.in(...)} to profile things itself. // * Note that you should need this rarely as the rule blacklists the test class // * anyway, so code in it does not count towards the profiling score. // */ // public static WithProfiling rule(boolean enableProfiling) { // return new WithProfiling(enableProfiling); // } // // @Override // public Statement apply(final Statement base, final Description description) { // return new Statement() { // @Override // public void evaluate() throws Throwable { // Util.loadAgent(); // ClassBlacklist.add(description.getTestClass()); // ProfileData.resetCounters(); // if (shouldEnableProfiling) { // ProfileData.enableProfiling(); // } else { // ProfileData.disableProfiling(); // } // try { // base.evaluate(); // } finally { // ProfileData.disableProfiling(); // } // } // }; // } // } // // Path: Java7TestProject/src/main/java/net/jproffa/testproject/TestedClass.java // public class TestedClass { // public static long factorial(long n) { // long result = 1; // for (int i = 1; i <= n; ++i) { // result = result * i; // } // return result; // } // }
import net.jproffa.profiler.WithProfiling; import net.jproffa.testproject.TestedClass; import org.junit.Test;
package net.jproffa.test; public class Java7VerifierTest { @Test public void testProfilingReallySimpleCodeUnderJava7() { WithProfiling.in(new Runnable() { @Override public void run() {
// Path: Profiler/src/main/java/net/jproffa/profiler/WithProfiling.java // public final class WithProfiling implements TestRule { // private final boolean shouldEnableProfiling; // // private WithProfiling(boolean shouldEnableProfiling) { // this.shouldEnableProfiling = shouldEnableProfiling; // } // // public static void in(Runnable inner) { // Util.loadAgent(); // ProfileData.resetCounters(); // ProfileData.enableProfiling(); // try { // inner.run(); // } finally { // ProfileData.disableProfiling(); // } // } // // public static void in(RunnableEx inner) throws Exception { // Util.loadAgent(); // ProfileData.resetCounters(); // ProfileData.enableProfiling(); // try { // inner.run(); // } finally { // ProfileData.disableProfiling(); // } // } // // public static <V> V in(Callable<V> inner) throws Exception { // Util.loadAgent(); // ProfileData.resetCounters(); // ProfileData.enableProfiling(); // try { // return inner.call(); // } finally { // ProfileData.disableProfiling(); // } // } // // /** // * Returns a JUnit rule that sets up and enables profiling before each test. // */ // public static WithProfiling rule() { // return new WithProfiling(true); // } // // /** // * Returns a JUnit rule that sets up and optionally enables profiling before each test. // * // * <p> // * If {@code enableProfiling} is false, it only ensures the profiler is initialized // * but disables profiling before each test. The test may use // * {@code WithProfiling.in(...)} to profile things itself. // * Note that you should need this rarely as the rule blacklists the test class // * anyway, so code in it does not count towards the profiling score. // */ // public static WithProfiling rule(boolean enableProfiling) { // return new WithProfiling(enableProfiling); // } // // @Override // public Statement apply(final Statement base, final Description description) { // return new Statement() { // @Override // public void evaluate() throws Throwable { // Util.loadAgent(); // ClassBlacklist.add(description.getTestClass()); // ProfileData.resetCounters(); // if (shouldEnableProfiling) { // ProfileData.enableProfiling(); // } else { // ProfileData.disableProfiling(); // } // try { // base.evaluate(); // } finally { // ProfileData.disableProfiling(); // } // } // }; // } // } // // Path: Java7TestProject/src/main/java/net/jproffa/testproject/TestedClass.java // public class TestedClass { // public static long factorial(long n) { // long result = 1; // for (int i = 1; i <= n; ++i) { // result = result * i; // } // return result; // } // } // Path: Java7TestProject/src/test/java/net/jproffa/test/Java7VerifierTest.java import net.jproffa.profiler.WithProfiling; import net.jproffa.testproject.TestedClass; import org.junit.Test; package net.jproffa.test; public class Java7VerifierTest { @Test public void testProfilingReallySimpleCodeUnderJava7() { WithProfiling.in(new Runnable() { @Override public void run() {
TestedClass.factorial(15);
JProffa/JProffa
Profiler/src/main/java/net/jproffa/profiler/DefaultThreadBlockerPolicy.java
// Path: ProfileData/src/main/java/net/jproffa/profiledata/ProfileData.java // public class ProfileData { // // /** // * Holds information how many times basic block has been called. Indexes are the ones returned by addBasicBlock(). // */ // public static long[] callsToBasicBlock; // private static int basicBlockAmount = 0; // /** // * How costly a basic block is. Naive way to count it is by assuming every bytecodes cost is 1 and multiply by // * amount of bytecodes in the basic block. // */ // public static long[] basicBlockCost; // private static List<Long> basicBlockCostAccumulator = new ArrayList<Long>(); // private static List<String> basicBlockDesc = new ArrayList<String>(); // private static Map<String, Integer> methodStarterBlockMap = new HashMap<String, Integer>(); // // private static boolean profilingEnabled = false; // // /** // * Adds basic block with default cost (1). // * // * @return Index of basic block in arrays. // */ // public static int addBasicBlock() { // return addBasicBlock(1L); // } // // /** // * Adds a new basic block. // * // * @param cost Cost of the basic block. // * @return Index of the basic block in the arrays. // */ // public static int addBasicBlock(long cost) { // return addBasicBlock(cost, "", false); // } // // /** // * Adds a new basic block with a description. // * // * @param cost Cost of the basic block. // * @param desc Description of the basic block. // * @return Index of the basic block in the arrays. // */ // public static synchronized int addBasicBlock(long cost, String desc, boolean starter) { // basicBlockAmount++; // basicBlockCostAccumulator.add(cost); // basicBlockDesc.add(desc == null ? "" : desc); // if (starter) { // methodStarterBlockMap.put(desc, basicBlockAmount - 1); // } // return basicBlockAmount - 1; // } // // public static void incrementCallsToBasicBlock(int index) { // if (profilingEnabled) { // callsToBasicBlock[index] += 1; // } // } // // /** // * Reset callsToBasicBlock arrays elements to 0. // */ // public static synchronized void resetCounters() { // if (callsToBasicBlock == null) { // initialize(); // } // for (int i = 0; i < callsToBasicBlock.length; i++) { // callsToBasicBlock[i] = 0L; // } // } // // /** // * Initialize arrays from added basic blocks. Needs to be called before using the arrays. // */ // public static synchronized void initialize() { // long[] newCallsToBasicBlock = new long[basicBlockAmount]; // if (callsToBasicBlock != null) { // System.arraycopy(callsToBasicBlock, 0, newCallsToBasicBlock, 0, callsToBasicBlock.length); // } // callsToBasicBlock = newCallsToBasicBlock; // // basicBlockCost = new long[basicBlockCostAccumulator.size()]; // for (int i = 0; i < basicBlockCostAccumulator.size(); i++) { // basicBlockCost[i] = basicBlockCostAccumulator.get(i); // } // } // // public static long[] getCallsToBasicBlock() { // return callsToBasicBlock; // } // // public static int getBasicBlockAmount() { // return basicBlockAmount; // } // // public static long[] getBasicBlockCost() { // return basicBlockCost; // } // // public static List<String> getBasicBlockDesc() { // return basicBlockDesc; // } // // // /** // * Are counter increments allowed. // * // * @return // */ // public static boolean isProfilingEnabled() { // return profilingEnabled; // } // // /** // * Disallow counter increments. // */ // public static void disableProfiling() { // profilingEnabled = false; // } // // /** // * Allow counter increments. // */ // public static void enableProfiling() { // profilingEnabled = true; // } // // public static Map<String, Integer> getMethodStarterBlockMap() { // return methodStarterBlockMap; // } // } // // Path: ProfileData/src/main/java/net/jproffa/profiledata/ThreadBlocker.java // public final class ThreadBlocker { // // ThreadBlockerTransformer in the main project injects Thread // // with code that calls {checkStartingThreadAllowed(). // // private ThreadBlocker() { // } // // public static interface Policy { // public boolean isAllowedToStart(Thread thread); // } // // private static final List<Policy> policies = new ArrayList<Policy>(); // // public static synchronized void addPolicy(Policy cb) { // policies.add(cb); // } // // public static synchronized void removePolicy(Policy cb) { // policies.remove(cb); // } // // public static synchronized boolean isStartingThreadAllowed(Thread thread) { // for (Policy cb : policies) { // if (!cb.isAllowedToStart(thread)) { // return false; // } // } // return true; // } // // public static void checkStartingThreadAllowed(Thread thread) { // if (!isStartingThreadAllowed(thread)) { // throw new IllegalStateException("Starting thread " + thread.getName() + " denied due to profiling."); // } // } // }
import net.jproffa.profiledata.ProfileData; import net.jproffa.profiledata.ThreadBlocker;
package net.jproffa.profiler; public class DefaultThreadBlockerPolicy implements ThreadBlocker.Policy { @Override public boolean isAllowedToStart(Thread thread) {
// Path: ProfileData/src/main/java/net/jproffa/profiledata/ProfileData.java // public class ProfileData { // // /** // * Holds information how many times basic block has been called. Indexes are the ones returned by addBasicBlock(). // */ // public static long[] callsToBasicBlock; // private static int basicBlockAmount = 0; // /** // * How costly a basic block is. Naive way to count it is by assuming every bytecodes cost is 1 and multiply by // * amount of bytecodes in the basic block. // */ // public static long[] basicBlockCost; // private static List<Long> basicBlockCostAccumulator = new ArrayList<Long>(); // private static List<String> basicBlockDesc = new ArrayList<String>(); // private static Map<String, Integer> methodStarterBlockMap = new HashMap<String, Integer>(); // // private static boolean profilingEnabled = false; // // /** // * Adds basic block with default cost (1). // * // * @return Index of basic block in arrays. // */ // public static int addBasicBlock() { // return addBasicBlock(1L); // } // // /** // * Adds a new basic block. // * // * @param cost Cost of the basic block. // * @return Index of the basic block in the arrays. // */ // public static int addBasicBlock(long cost) { // return addBasicBlock(cost, "", false); // } // // /** // * Adds a new basic block with a description. // * // * @param cost Cost of the basic block. // * @param desc Description of the basic block. // * @return Index of the basic block in the arrays. // */ // public static synchronized int addBasicBlock(long cost, String desc, boolean starter) { // basicBlockAmount++; // basicBlockCostAccumulator.add(cost); // basicBlockDesc.add(desc == null ? "" : desc); // if (starter) { // methodStarterBlockMap.put(desc, basicBlockAmount - 1); // } // return basicBlockAmount - 1; // } // // public static void incrementCallsToBasicBlock(int index) { // if (profilingEnabled) { // callsToBasicBlock[index] += 1; // } // } // // /** // * Reset callsToBasicBlock arrays elements to 0. // */ // public static synchronized void resetCounters() { // if (callsToBasicBlock == null) { // initialize(); // } // for (int i = 0; i < callsToBasicBlock.length; i++) { // callsToBasicBlock[i] = 0L; // } // } // // /** // * Initialize arrays from added basic blocks. Needs to be called before using the arrays. // */ // public static synchronized void initialize() { // long[] newCallsToBasicBlock = new long[basicBlockAmount]; // if (callsToBasicBlock != null) { // System.arraycopy(callsToBasicBlock, 0, newCallsToBasicBlock, 0, callsToBasicBlock.length); // } // callsToBasicBlock = newCallsToBasicBlock; // // basicBlockCost = new long[basicBlockCostAccumulator.size()]; // for (int i = 0; i < basicBlockCostAccumulator.size(); i++) { // basicBlockCost[i] = basicBlockCostAccumulator.get(i); // } // } // // public static long[] getCallsToBasicBlock() { // return callsToBasicBlock; // } // // public static int getBasicBlockAmount() { // return basicBlockAmount; // } // // public static long[] getBasicBlockCost() { // return basicBlockCost; // } // // public static List<String> getBasicBlockDesc() { // return basicBlockDesc; // } // // // /** // * Are counter increments allowed. // * // * @return // */ // public static boolean isProfilingEnabled() { // return profilingEnabled; // } // // /** // * Disallow counter increments. // */ // public static void disableProfiling() { // profilingEnabled = false; // } // // /** // * Allow counter increments. // */ // public static void enableProfiling() { // profilingEnabled = true; // } // // public static Map<String, Integer> getMethodStarterBlockMap() { // return methodStarterBlockMap; // } // } // // Path: ProfileData/src/main/java/net/jproffa/profiledata/ThreadBlocker.java // public final class ThreadBlocker { // // ThreadBlockerTransformer in the main project injects Thread // // with code that calls {checkStartingThreadAllowed(). // // private ThreadBlocker() { // } // // public static interface Policy { // public boolean isAllowedToStart(Thread thread); // } // // private static final List<Policy> policies = new ArrayList<Policy>(); // // public static synchronized void addPolicy(Policy cb) { // policies.add(cb); // } // // public static synchronized void removePolicy(Policy cb) { // policies.remove(cb); // } // // public static synchronized boolean isStartingThreadAllowed(Thread thread) { // for (Policy cb : policies) { // if (!cb.isAllowedToStart(thread)) { // return false; // } // } // return true; // } // // public static void checkStartingThreadAllowed(Thread thread) { // if (!isStartingThreadAllowed(thread)) { // throw new IllegalStateException("Starting thread " + thread.getName() + " denied due to profiling."); // } // } // } // Path: Profiler/src/main/java/net/jproffa/profiler/DefaultThreadBlockerPolicy.java import net.jproffa.profiledata.ProfileData; import net.jproffa.profiledata.ThreadBlocker; package net.jproffa.profiler; public class DefaultThreadBlockerPolicy implements ThreadBlocker.Policy { @Override public boolean isAllowedToStart(Thread thread) {
return !ProfileData.isProfilingEnabled() || !Thread.currentThread().getName().equals("main");
JProffa/JProffa
Profiler/src/main/java/net/jproffa/profiler/Util.java
// Path: ProfileData/src/main/java/net/jproffa/profiledata/ProfileData.java // public class ProfileData { // // /** // * Holds information how many times basic block has been called. Indexes are the ones returned by addBasicBlock(). // */ // public static long[] callsToBasicBlock; // private static int basicBlockAmount = 0; // /** // * How costly a basic block is. Naive way to count it is by assuming every bytecodes cost is 1 and multiply by // * amount of bytecodes in the basic block. // */ // public static long[] basicBlockCost; // private static List<Long> basicBlockCostAccumulator = new ArrayList<Long>(); // private static List<String> basicBlockDesc = new ArrayList<String>(); // private static Map<String, Integer> methodStarterBlockMap = new HashMap<String, Integer>(); // // private static boolean profilingEnabled = false; // // /** // * Adds basic block with default cost (1). // * // * @return Index of basic block in arrays. // */ // public static int addBasicBlock() { // return addBasicBlock(1L); // } // // /** // * Adds a new basic block. // * // * @param cost Cost of the basic block. // * @return Index of the basic block in the arrays. // */ // public static int addBasicBlock(long cost) { // return addBasicBlock(cost, "", false); // } // // /** // * Adds a new basic block with a description. // * // * @param cost Cost of the basic block. // * @param desc Description of the basic block. // * @return Index of the basic block in the arrays. // */ // public static synchronized int addBasicBlock(long cost, String desc, boolean starter) { // basicBlockAmount++; // basicBlockCostAccumulator.add(cost); // basicBlockDesc.add(desc == null ? "" : desc); // if (starter) { // methodStarterBlockMap.put(desc, basicBlockAmount - 1); // } // return basicBlockAmount - 1; // } // // public static void incrementCallsToBasicBlock(int index) { // if (profilingEnabled) { // callsToBasicBlock[index] += 1; // } // } // // /** // * Reset callsToBasicBlock arrays elements to 0. // */ // public static synchronized void resetCounters() { // if (callsToBasicBlock == null) { // initialize(); // } // for (int i = 0; i < callsToBasicBlock.length; i++) { // callsToBasicBlock[i] = 0L; // } // } // // /** // * Initialize arrays from added basic blocks. Needs to be called before using the arrays. // */ // public static synchronized void initialize() { // long[] newCallsToBasicBlock = new long[basicBlockAmount]; // if (callsToBasicBlock != null) { // System.arraycopy(callsToBasicBlock, 0, newCallsToBasicBlock, 0, callsToBasicBlock.length); // } // callsToBasicBlock = newCallsToBasicBlock; // // basicBlockCost = new long[basicBlockCostAccumulator.size()]; // for (int i = 0; i < basicBlockCostAccumulator.size(); i++) { // basicBlockCost[i] = basicBlockCostAccumulator.get(i); // } // } // // public static long[] getCallsToBasicBlock() { // return callsToBasicBlock; // } // // public static int getBasicBlockAmount() { // return basicBlockAmount; // } // // public static long[] getBasicBlockCost() { // return basicBlockCost; // } // // public static List<String> getBasicBlockDesc() { // return basicBlockDesc; // } // // // /** // * Are counter increments allowed. // * // * @return // */ // public static boolean isProfilingEnabled() { // return profilingEnabled; // } // // /** // * Disallow counter increments. // */ // public static void disableProfiling() { // profilingEnabled = false; // } // // /** // * Allow counter increments. // */ // public static void enableProfiling() { // profilingEnabled = true; // } // // public static Map<String, Integer> getMethodStarterBlockMap() { // return methodStarterBlockMap; // } // }
import com.sun.tools.attach.VirtualMachine; import net.jproffa.profiledata.ProfileData; import org.apache.log4j.Logger; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.Label; import static org.objectweb.asm.Opcodes.*; import org.objectweb.asm.tree.*; import java.io.*; import java.lang.management.ManagementFactory; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.TreeMap; import org.objectweb.asm.Type; import java.util.Map.Entry; import static org.objectweb.asm.tree.AbstractInsnNode.*;
*/ public static void loadAgent() { if (agentLoaded) { return; } String nameOfRunningVM = ManagementFactory.getRuntimeMXBean().getName(); String pid = nameOfRunningVM.substring(0, nameOfRunningVM.indexOf('@')); // System.out.println("VM pid: " + pid); try { VirtualMachine vm = VirtualMachine.attach(pid); File jarFile = new File(Util.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()); String profilerJarPath = jarFile.getPath(); vm.loadAgent(profilerJarPath); agentLoaded = true; vm.detach(); } catch (NoClassDefFoundError e) { throw new RuntimeException("NoClassDefFoundError thrown: tools.jar probably not loaded.", e); } catch (Exception e) { throw new RuntimeException(e); } } /** * Gets total cost. This is counted by multiplying the amount of calls to a basic block by its cost and adding them * together. * * @return Total cost of execution. */ public static long getTotalCost() { checkAgentIsLoaded();
// Path: ProfileData/src/main/java/net/jproffa/profiledata/ProfileData.java // public class ProfileData { // // /** // * Holds information how many times basic block has been called. Indexes are the ones returned by addBasicBlock(). // */ // public static long[] callsToBasicBlock; // private static int basicBlockAmount = 0; // /** // * How costly a basic block is. Naive way to count it is by assuming every bytecodes cost is 1 and multiply by // * amount of bytecodes in the basic block. // */ // public static long[] basicBlockCost; // private static List<Long> basicBlockCostAccumulator = new ArrayList<Long>(); // private static List<String> basicBlockDesc = new ArrayList<String>(); // private static Map<String, Integer> methodStarterBlockMap = new HashMap<String, Integer>(); // // private static boolean profilingEnabled = false; // // /** // * Adds basic block with default cost (1). // * // * @return Index of basic block in arrays. // */ // public static int addBasicBlock() { // return addBasicBlock(1L); // } // // /** // * Adds a new basic block. // * // * @param cost Cost of the basic block. // * @return Index of the basic block in the arrays. // */ // public static int addBasicBlock(long cost) { // return addBasicBlock(cost, "", false); // } // // /** // * Adds a new basic block with a description. // * // * @param cost Cost of the basic block. // * @param desc Description of the basic block. // * @return Index of the basic block in the arrays. // */ // public static synchronized int addBasicBlock(long cost, String desc, boolean starter) { // basicBlockAmount++; // basicBlockCostAccumulator.add(cost); // basicBlockDesc.add(desc == null ? "" : desc); // if (starter) { // methodStarterBlockMap.put(desc, basicBlockAmount - 1); // } // return basicBlockAmount - 1; // } // // public static void incrementCallsToBasicBlock(int index) { // if (profilingEnabled) { // callsToBasicBlock[index] += 1; // } // } // // /** // * Reset callsToBasicBlock arrays elements to 0. // */ // public static synchronized void resetCounters() { // if (callsToBasicBlock == null) { // initialize(); // } // for (int i = 0; i < callsToBasicBlock.length; i++) { // callsToBasicBlock[i] = 0L; // } // } // // /** // * Initialize arrays from added basic blocks. Needs to be called before using the arrays. // */ // public static synchronized void initialize() { // long[] newCallsToBasicBlock = new long[basicBlockAmount]; // if (callsToBasicBlock != null) { // System.arraycopy(callsToBasicBlock, 0, newCallsToBasicBlock, 0, callsToBasicBlock.length); // } // callsToBasicBlock = newCallsToBasicBlock; // // basicBlockCost = new long[basicBlockCostAccumulator.size()]; // for (int i = 0; i < basicBlockCostAccumulator.size(); i++) { // basicBlockCost[i] = basicBlockCostAccumulator.get(i); // } // } // // public static long[] getCallsToBasicBlock() { // return callsToBasicBlock; // } // // public static int getBasicBlockAmount() { // return basicBlockAmount; // } // // public static long[] getBasicBlockCost() { // return basicBlockCost; // } // // public static List<String> getBasicBlockDesc() { // return basicBlockDesc; // } // // // /** // * Are counter increments allowed. // * // * @return // */ // public static boolean isProfilingEnabled() { // return profilingEnabled; // } // // /** // * Disallow counter increments. // */ // public static void disableProfiling() { // profilingEnabled = false; // } // // /** // * Allow counter increments. // */ // public static void enableProfiling() { // profilingEnabled = true; // } // // public static Map<String, Integer> getMethodStarterBlockMap() { // return methodStarterBlockMap; // } // } // Path: Profiler/src/main/java/net/jproffa/profiler/Util.java import com.sun.tools.attach.VirtualMachine; import net.jproffa.profiledata.ProfileData; import org.apache.log4j.Logger; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.Label; import static org.objectweb.asm.Opcodes.*; import org.objectweb.asm.tree.*; import java.io.*; import java.lang.management.ManagementFactory; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.TreeMap; import org.objectweb.asm.Type; import java.util.Map.Entry; import static org.objectweb.asm.tree.AbstractInsnNode.*; */ public static void loadAgent() { if (agentLoaded) { return; } String nameOfRunningVM = ManagementFactory.getRuntimeMXBean().getName(); String pid = nameOfRunningVM.substring(0, nameOfRunningVM.indexOf('@')); // System.out.println("VM pid: " + pid); try { VirtualMachine vm = VirtualMachine.attach(pid); File jarFile = new File(Util.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()); String profilerJarPath = jarFile.getPath(); vm.loadAgent(profilerJarPath); agentLoaded = true; vm.detach(); } catch (NoClassDefFoundError e) { throw new RuntimeException("NoClassDefFoundError thrown: tools.jar probably not loaded.", e); } catch (Exception e) { throw new RuntimeException(e); } } /** * Gets total cost. This is counted by multiplying the amount of calls to a basic block by its cost and adding them * together. * * @return Total cost of execution. */ public static long getTotalCost() { checkAgentIsLoaded();
long[] callsToBasicBlock = ProfileData.getCallsToBasicBlock();
JProffa/JProffa
TestProject/src/test/java/net/jproffa/test/ComplexityQuadraticTest.java
// Path: TestProject/src/test/java/net/jproffa/implementations/IntegerImpl.java // public class IntegerImpl extends AbstractImpl implements Benchmarkable<Integer> { // // @Override // public Integer getInput(int size) { // return size; // } // // @Override // public int getSize(Integer input) { // return input; // } // // @Override // public Output<Integer> runMethod(List<Integer> list) throws Exception { // runStatic(1); // // Output<Integer> out = new Output<Integer>(); // for (Integer i : list) { // out.addToInput(i); // out.addToSize(getSize(i)); // out.addToTime(runStatic(i)); // } // // return out; // } // // public Output<Integer> runMethod(List<Integer> list, List<Integer> list2) throws Exception { // runStatic(1, 0); // // Output<Integer> out = new Output<Integer>(); // // for (int i = 0; i < list.size(); i++) { // out.addToInput(list.get(i)); // out.addToSize(list.get(i)); // out.addToTime(runStatic(list.get(i), list2.get(i))); // } // // return out; // } // // public Output<Integer> runMethod(List<Integer> list, List<Integer> list2, List<Integer> list3) throws Exception { // runStatic(1, 0, 0); // // Output<Integer> out = new Output<Integer>(); // // for (int i = 0; i < list.size(); i++) { // out.addToInput(list.get(i)); // out.addToSize(list.get(i)); // out.addToTime(runStatic(list.get(i), list2.get(i), list3.get(i))); // } // // return out; // } // } // // Path: Profiler/src/main/java/net/jproffa/profiler/WithProfiling.java // public final class WithProfiling implements TestRule { // private final boolean shouldEnableProfiling; // // private WithProfiling(boolean shouldEnableProfiling) { // this.shouldEnableProfiling = shouldEnableProfiling; // } // // public static void in(Runnable inner) { // Util.loadAgent(); // ProfileData.resetCounters(); // ProfileData.enableProfiling(); // try { // inner.run(); // } finally { // ProfileData.disableProfiling(); // } // } // // public static void in(RunnableEx inner) throws Exception { // Util.loadAgent(); // ProfileData.resetCounters(); // ProfileData.enableProfiling(); // try { // inner.run(); // } finally { // ProfileData.disableProfiling(); // } // } // // public static <V> V in(Callable<V> inner) throws Exception { // Util.loadAgent(); // ProfileData.resetCounters(); // ProfileData.enableProfiling(); // try { // return inner.call(); // } finally { // ProfileData.disableProfiling(); // } // } // // /** // * Returns a JUnit rule that sets up and enables profiling before each test. // */ // public static WithProfiling rule() { // return new WithProfiling(true); // } // // /** // * Returns a JUnit rule that sets up and optionally enables profiling before each test. // * // * <p> // * If {@code enableProfiling} is false, it only ensures the profiler is initialized // * but disables profiling before each test. The test may use // * {@code WithProfiling.in(...)} to profile things itself. // * Note that you should need this rarely as the rule blacklists the test class // * anyway, so code in it does not count towards the profiling score. // */ // public static WithProfiling rule(boolean enableProfiling) { // return new WithProfiling(enableProfiling); // } // // @Override // public Statement apply(final Statement base, final Description description) { // return new Statement() { // @Override // public void evaluate() throws Throwable { // Util.loadAgent(); // ClassBlacklist.add(description.getTestClass()); // ProfileData.resetCounters(); // if (shouldEnableProfiling) { // ProfileData.enableProfiling(); // } else { // ProfileData.disableProfiling(); // } // try { // base.evaluate(); // } finally { // ProfileData.disableProfiling(); // } // } // }; // } // }
import net.jproffa.implementations.IntegerImpl; import net.jproffa.profiler.WithProfiling; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertTrue; import org.junit.Rule;
package net.jproffa.test; public class ComplexityQuadraticTest { @Rule public WithProfiling profiling = WithProfiling.rule();
// Path: TestProject/src/test/java/net/jproffa/implementations/IntegerImpl.java // public class IntegerImpl extends AbstractImpl implements Benchmarkable<Integer> { // // @Override // public Integer getInput(int size) { // return size; // } // // @Override // public int getSize(Integer input) { // return input; // } // // @Override // public Output<Integer> runMethod(List<Integer> list) throws Exception { // runStatic(1); // // Output<Integer> out = new Output<Integer>(); // for (Integer i : list) { // out.addToInput(i); // out.addToSize(getSize(i)); // out.addToTime(runStatic(i)); // } // // return out; // } // // public Output<Integer> runMethod(List<Integer> list, List<Integer> list2) throws Exception { // runStatic(1, 0); // // Output<Integer> out = new Output<Integer>(); // // for (int i = 0; i < list.size(); i++) { // out.addToInput(list.get(i)); // out.addToSize(list.get(i)); // out.addToTime(runStatic(list.get(i), list2.get(i))); // } // // return out; // } // // public Output<Integer> runMethod(List<Integer> list, List<Integer> list2, List<Integer> list3) throws Exception { // runStatic(1, 0, 0); // // Output<Integer> out = new Output<Integer>(); // // for (int i = 0; i < list.size(); i++) { // out.addToInput(list.get(i)); // out.addToSize(list.get(i)); // out.addToTime(runStatic(list.get(i), list2.get(i), list3.get(i))); // } // // return out; // } // } // // Path: Profiler/src/main/java/net/jproffa/profiler/WithProfiling.java // public final class WithProfiling implements TestRule { // private final boolean shouldEnableProfiling; // // private WithProfiling(boolean shouldEnableProfiling) { // this.shouldEnableProfiling = shouldEnableProfiling; // } // // public static void in(Runnable inner) { // Util.loadAgent(); // ProfileData.resetCounters(); // ProfileData.enableProfiling(); // try { // inner.run(); // } finally { // ProfileData.disableProfiling(); // } // } // // public static void in(RunnableEx inner) throws Exception { // Util.loadAgent(); // ProfileData.resetCounters(); // ProfileData.enableProfiling(); // try { // inner.run(); // } finally { // ProfileData.disableProfiling(); // } // } // // public static <V> V in(Callable<V> inner) throws Exception { // Util.loadAgent(); // ProfileData.resetCounters(); // ProfileData.enableProfiling(); // try { // return inner.call(); // } finally { // ProfileData.disableProfiling(); // } // } // // /** // * Returns a JUnit rule that sets up and enables profiling before each test. // */ // public static WithProfiling rule() { // return new WithProfiling(true); // } // // /** // * Returns a JUnit rule that sets up and optionally enables profiling before each test. // * // * <p> // * If {@code enableProfiling} is false, it only ensures the profiler is initialized // * but disables profiling before each test. The test may use // * {@code WithProfiling.in(...)} to profile things itself. // * Note that you should need this rarely as the rule blacklists the test class // * anyway, so code in it does not count towards the profiling score. // */ // public static WithProfiling rule(boolean enableProfiling) { // return new WithProfiling(enableProfiling); // } // // @Override // public Statement apply(final Statement base, final Description description) { // return new Statement() { // @Override // public void evaluate() throws Throwable { // Util.loadAgent(); // ClassBlacklist.add(description.getTestClass()); // ProfileData.resetCounters(); // if (shouldEnableProfiling) { // ProfileData.enableProfiling(); // } else { // ProfileData.disableProfiling(); // } // try { // base.evaluate(); // } finally { // ProfileData.disableProfiling(); // } // } // }; // } // } // Path: TestProject/src/test/java/net/jproffa/test/ComplexityQuadraticTest.java import net.jproffa.implementations.IntegerImpl; import net.jproffa.profiler.WithProfiling; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertTrue; import org.junit.Rule; package net.jproffa.test; public class ComplexityQuadraticTest { @Rule public WithProfiling profiling = WithProfiling.rule();
private IntegerImpl impl;
JProffa/JProffa
Profiler/src/main/java/net/jproffa/profiler/WithProfiling.java
// Path: ProfileData/src/main/java/net/jproffa/profiledata/ProfileData.java // public class ProfileData { // // /** // * Holds information how many times basic block has been called. Indexes are the ones returned by addBasicBlock(). // */ // public static long[] callsToBasicBlock; // private static int basicBlockAmount = 0; // /** // * How costly a basic block is. Naive way to count it is by assuming every bytecodes cost is 1 and multiply by // * amount of bytecodes in the basic block. // */ // public static long[] basicBlockCost; // private static List<Long> basicBlockCostAccumulator = new ArrayList<Long>(); // private static List<String> basicBlockDesc = new ArrayList<String>(); // private static Map<String, Integer> methodStarterBlockMap = new HashMap<String, Integer>(); // // private static boolean profilingEnabled = false; // // /** // * Adds basic block with default cost (1). // * // * @return Index of basic block in arrays. // */ // public static int addBasicBlock() { // return addBasicBlock(1L); // } // // /** // * Adds a new basic block. // * // * @param cost Cost of the basic block. // * @return Index of the basic block in the arrays. // */ // public static int addBasicBlock(long cost) { // return addBasicBlock(cost, "", false); // } // // /** // * Adds a new basic block with a description. // * // * @param cost Cost of the basic block. // * @param desc Description of the basic block. // * @return Index of the basic block in the arrays. // */ // public static synchronized int addBasicBlock(long cost, String desc, boolean starter) { // basicBlockAmount++; // basicBlockCostAccumulator.add(cost); // basicBlockDesc.add(desc == null ? "" : desc); // if (starter) { // methodStarterBlockMap.put(desc, basicBlockAmount - 1); // } // return basicBlockAmount - 1; // } // // public static void incrementCallsToBasicBlock(int index) { // if (profilingEnabled) { // callsToBasicBlock[index] += 1; // } // } // // /** // * Reset callsToBasicBlock arrays elements to 0. // */ // public static synchronized void resetCounters() { // if (callsToBasicBlock == null) { // initialize(); // } // for (int i = 0; i < callsToBasicBlock.length; i++) { // callsToBasicBlock[i] = 0L; // } // } // // /** // * Initialize arrays from added basic blocks. Needs to be called before using the arrays. // */ // public static synchronized void initialize() { // long[] newCallsToBasicBlock = new long[basicBlockAmount]; // if (callsToBasicBlock != null) { // System.arraycopy(callsToBasicBlock, 0, newCallsToBasicBlock, 0, callsToBasicBlock.length); // } // callsToBasicBlock = newCallsToBasicBlock; // // basicBlockCost = new long[basicBlockCostAccumulator.size()]; // for (int i = 0; i < basicBlockCostAccumulator.size(); i++) { // basicBlockCost[i] = basicBlockCostAccumulator.get(i); // } // } // // public static long[] getCallsToBasicBlock() { // return callsToBasicBlock; // } // // public static int getBasicBlockAmount() { // return basicBlockAmount; // } // // public static long[] getBasicBlockCost() { // return basicBlockCost; // } // // public static List<String> getBasicBlockDesc() { // return basicBlockDesc; // } // // // /** // * Are counter increments allowed. // * // * @return // */ // public static boolean isProfilingEnabled() { // return profilingEnabled; // } // // /** // * Disallow counter increments. // */ // public static void disableProfiling() { // profilingEnabled = false; // } // // /** // * Allow counter increments. // */ // public static void enableProfiling() { // profilingEnabled = true; // } // // public static Map<String, Integer> getMethodStarterBlockMap() { // return methodStarterBlockMap; // } // }
import net.jproffa.profiledata.ProfileData; import java.util.concurrent.Callable; import org.junit.rules.TestRule; import org.junit.runner.Description; import org.junit.runners.model.Statement;
package net.jproffa.profiler; /** * Enables profiling for a piece of code or a test. * * <p> * More specifically it ensures the agent is loaded, * resets counters before the block and disables profiling * after the block test. * * <p> * It can be used as a JUnit rule, which causes it to additionally * blacklist the test class at hand. */ public final class WithProfiling implements TestRule { private final boolean shouldEnableProfiling; private WithProfiling(boolean shouldEnableProfiling) { this.shouldEnableProfiling = shouldEnableProfiling; } public static void in(Runnable inner) { Util.loadAgent();
// Path: ProfileData/src/main/java/net/jproffa/profiledata/ProfileData.java // public class ProfileData { // // /** // * Holds information how many times basic block has been called. Indexes are the ones returned by addBasicBlock(). // */ // public static long[] callsToBasicBlock; // private static int basicBlockAmount = 0; // /** // * How costly a basic block is. Naive way to count it is by assuming every bytecodes cost is 1 and multiply by // * amount of bytecodes in the basic block. // */ // public static long[] basicBlockCost; // private static List<Long> basicBlockCostAccumulator = new ArrayList<Long>(); // private static List<String> basicBlockDesc = new ArrayList<String>(); // private static Map<String, Integer> methodStarterBlockMap = new HashMap<String, Integer>(); // // private static boolean profilingEnabled = false; // // /** // * Adds basic block with default cost (1). // * // * @return Index of basic block in arrays. // */ // public static int addBasicBlock() { // return addBasicBlock(1L); // } // // /** // * Adds a new basic block. // * // * @param cost Cost of the basic block. // * @return Index of the basic block in the arrays. // */ // public static int addBasicBlock(long cost) { // return addBasicBlock(cost, "", false); // } // // /** // * Adds a new basic block with a description. // * // * @param cost Cost of the basic block. // * @param desc Description of the basic block. // * @return Index of the basic block in the arrays. // */ // public static synchronized int addBasicBlock(long cost, String desc, boolean starter) { // basicBlockAmount++; // basicBlockCostAccumulator.add(cost); // basicBlockDesc.add(desc == null ? "" : desc); // if (starter) { // methodStarterBlockMap.put(desc, basicBlockAmount - 1); // } // return basicBlockAmount - 1; // } // // public static void incrementCallsToBasicBlock(int index) { // if (profilingEnabled) { // callsToBasicBlock[index] += 1; // } // } // // /** // * Reset callsToBasicBlock arrays elements to 0. // */ // public static synchronized void resetCounters() { // if (callsToBasicBlock == null) { // initialize(); // } // for (int i = 0; i < callsToBasicBlock.length; i++) { // callsToBasicBlock[i] = 0L; // } // } // // /** // * Initialize arrays from added basic blocks. Needs to be called before using the arrays. // */ // public static synchronized void initialize() { // long[] newCallsToBasicBlock = new long[basicBlockAmount]; // if (callsToBasicBlock != null) { // System.arraycopy(callsToBasicBlock, 0, newCallsToBasicBlock, 0, callsToBasicBlock.length); // } // callsToBasicBlock = newCallsToBasicBlock; // // basicBlockCost = new long[basicBlockCostAccumulator.size()]; // for (int i = 0; i < basicBlockCostAccumulator.size(); i++) { // basicBlockCost[i] = basicBlockCostAccumulator.get(i); // } // } // // public static long[] getCallsToBasicBlock() { // return callsToBasicBlock; // } // // public static int getBasicBlockAmount() { // return basicBlockAmount; // } // // public static long[] getBasicBlockCost() { // return basicBlockCost; // } // // public static List<String> getBasicBlockDesc() { // return basicBlockDesc; // } // // // /** // * Are counter increments allowed. // * // * @return // */ // public static boolean isProfilingEnabled() { // return profilingEnabled; // } // // /** // * Disallow counter increments. // */ // public static void disableProfiling() { // profilingEnabled = false; // } // // /** // * Allow counter increments. // */ // public static void enableProfiling() { // profilingEnabled = true; // } // // public static Map<String, Integer> getMethodStarterBlockMap() { // return methodStarterBlockMap; // } // } // Path: Profiler/src/main/java/net/jproffa/profiler/WithProfiling.java import net.jproffa.profiledata.ProfileData; import java.util.concurrent.Callable; import org.junit.rules.TestRule; import org.junit.runner.Description; import org.junit.runners.model.Statement; package net.jproffa.profiler; /** * Enables profiling for a piece of code or a test. * * <p> * More specifically it ensures the agent is loaded, * resets counters before the block and disables profiling * after the block test. * * <p> * It can be used as a JUnit rule, which causes it to additionally * blacklist the test class at hand. */ public final class WithProfiling implements TestRule { private final boolean shouldEnableProfiling; private WithProfiling(boolean shouldEnableProfiling) { this.shouldEnableProfiling = shouldEnableProfiling; } public static void in(Runnable inner) { Util.loadAgent();
ProfileData.resetCounters();
JProffa/JProffa
Profiler/src/test/java/net/jproffa/profiler/OutputTest.java
// Path: Profiler/src/main/java/net/jproffa/profiler/Output.java // public class Output<T> { // // private List<T> input; // private List<Integer> size; // private List<Long> time; // // public Output() { // input = new ArrayList<T>(); // size = new ArrayList<Integer>(); // time = new ArrayList<Long>(); // } // // public List<T> getInput() { // return input; // } // // public void setInput(List<T> input) { // this.input = input; // } // // public List<Integer> getSize() { // return size; // } // // public void setSize(List<Integer> size) { // this.size = size; // } // // public List<Long> getTime() { // return time; // } // // public void setTime(List<Long> time) { // this.time = time; // } // // public void addToInput(T object) { // input.add(object); // } // // public void addToTime(long t) { // time.add(t); // } // // public void addToSize(int i) { // size.add(i); // } // // public int entryCount() { // return size.size(); // } // // @Override // public String toString() { // if (input.isEmpty()) { // return "<empty Output>"; // } // if (input.size() != size.size() || size.size() != time.size()) { // return "<invalid Output>"; // } // // String[][] rows = new String[][] { // new String[input.size()], // new String[size.size()], // new String[time.size()] // }; // int n = entryCount(); // for (int col = 0; col < n; ++col) { // rows[0][col] = input.get(col).toString(); // rows[1][col] = size.get(col).toString(); // rows[2][col] = time.get(col).toString(); // } // // return formatTable(rows); // } // // private String formatTable(String[][] rows) { // StringBuilder sb = new StringBuilder(); // int[] colWidths = getColWidths(rows); // // for (int i = 0; i < rows.length; ++i) { // String[] row = rows[i]; // // sb.append("| "); // for (int j = 0; j < row.length; ++j) { // if (j > 0) { // sb.append(" | "); // } // // int colWidth = colWidths[j]; // int padding = colWidth - row[j].length(); // for (int p = 0; p < padding; ++p) { // sb.append(' '); // } // sb.append(row[j]); // } // sb.append(" |").append("\n"); // } // return sb.toString(); // } // // private int[] getColWidths(String[][] rows) { // int[] colWidths = new int[entryCount()]; // for (int j = 0; j < entryCount(); ++j) { // int w = 0; // for (int i = 0; i < rows.length; ++i) { // w = Math.max(w, rows[i][j].length()); // } // colWidths[j] = w; // } // return colWidths; // } // // }
import net.jproffa.profiler.Output; import org.junit.Test; import static org.junit.Assert.*;
package net.jproffa.profiler; public class OutputTest { @Test public void testEmptyToString() {
// Path: Profiler/src/main/java/net/jproffa/profiler/Output.java // public class Output<T> { // // private List<T> input; // private List<Integer> size; // private List<Long> time; // // public Output() { // input = new ArrayList<T>(); // size = new ArrayList<Integer>(); // time = new ArrayList<Long>(); // } // // public List<T> getInput() { // return input; // } // // public void setInput(List<T> input) { // this.input = input; // } // // public List<Integer> getSize() { // return size; // } // // public void setSize(List<Integer> size) { // this.size = size; // } // // public List<Long> getTime() { // return time; // } // // public void setTime(List<Long> time) { // this.time = time; // } // // public void addToInput(T object) { // input.add(object); // } // // public void addToTime(long t) { // time.add(t); // } // // public void addToSize(int i) { // size.add(i); // } // // public int entryCount() { // return size.size(); // } // // @Override // public String toString() { // if (input.isEmpty()) { // return "<empty Output>"; // } // if (input.size() != size.size() || size.size() != time.size()) { // return "<invalid Output>"; // } // // String[][] rows = new String[][] { // new String[input.size()], // new String[size.size()], // new String[time.size()] // }; // int n = entryCount(); // for (int col = 0; col < n; ++col) { // rows[0][col] = input.get(col).toString(); // rows[1][col] = size.get(col).toString(); // rows[2][col] = time.get(col).toString(); // } // // return formatTable(rows); // } // // private String formatTable(String[][] rows) { // StringBuilder sb = new StringBuilder(); // int[] colWidths = getColWidths(rows); // // for (int i = 0; i < rows.length; ++i) { // String[] row = rows[i]; // // sb.append("| "); // for (int j = 0; j < row.length; ++j) { // if (j > 0) { // sb.append(" | "); // } // // int colWidth = colWidths[j]; // int padding = colWidth - row[j].length(); // for (int p = 0; p < padding; ++p) { // sb.append(' '); // } // sb.append(row[j]); // } // sb.append(" |").append("\n"); // } // return sb.toString(); // } // // private int[] getColWidths(String[][] rows) { // int[] colWidths = new int[entryCount()]; // for (int j = 0; j < entryCount(); ++j) { // int w = 0; // for (int i = 0; i < rows.length; ++i) { // w = Math.max(w, rows[i][j].length()); // } // colWidths[j] = w; // } // return colWidths; // } // // } // Path: Profiler/src/test/java/net/jproffa/profiler/OutputTest.java import net.jproffa.profiler.Output; import org.junit.Test; import static org.junit.Assert.*; package net.jproffa.profiler; public class OutputTest { @Test public void testEmptyToString() {
Output<String> o = new Output<String>();
JProffa/JProffa
TestProject/src/test/java/net/jproffa/test/PreventingThreadCreationTest.java
// Path: Profiler/src/main/java/net/jproffa/profiler/WithProfiling.java // public final class WithProfiling implements TestRule { // private final boolean shouldEnableProfiling; // // private WithProfiling(boolean shouldEnableProfiling) { // this.shouldEnableProfiling = shouldEnableProfiling; // } // // public static void in(Runnable inner) { // Util.loadAgent(); // ProfileData.resetCounters(); // ProfileData.enableProfiling(); // try { // inner.run(); // } finally { // ProfileData.disableProfiling(); // } // } // // public static void in(RunnableEx inner) throws Exception { // Util.loadAgent(); // ProfileData.resetCounters(); // ProfileData.enableProfiling(); // try { // inner.run(); // } finally { // ProfileData.disableProfiling(); // } // } // // public static <V> V in(Callable<V> inner) throws Exception { // Util.loadAgent(); // ProfileData.resetCounters(); // ProfileData.enableProfiling(); // try { // return inner.call(); // } finally { // ProfileData.disableProfiling(); // } // } // // /** // * Returns a JUnit rule that sets up and enables profiling before each test. // */ // public static WithProfiling rule() { // return new WithProfiling(true); // } // // /** // * Returns a JUnit rule that sets up and optionally enables profiling before each test. // * // * <p> // * If {@code enableProfiling} is false, it only ensures the profiler is initialized // * but disables profiling before each test. The test may use // * {@code WithProfiling.in(...)} to profile things itself. // * Note that you should need this rarely as the rule blacklists the test class // * anyway, so code in it does not count towards the profiling score. // */ // public static WithProfiling rule(boolean enableProfiling) { // return new WithProfiling(enableProfiling); // } // // @Override // public Statement apply(final Statement base, final Description description) { // return new Statement() { // @Override // public void evaluate() throws Throwable { // Util.loadAgent(); // ClassBlacklist.add(description.getTestClass()); // ProfileData.resetCounters(); // if (shouldEnableProfiling) { // ProfileData.enableProfiling(); // } else { // ProfileData.disableProfiling(); // } // try { // base.evaluate(); // } finally { // ProfileData.disableProfiling(); // } // } // }; // } // } // // Path: TestProject/src/main/java/net/jproffa/testproject/ThreadCreation.java // public class ThreadCreation { // public static void createThreadAndStart() { // Thread t = new Thread(); // t.start(); // System.out.println("You should never see me!"); // } // }
import net.jproffa.profiler.WithProfiling; import net.jproffa.testproject.ThreadCreation; import org.junit.Test; import static org.junit.Assert.fail; import org.junit.Rule;
package net.jproffa.test; public class PreventingThreadCreationTest { @Rule public WithProfiling profiling = WithProfiling.rule(); @Test public void threadCreateTest() { try { WithProfiling.in(new Runnable() { @Override public void run() {
// Path: Profiler/src/main/java/net/jproffa/profiler/WithProfiling.java // public final class WithProfiling implements TestRule { // private final boolean shouldEnableProfiling; // // private WithProfiling(boolean shouldEnableProfiling) { // this.shouldEnableProfiling = shouldEnableProfiling; // } // // public static void in(Runnable inner) { // Util.loadAgent(); // ProfileData.resetCounters(); // ProfileData.enableProfiling(); // try { // inner.run(); // } finally { // ProfileData.disableProfiling(); // } // } // // public static void in(RunnableEx inner) throws Exception { // Util.loadAgent(); // ProfileData.resetCounters(); // ProfileData.enableProfiling(); // try { // inner.run(); // } finally { // ProfileData.disableProfiling(); // } // } // // public static <V> V in(Callable<V> inner) throws Exception { // Util.loadAgent(); // ProfileData.resetCounters(); // ProfileData.enableProfiling(); // try { // return inner.call(); // } finally { // ProfileData.disableProfiling(); // } // } // // /** // * Returns a JUnit rule that sets up and enables profiling before each test. // */ // public static WithProfiling rule() { // return new WithProfiling(true); // } // // /** // * Returns a JUnit rule that sets up and optionally enables profiling before each test. // * // * <p> // * If {@code enableProfiling} is false, it only ensures the profiler is initialized // * but disables profiling before each test. The test may use // * {@code WithProfiling.in(...)} to profile things itself. // * Note that you should need this rarely as the rule blacklists the test class // * anyway, so code in it does not count towards the profiling score. // */ // public static WithProfiling rule(boolean enableProfiling) { // return new WithProfiling(enableProfiling); // } // // @Override // public Statement apply(final Statement base, final Description description) { // return new Statement() { // @Override // public void evaluate() throws Throwable { // Util.loadAgent(); // ClassBlacklist.add(description.getTestClass()); // ProfileData.resetCounters(); // if (shouldEnableProfiling) { // ProfileData.enableProfiling(); // } else { // ProfileData.disableProfiling(); // } // try { // base.evaluate(); // } finally { // ProfileData.disableProfiling(); // } // } // }; // } // } // // Path: TestProject/src/main/java/net/jproffa/testproject/ThreadCreation.java // public class ThreadCreation { // public static void createThreadAndStart() { // Thread t = new Thread(); // t.start(); // System.out.println("You should never see me!"); // } // } // Path: TestProject/src/test/java/net/jproffa/test/PreventingThreadCreationTest.java import net.jproffa.profiler.WithProfiling; import net.jproffa.testproject.ThreadCreation; import org.junit.Test; import static org.junit.Assert.fail; import org.junit.Rule; package net.jproffa.test; public class PreventingThreadCreationTest { @Rule public WithProfiling profiling = WithProfiling.rule(); @Test public void threadCreateTest() { try { WithProfiling.in(new Runnable() { @Override public void run() {
ThreadCreation.createThreadAndStart();
JProffa/JProffa
Profiler/src/main/java/net/jproffa/profiler/ThreadBlockerTransformer.java
// Path: ProfileData/src/main/java/net/jproffa/profiledata/ThreadBlocker.java // public final class ThreadBlocker { // // ThreadBlockerTransformer in the main project injects Thread // // with code that calls {checkStartingThreadAllowed(). // // private ThreadBlocker() { // } // // public static interface Policy { // public boolean isAllowedToStart(Thread thread); // } // // private static final List<Policy> policies = new ArrayList<Policy>(); // // public static synchronized void addPolicy(Policy cb) { // policies.add(cb); // } // // public static synchronized void removePolicy(Policy cb) { // policies.remove(cb); // } // // public static synchronized boolean isStartingThreadAllowed(Thread thread) { // for (Policy cb : policies) { // if (!cb.isAllowedToStart(thread)) { // return false; // } // } // return true; // } // // public static void checkStartingThreadAllowed(Thread thread) { // if (!isStartingThreadAllowed(thread)) { // throw new IllegalStateException("Starting thread " + thread.getName() + " denied due to profiling."); // } // } // }
import net.jproffa.profiledata.ThreadBlocker; import java.lang.instrument.ClassFileTransformer; import java.lang.instrument.IllegalClassFormatException; import java.security.ProtectionDomain; import java.util.List; import org.apache.log4j.Logger; import org.objectweb.asm.tree.*; import static org.objectweb.asm.Opcodes.*;
public byte[] transform( ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException { try { if (!className.equals("java/lang/Thread")) { return null; } ClassNode thread = Util.initClassNode(classfileBuffer); InsnList insns = getInstructions(); for (MethodNode methodNode : (List<MethodNode>) thread.methods) { if (!methodNode.name.equals("start")) { continue; } methodNode.instructions.insert(insns); } Thread.currentThread().getStackTrace(); return Util.generateBytecode(thread); } catch (Throwable t) { logger.fatal("Exception while transforming", t); } return null; } private InsnList getInstructions() { InsnList insnList = new InsnList();
// Path: ProfileData/src/main/java/net/jproffa/profiledata/ThreadBlocker.java // public final class ThreadBlocker { // // ThreadBlockerTransformer in the main project injects Thread // // with code that calls {checkStartingThreadAllowed(). // // private ThreadBlocker() { // } // // public static interface Policy { // public boolean isAllowedToStart(Thread thread); // } // // private static final List<Policy> policies = new ArrayList<Policy>(); // // public static synchronized void addPolicy(Policy cb) { // policies.add(cb); // } // // public static synchronized void removePolicy(Policy cb) { // policies.remove(cb); // } // // public static synchronized boolean isStartingThreadAllowed(Thread thread) { // for (Policy cb : policies) { // if (!cb.isAllowedToStart(thread)) { // return false; // } // } // return true; // } // // public static void checkStartingThreadAllowed(Thread thread) { // if (!isStartingThreadAllowed(thread)) { // throw new IllegalStateException("Starting thread " + thread.getName() + " denied due to profiling."); // } // } // } // Path: Profiler/src/main/java/net/jproffa/profiler/ThreadBlockerTransformer.java import net.jproffa.profiledata.ThreadBlocker; import java.lang.instrument.ClassFileTransformer; import java.lang.instrument.IllegalClassFormatException; import java.security.ProtectionDomain; import java.util.List; import org.apache.log4j.Logger; import org.objectweb.asm.tree.*; import static org.objectweb.asm.Opcodes.*; public byte[] transform( ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException { try { if (!className.equals("java/lang/Thread")) { return null; } ClassNode thread = Util.initClassNode(classfileBuffer); InsnList insns = getInstructions(); for (MethodNode methodNode : (List<MethodNode>) thread.methods) { if (!methodNode.name.equals("start")) { continue; } methodNode.instructions.insert(insns); } Thread.currentThread().getStackTrace(); return Util.generateBytecode(thread); } catch (Throwable t) { logger.fatal("Exception while transforming", t); } return null; } private InsnList getInstructions() { InsnList insnList = new InsnList();
String className = ThreadBlocker.class.getName().replace('.', '/');
JProffa/JProffa
Profiler/src/main/java/net/jproffa/profiler/AbstractImpl.java
// Path: ProfileData/src/main/java/net/jproffa/profiledata/ProfileData.java // public class ProfileData { // // /** // * Holds information how many times basic block has been called. Indexes are the ones returned by addBasicBlock(). // */ // public static long[] callsToBasicBlock; // private static int basicBlockAmount = 0; // /** // * How costly a basic block is. Naive way to count it is by assuming every bytecodes cost is 1 and multiply by // * amount of bytecodes in the basic block. // */ // public static long[] basicBlockCost; // private static List<Long> basicBlockCostAccumulator = new ArrayList<Long>(); // private static List<String> basicBlockDesc = new ArrayList<String>(); // private static Map<String, Integer> methodStarterBlockMap = new HashMap<String, Integer>(); // // private static boolean profilingEnabled = false; // // /** // * Adds basic block with default cost (1). // * // * @return Index of basic block in arrays. // */ // public static int addBasicBlock() { // return addBasicBlock(1L); // } // // /** // * Adds a new basic block. // * // * @param cost Cost of the basic block. // * @return Index of the basic block in the arrays. // */ // public static int addBasicBlock(long cost) { // return addBasicBlock(cost, "", false); // } // // /** // * Adds a new basic block with a description. // * // * @param cost Cost of the basic block. // * @param desc Description of the basic block. // * @return Index of the basic block in the arrays. // */ // public static synchronized int addBasicBlock(long cost, String desc, boolean starter) { // basicBlockAmount++; // basicBlockCostAccumulator.add(cost); // basicBlockDesc.add(desc == null ? "" : desc); // if (starter) { // methodStarterBlockMap.put(desc, basicBlockAmount - 1); // } // return basicBlockAmount - 1; // } // // public static void incrementCallsToBasicBlock(int index) { // if (profilingEnabled) { // callsToBasicBlock[index] += 1; // } // } // // /** // * Reset callsToBasicBlock arrays elements to 0. // */ // public static synchronized void resetCounters() { // if (callsToBasicBlock == null) { // initialize(); // } // for (int i = 0; i < callsToBasicBlock.length; i++) { // callsToBasicBlock[i] = 0L; // } // } // // /** // * Initialize arrays from added basic blocks. Needs to be called before using the arrays. // */ // public static synchronized void initialize() { // long[] newCallsToBasicBlock = new long[basicBlockAmount]; // if (callsToBasicBlock != null) { // System.arraycopy(callsToBasicBlock, 0, newCallsToBasicBlock, 0, callsToBasicBlock.length); // } // callsToBasicBlock = newCallsToBasicBlock; // // basicBlockCost = new long[basicBlockCostAccumulator.size()]; // for (int i = 0; i < basicBlockCostAccumulator.size(); i++) { // basicBlockCost[i] = basicBlockCostAccumulator.get(i); // } // } // // public static long[] getCallsToBasicBlock() { // return callsToBasicBlock; // } // // public static int getBasicBlockAmount() { // return basicBlockAmount; // } // // public static long[] getBasicBlockCost() { // return basicBlockCost; // } // // public static List<String> getBasicBlockDesc() { // return basicBlockDesc; // } // // // /** // * Are counter increments allowed. // * // * @return // */ // public static boolean isProfilingEnabled() { // return profilingEnabled; // } // // /** // * Disallow counter increments. // */ // public static void disableProfiling() { // profilingEnabled = false; // } // // /** // * Allow counter increments. // */ // public static void enableProfiling() { // profilingEnabled = true; // } // // public static Map<String, Integer> getMethodStarterBlockMap() { // return methodStarterBlockMap; // } // }
import net.jproffa.profiledata.ProfileData; import org.apache.log4j.Logger; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Arrays;
for (int i = 0; i < parameterTypes.length; i++) { if (!changeToPrimitive(parameterTypes[i]).equals(changeToPrimitive(methodParameterTypes[i]))) { continue outer; } } return method; } throw new NoSuchMethodException("Method with name " + methodName + " and suitable parameters not found from " + className); } /** * Run static method with given inputs. * * @param inputs Input variables. Primitive boxing classes (Integer, Boolean, etc.) must not be nulls. * @return Total cost * @throws Exception */ public long runStaticOnce(Object... inputs) throws Exception { return runOnce(null, inputs); } /** * Run method of given instance with given inputs. * * @param instance Instance of the class which we are testing. * @param inputs Input variables. Primitive boxing classes (Integer, Boolean, etc.) must not be nulls. * @return Total cost * @throws Exception */ public long runOnce(final Object instance, final Object... inputs) throws Exception {
// Path: ProfileData/src/main/java/net/jproffa/profiledata/ProfileData.java // public class ProfileData { // // /** // * Holds information how many times basic block has been called. Indexes are the ones returned by addBasicBlock(). // */ // public static long[] callsToBasicBlock; // private static int basicBlockAmount = 0; // /** // * How costly a basic block is. Naive way to count it is by assuming every bytecodes cost is 1 and multiply by // * amount of bytecodes in the basic block. // */ // public static long[] basicBlockCost; // private static List<Long> basicBlockCostAccumulator = new ArrayList<Long>(); // private static List<String> basicBlockDesc = new ArrayList<String>(); // private static Map<String, Integer> methodStarterBlockMap = new HashMap<String, Integer>(); // // private static boolean profilingEnabled = false; // // /** // * Adds basic block with default cost (1). // * // * @return Index of basic block in arrays. // */ // public static int addBasicBlock() { // return addBasicBlock(1L); // } // // /** // * Adds a new basic block. // * // * @param cost Cost of the basic block. // * @return Index of the basic block in the arrays. // */ // public static int addBasicBlock(long cost) { // return addBasicBlock(cost, "", false); // } // // /** // * Adds a new basic block with a description. // * // * @param cost Cost of the basic block. // * @param desc Description of the basic block. // * @return Index of the basic block in the arrays. // */ // public static synchronized int addBasicBlock(long cost, String desc, boolean starter) { // basicBlockAmount++; // basicBlockCostAccumulator.add(cost); // basicBlockDesc.add(desc == null ? "" : desc); // if (starter) { // methodStarterBlockMap.put(desc, basicBlockAmount - 1); // } // return basicBlockAmount - 1; // } // // public static void incrementCallsToBasicBlock(int index) { // if (profilingEnabled) { // callsToBasicBlock[index] += 1; // } // } // // /** // * Reset callsToBasicBlock arrays elements to 0. // */ // public static synchronized void resetCounters() { // if (callsToBasicBlock == null) { // initialize(); // } // for (int i = 0; i < callsToBasicBlock.length; i++) { // callsToBasicBlock[i] = 0L; // } // } // // /** // * Initialize arrays from added basic blocks. Needs to be called before using the arrays. // */ // public static synchronized void initialize() { // long[] newCallsToBasicBlock = new long[basicBlockAmount]; // if (callsToBasicBlock != null) { // System.arraycopy(callsToBasicBlock, 0, newCallsToBasicBlock, 0, callsToBasicBlock.length); // } // callsToBasicBlock = newCallsToBasicBlock; // // basicBlockCost = new long[basicBlockCostAccumulator.size()]; // for (int i = 0; i < basicBlockCostAccumulator.size(); i++) { // basicBlockCost[i] = basicBlockCostAccumulator.get(i); // } // } // // public static long[] getCallsToBasicBlock() { // return callsToBasicBlock; // } // // public static int getBasicBlockAmount() { // return basicBlockAmount; // } // // public static long[] getBasicBlockCost() { // return basicBlockCost; // } // // public static List<String> getBasicBlockDesc() { // return basicBlockDesc; // } // // // /** // * Are counter increments allowed. // * // * @return // */ // public static boolean isProfilingEnabled() { // return profilingEnabled; // } // // /** // * Disallow counter increments. // */ // public static void disableProfiling() { // profilingEnabled = false; // } // // /** // * Allow counter increments. // */ // public static void enableProfiling() { // profilingEnabled = true; // } // // public static Map<String, Integer> getMethodStarterBlockMap() { // return methodStarterBlockMap; // } // } // Path: Profiler/src/main/java/net/jproffa/profiler/AbstractImpl.java import net.jproffa.profiledata.ProfileData; import org.apache.log4j.Logger; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Arrays; for (int i = 0; i < parameterTypes.length; i++) { if (!changeToPrimitive(parameterTypes[i]).equals(changeToPrimitive(methodParameterTypes[i]))) { continue outer; } } return method; } throw new NoSuchMethodException("Method with name " + methodName + " and suitable parameters not found from " + className); } /** * Run static method with given inputs. * * @param inputs Input variables. Primitive boxing classes (Integer, Boolean, etc.) must not be nulls. * @return Total cost * @throws Exception */ public long runStaticOnce(Object... inputs) throws Exception { return runOnce(null, inputs); } /** * Run method of given instance with given inputs. * * @param instance Instance of the class which we are testing. * @param inputs Input variables. Primitive boxing classes (Integer, Boolean, etc.) must not be nulls. * @return Total cost * @throws Exception */ public long runOnce(final Object instance, final Object... inputs) throws Exception {
ProfileData.disableProfiling();
JProffa/JProffa
Graph/src/main/java/net/jproffa/graph/Line.java
// Path: Profiler/src/main/java/net/jproffa/profiler/Output.java // public class Output<T> { // // private List<T> input; // private List<Integer> size; // private List<Long> time; // // public Output() { // input = new ArrayList<T>(); // size = new ArrayList<Integer>(); // time = new ArrayList<Long>(); // } // // public List<T> getInput() { // return input; // } // // public void setInput(List<T> input) { // this.input = input; // } // // public List<Integer> getSize() { // return size; // } // // public void setSize(List<Integer> size) { // this.size = size; // } // // public List<Long> getTime() { // return time; // } // // public void setTime(List<Long> time) { // this.time = time; // } // // public void addToInput(T object) { // input.add(object); // } // // public void addToTime(long t) { // time.add(t); // } // // public void addToSize(int i) { // size.add(i); // } // // public int entryCount() { // return size.size(); // } // // @Override // public String toString() { // if (input.isEmpty()) { // return "<empty Output>"; // } // if (input.size() != size.size() || size.size() != time.size()) { // return "<invalid Output>"; // } // // String[][] rows = new String[][] { // new String[input.size()], // new String[size.size()], // new String[time.size()] // }; // int n = entryCount(); // for (int col = 0; col < n; ++col) { // rows[0][col] = input.get(col).toString(); // rows[1][col] = size.get(col).toString(); // rows[2][col] = time.get(col).toString(); // } // // return formatTable(rows); // } // // private String formatTable(String[][] rows) { // StringBuilder sb = new StringBuilder(); // int[] colWidths = getColWidths(rows); // // for (int i = 0; i < rows.length; ++i) { // String[] row = rows[i]; // // sb.append("| "); // for (int j = 0; j < row.length; ++j) { // if (j > 0) { // sb.append(" | "); // } // // int colWidth = colWidths[j]; // int padding = colWidth - row[j].length(); // for (int p = 0; p < padding; ++p) { // sb.append(' '); // } // sb.append(row[j]); // } // sb.append(" |").append("\n"); // } // return sb.toString(); // } // // private int[] getColWidths(String[][] rows) { // int[] colWidths = new int[entryCount()]; // for (int j = 0; j < entryCount(); ++j) { // int w = 0; // for (int i = 0; i < rows.length; ++i) { // w = Math.max(w, rows[i][j].length()); // } // colWidths[j] = w; // } // return colWidths; // } // // }
import java.util.List; import net.jproffa.profiler.Output;
package net.jproffa.graph; public class Line { public List<Long> time; public List<Integer> input; public String className; public String methodName; /** * Additional description optionally specified by the test writer. * * The annotation may be null. There may be multiple lines with the same annotation. */ public String annotation;
// Path: Profiler/src/main/java/net/jproffa/profiler/Output.java // public class Output<T> { // // private List<T> input; // private List<Integer> size; // private List<Long> time; // // public Output() { // input = new ArrayList<T>(); // size = new ArrayList<Integer>(); // time = new ArrayList<Long>(); // } // // public List<T> getInput() { // return input; // } // // public void setInput(List<T> input) { // this.input = input; // } // // public List<Integer> getSize() { // return size; // } // // public void setSize(List<Integer> size) { // this.size = size; // } // // public List<Long> getTime() { // return time; // } // // public void setTime(List<Long> time) { // this.time = time; // } // // public void addToInput(T object) { // input.add(object); // } // // public void addToTime(long t) { // time.add(t); // } // // public void addToSize(int i) { // size.add(i); // } // // public int entryCount() { // return size.size(); // } // // @Override // public String toString() { // if (input.isEmpty()) { // return "<empty Output>"; // } // if (input.size() != size.size() || size.size() != time.size()) { // return "<invalid Output>"; // } // // String[][] rows = new String[][] { // new String[input.size()], // new String[size.size()], // new String[time.size()] // }; // int n = entryCount(); // for (int col = 0; col < n; ++col) { // rows[0][col] = input.get(col).toString(); // rows[1][col] = size.get(col).toString(); // rows[2][col] = time.get(col).toString(); // } // // return formatTable(rows); // } // // private String formatTable(String[][] rows) { // StringBuilder sb = new StringBuilder(); // int[] colWidths = getColWidths(rows); // // for (int i = 0; i < rows.length; ++i) { // String[] row = rows[i]; // // sb.append("| "); // for (int j = 0; j < row.length; ++j) { // if (j > 0) { // sb.append(" | "); // } // // int colWidth = colWidths[j]; // int padding = colWidth - row[j].length(); // for (int p = 0; p < padding; ++p) { // sb.append(' '); // } // sb.append(row[j]); // } // sb.append(" |").append("\n"); // } // return sb.toString(); // } // // private int[] getColWidths(String[][] rows) { // int[] colWidths = new int[entryCount()]; // for (int j = 0; j < entryCount(); ++j) { // int w = 0; // for (int i = 0; i < rows.length; ++i) { // w = Math.max(w, rows[i][j].length()); // } // colWidths[j] = w; // } // return colWidths; // } // // } // Path: Graph/src/main/java/net/jproffa/graph/Line.java import java.util.List; import net.jproffa.profiler.Output; package net.jproffa.graph; public class Line { public List<Long> time; public List<Integer> input; public String className; public String methodName; /** * Additional description optionally specified by the test writer. * * The annotation may be null. There may be multiple lines with the same annotation. */ public String annotation;
public Line(Output<?> output, String className, String methodName, String annotation) {
JProffa/JProffa
Graph/src/main/java/net/jproffa/graph/GraphRenderer.java
// Path: Profiler/src/main/java/net/jproffa/profiler/Output.java // public class Output<T> { // // private List<T> input; // private List<Integer> size; // private List<Long> time; // // public Output() { // input = new ArrayList<T>(); // size = new ArrayList<Integer>(); // time = new ArrayList<Long>(); // } // // public List<T> getInput() { // return input; // } // // public void setInput(List<T> input) { // this.input = input; // } // // public List<Integer> getSize() { // return size; // } // // public void setSize(List<Integer> size) { // this.size = size; // } // // public List<Long> getTime() { // return time; // } // // public void setTime(List<Long> time) { // this.time = time; // } // // public void addToInput(T object) { // input.add(object); // } // // public void addToTime(long t) { // time.add(t); // } // // public void addToSize(int i) { // size.add(i); // } // // public int entryCount() { // return size.size(); // } // // @Override // public String toString() { // if (input.isEmpty()) { // return "<empty Output>"; // } // if (input.size() != size.size() || size.size() != time.size()) { // return "<invalid Output>"; // } // // String[][] rows = new String[][] { // new String[input.size()], // new String[size.size()], // new String[time.size()] // }; // int n = entryCount(); // for (int col = 0; col < n; ++col) { // rows[0][col] = input.get(col).toString(); // rows[1][col] = size.get(col).toString(); // rows[2][col] = time.get(col).toString(); // } // // return formatTable(rows); // } // // private String formatTable(String[][] rows) { // StringBuilder sb = new StringBuilder(); // int[] colWidths = getColWidths(rows); // // for (int i = 0; i < rows.length; ++i) { // String[] row = rows[i]; // // sb.append("| "); // for (int j = 0; j < row.length; ++j) { // if (j > 0) { // sb.append(" | "); // } // // int colWidth = colWidths[j]; // int padding = colWidth - row[j].length(); // for (int p = 0; p < padding; ++p) { // sb.append(' '); // } // sb.append(row[j]); // } // sb.append(" |").append("\n"); // } // return sb.toString(); // } // // private int[] getColWidths(String[][] rows) { // int[] colWidths = new int[entryCount()]; // for (int j = 0; j < entryCount(); ++j) { // int w = 0; // for (int i = 0; i < rows.length; ++i) { // w = Math.max(w, rows[i][j].length()); // } // colWidths[j] = w; // } // return colWidths; // } // // }
import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart; import org.jfree.chart.axis.NumberAxis; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer; import org.jfree.data.xy.XYDataset; import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection; import javax.swing.*; import java.awt.*; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.Semaphore; import net.jproffa.profiler.Output; import org.apache.commons.math3.analysis.UnivariateFunction; import org.jfree.chart.plot.Plot; import org.jfree.data.general.Dataset;
package net.jproffa.graph; public class GraphRenderer { private final JFreeChart chart; public GraphRenderer(List<Line> lines) { final XYDataset dataset = createDataset(lines); chart = createChart(dataset); } //TODO: generalize the convenience overloads of showAndWait public static void showAndWait( String className, String methodName,
// Path: Profiler/src/main/java/net/jproffa/profiler/Output.java // public class Output<T> { // // private List<T> input; // private List<Integer> size; // private List<Long> time; // // public Output() { // input = new ArrayList<T>(); // size = new ArrayList<Integer>(); // time = new ArrayList<Long>(); // } // // public List<T> getInput() { // return input; // } // // public void setInput(List<T> input) { // this.input = input; // } // // public List<Integer> getSize() { // return size; // } // // public void setSize(List<Integer> size) { // this.size = size; // } // // public List<Long> getTime() { // return time; // } // // public void setTime(List<Long> time) { // this.time = time; // } // // public void addToInput(T object) { // input.add(object); // } // // public void addToTime(long t) { // time.add(t); // } // // public void addToSize(int i) { // size.add(i); // } // // public int entryCount() { // return size.size(); // } // // @Override // public String toString() { // if (input.isEmpty()) { // return "<empty Output>"; // } // if (input.size() != size.size() || size.size() != time.size()) { // return "<invalid Output>"; // } // // String[][] rows = new String[][] { // new String[input.size()], // new String[size.size()], // new String[time.size()] // }; // int n = entryCount(); // for (int col = 0; col < n; ++col) { // rows[0][col] = input.get(col).toString(); // rows[1][col] = size.get(col).toString(); // rows[2][col] = time.get(col).toString(); // } // // return formatTable(rows); // } // // private String formatTable(String[][] rows) { // StringBuilder sb = new StringBuilder(); // int[] colWidths = getColWidths(rows); // // for (int i = 0; i < rows.length; ++i) { // String[] row = rows[i]; // // sb.append("| "); // for (int j = 0; j < row.length; ++j) { // if (j > 0) { // sb.append(" | "); // } // // int colWidth = colWidths[j]; // int padding = colWidth - row[j].length(); // for (int p = 0; p < padding; ++p) { // sb.append(' '); // } // sb.append(row[j]); // } // sb.append(" |").append("\n"); // } // return sb.toString(); // } // // private int[] getColWidths(String[][] rows) { // int[] colWidths = new int[entryCount()]; // for (int j = 0; j < entryCount(); ++j) { // int w = 0; // for (int i = 0; i < rows.length; ++i) { // w = Math.max(w, rows[i][j].length()); // } // colWidths[j] = w; // } // return colWidths; // } // // } // Path: Graph/src/main/java/net/jproffa/graph/GraphRenderer.java import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart; import org.jfree.chart.axis.NumberAxis; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer; import org.jfree.data.xy.XYDataset; import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection; import javax.swing.*; import java.awt.*; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.Semaphore; import net.jproffa.profiler.Output; import org.apache.commons.math3.analysis.UnivariateFunction; import org.jfree.chart.plot.Plot; import org.jfree.data.general.Dataset; package net.jproffa.graph; public class GraphRenderer { private final JFreeChart chart; public GraphRenderer(List<Line> lines) { final XYDataset dataset = createDataset(lines); chart = createChart(dataset); } //TODO: generalize the convenience overloads of showAndWait public static void showAndWait( String className, String methodName,
Output<?> output,
JProffa/JProffa
Graph/src/main/java/net/jproffa/graph/GraphWriter.java
// Path: Profiler/src/main/java/net/jproffa/profiler/Output.java // public class Output<T> { // // private List<T> input; // private List<Integer> size; // private List<Long> time; // // public Output() { // input = new ArrayList<T>(); // size = new ArrayList<Integer>(); // time = new ArrayList<Long>(); // } // // public List<T> getInput() { // return input; // } // // public void setInput(List<T> input) { // this.input = input; // } // // public List<Integer> getSize() { // return size; // } // // public void setSize(List<Integer> size) { // this.size = size; // } // // public List<Long> getTime() { // return time; // } // // public void setTime(List<Long> time) { // this.time = time; // } // // public void addToInput(T object) { // input.add(object); // } // // public void addToTime(long t) { // time.add(t); // } // // public void addToSize(int i) { // size.add(i); // } // // public int entryCount() { // return size.size(); // } // // @Override // public String toString() { // if (input.isEmpty()) { // return "<empty Output>"; // } // if (input.size() != size.size() || size.size() != time.size()) { // return "<invalid Output>"; // } // // String[][] rows = new String[][] { // new String[input.size()], // new String[size.size()], // new String[time.size()] // }; // int n = entryCount(); // for (int col = 0; col < n; ++col) { // rows[0][col] = input.get(col).toString(); // rows[1][col] = size.get(col).toString(); // rows[2][col] = time.get(col).toString(); // } // // return formatTable(rows); // } // // private String formatTable(String[][] rows) { // StringBuilder sb = new StringBuilder(); // int[] colWidths = getColWidths(rows); // // for (int i = 0; i < rows.length; ++i) { // String[] row = rows[i]; // // sb.append("| "); // for (int j = 0; j < row.length; ++j) { // if (j > 0) { // sb.append(" | "); // } // // int colWidth = colWidths[j]; // int padding = colWidth - row[j].length(); // for (int p = 0; p < padding; ++p) { // sb.append(' '); // } // sb.append(row[j]); // } // sb.append(" |").append("\n"); // } // return sb.toString(); // } // // private int[] getColWidths(String[][] rows) { // int[] colWidths = new int[entryCount()]; // for (int j = 0; j < entryCount(); ++j) { // int w = 0; // for (int i = 0; i < rows.length; ++i) { // w = Math.max(w, rows[i][j].length()); // } // colWidths[j] = w; // } // return colWidths; // } // // }
import com.google.gson.Gson; import org.junit.rules.TestRule; import org.junit.runner.Description; import org.junit.runners.model.Statement; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.List; import net.jproffa.profiler.Output;
* GraphRenderer renderer = new GraphRenderer(list); * JPanel panel = renderer.getJPanel(); } </pre> * @param time List of times * @param input List of inputs */ public void save(List<Long> time, List<Integer> input) throws IOException { File file = getFile(); FileWriter fstream = new FileWriter(file, true); BufferedWriter fbw = new BufferedWriter(fstream); Gson gson = new Gson(); String data = gson.toJson(new Line(time, input, className, methodName, annotation)); fbw.write(data); fbw.newLine(); fbw.close(); } /** * Saves the output objects time and size lists to file. This data can be read using GraphReader. <p> * Example: * <pre> {@code @Rule * GraphWriter gw = new GraphWriter(); * Output out = ...; * gw.save(out); * GraphReader gr = new GraphReader("path/to/directory"); * List<Line> lines = gr.get("some.TestClass", "testFoo"); * GraphRenderer renderer = new GraphRenderer(list); * JPanel panel = renderer.getJPanel(); } </pre> * @param out The output object containing non-empty list of times and list of sizes. * @throws IOException */
// Path: Profiler/src/main/java/net/jproffa/profiler/Output.java // public class Output<T> { // // private List<T> input; // private List<Integer> size; // private List<Long> time; // // public Output() { // input = new ArrayList<T>(); // size = new ArrayList<Integer>(); // time = new ArrayList<Long>(); // } // // public List<T> getInput() { // return input; // } // // public void setInput(List<T> input) { // this.input = input; // } // // public List<Integer> getSize() { // return size; // } // // public void setSize(List<Integer> size) { // this.size = size; // } // // public List<Long> getTime() { // return time; // } // // public void setTime(List<Long> time) { // this.time = time; // } // // public void addToInput(T object) { // input.add(object); // } // // public void addToTime(long t) { // time.add(t); // } // // public void addToSize(int i) { // size.add(i); // } // // public int entryCount() { // return size.size(); // } // // @Override // public String toString() { // if (input.isEmpty()) { // return "<empty Output>"; // } // if (input.size() != size.size() || size.size() != time.size()) { // return "<invalid Output>"; // } // // String[][] rows = new String[][] { // new String[input.size()], // new String[size.size()], // new String[time.size()] // }; // int n = entryCount(); // for (int col = 0; col < n; ++col) { // rows[0][col] = input.get(col).toString(); // rows[1][col] = size.get(col).toString(); // rows[2][col] = time.get(col).toString(); // } // // return formatTable(rows); // } // // private String formatTable(String[][] rows) { // StringBuilder sb = new StringBuilder(); // int[] colWidths = getColWidths(rows); // // for (int i = 0; i < rows.length; ++i) { // String[] row = rows[i]; // // sb.append("| "); // for (int j = 0; j < row.length; ++j) { // if (j > 0) { // sb.append(" | "); // } // // int colWidth = colWidths[j]; // int padding = colWidth - row[j].length(); // for (int p = 0; p < padding; ++p) { // sb.append(' '); // } // sb.append(row[j]); // } // sb.append(" |").append("\n"); // } // return sb.toString(); // } // // private int[] getColWidths(String[][] rows) { // int[] colWidths = new int[entryCount()]; // for (int j = 0; j < entryCount(); ++j) { // int w = 0; // for (int i = 0; i < rows.length; ++i) { // w = Math.max(w, rows[i][j].length()); // } // colWidths[j] = w; // } // return colWidths; // } // // } // Path: Graph/src/main/java/net/jproffa/graph/GraphWriter.java import com.google.gson.Gson; import org.junit.rules.TestRule; import org.junit.runner.Description; import org.junit.runners.model.Statement; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.List; import net.jproffa.profiler.Output; * GraphRenderer renderer = new GraphRenderer(list); * JPanel panel = renderer.getJPanel(); } </pre> * @param time List of times * @param input List of inputs */ public void save(List<Long> time, List<Integer> input) throws IOException { File file = getFile(); FileWriter fstream = new FileWriter(file, true); BufferedWriter fbw = new BufferedWriter(fstream); Gson gson = new Gson(); String data = gson.toJson(new Line(time, input, className, methodName, annotation)); fbw.write(data); fbw.newLine(); fbw.close(); } /** * Saves the output objects time and size lists to file. This data can be read using GraphReader. <p> * Example: * <pre> {@code @Rule * GraphWriter gw = new GraphWriter(); * Output out = ...; * gw.save(out); * GraphReader gr = new GraphReader("path/to/directory"); * List<Line> lines = gr.get("some.TestClass", "testFoo"); * GraphRenderer renderer = new GraphRenderer(list); * JPanel panel = renderer.getJPanel(); } </pre> * @param out The output object containing non-empty list of times and list of sizes. * @throws IOException */
public void save(Output<?> out) throws IOException {
chibash/stone
src/stone/ast/ASTLeaf.java
// Path: src/stone/Token.java // public abstract class Token { // public static final Token EOF = new Token(-1){}; // end of file // public static final String EOL = "\\n"; // end of line // private int lineNumber; // // protected Token(int line) { // lineNumber = line; // } // public int getLineNumber() { return lineNumber; } // public boolean isIdentifier() { return false; } // public boolean isNumber() { return false; } // public boolean isString() { return false; } // public int getNumber() { throw new StoneException("not number token"); } // public String getText() { return ""; } // }
import java.util.Iterator; import java.util.ArrayList; import stone.Token;
package stone.ast; public class ASTLeaf extends ASTree { private static ArrayList<ASTree> empty = new ArrayList<ASTree>();
// Path: src/stone/Token.java // public abstract class Token { // public static final Token EOF = new Token(-1){}; // end of file // public static final String EOL = "\\n"; // end of line // private int lineNumber; // // protected Token(int line) { // lineNumber = line; // } // public int getLineNumber() { return lineNumber; } // public boolean isIdentifier() { return false; } // public boolean isNumber() { return false; } // public boolean isString() { return false; } // public int getNumber() { throw new StoneException("not number token"); } // public String getText() { return ""; } // } // Path: src/stone/ast/ASTLeaf.java import java.util.Iterator; import java.util.ArrayList; import stone.Token; package stone.ast; public class ASTLeaf extends ASTree { private static ArrayList<ASTree> empty = new ArrayList<ASTree>();
protected Token token;
chibash/stone
src/chap13/Opcode.java
// Path: src/stone/StoneException.java // public class StoneException extends RuntimeException { // public StoneException(String m) { super(m); } // public StoneException(String m, ASTree t) { // super(m + " " + t.location()); // } // }
import stone.StoneException;
package chap13; public class Opcode { public static final byte ICONST = 1; // load an integer public static final byte BCONST = 2; // load an 8bit (1byte) integer public static final byte SCONST = 3; // load a character string public static final byte MOVE = 4; // move a value public static final byte GMOVE = 5; // move a value (global variable) public static final byte IFZERO = 6; // branch if false public static final byte GOTO = 7; // always branch public static final byte CALL = 8; // call a function public static final byte RETURN = 9; // return public static final byte SAVE = 10; // save all registers public static final byte RESTORE = 11; // restore all registers public static final byte NEG = 12; // arithmetic negation public static final byte ADD = 13; // add public static final byte SUB = 14; // subtract public static final byte MUL = 15; // multiply public static final byte DIV = 16; // divide public static final byte REM = 17; // remainder public static final byte EQUAL = 18; // equal public static final byte MORE = 19; // more than public static final byte LESS = 20; // less than public static byte encodeRegister(int reg) { if (reg > StoneVM.NUM_OF_REG)
// Path: src/stone/StoneException.java // public class StoneException extends RuntimeException { // public StoneException(String m) { super(m); } // public StoneException(String m, ASTree t) { // super(m + " " + t.location()); // } // } // Path: src/chap13/Opcode.java import stone.StoneException; package chap13; public class Opcode { public static final byte ICONST = 1; // load an integer public static final byte BCONST = 2; // load an 8bit (1byte) integer public static final byte SCONST = 3; // load a character string public static final byte MOVE = 4; // move a value public static final byte GMOVE = 5; // move a value (global variable) public static final byte IFZERO = 6; // branch if false public static final byte GOTO = 7; // always branch public static final byte CALL = 8; // call a function public static final byte RETURN = 9; // return public static final byte SAVE = 10; // save all registers public static final byte RESTORE = 11; // restore all registers public static final byte NEG = 12; // arithmetic negation public static final byte ADD = 13; // add public static final byte SUB = 14; // subtract public static final byte MUL = 15; // multiply public static final byte DIV = 16; // divide public static final byte REM = 17; // remainder public static final byte EQUAL = 18; // equal public static final byte MORE = 19; // more than public static final byte LESS = 20; // less than public static byte encodeRegister(int reg) { if (reg > StoneVM.NUM_OF_REG)
throw new StoneException("too many registers required");
chibash/stone
src/stone/FuncParser.java
// Path: src/stone/Parser.java // public static Parser rule() { return rule(null); } // // Path: src/stone/ast/ParameterList.java // public class ParameterList extends ASTList { // public ParameterList(List<ASTree> c) { super(c); } // public String name(int i) { return ((ASTLeaf)child(i)).token().getText(); } // public int size() { return numChildren(); } // } // // Path: src/stone/ast/Arguments.java // public class Arguments extends Postfix { // public Arguments(List<ASTree> c) { super(c); } // public int size() { return numChildren(); } // } // // Path: src/stone/ast/DefStmnt.java // public class DefStmnt extends ASTList { // public DefStmnt(List<ASTree> c) { super(c); } // public String name() { return ((ASTLeaf)child(0)).token().getText(); } // public ParameterList parameters() { return (ParameterList)child(1); } // public BlockStmnt body() { return (BlockStmnt)child(2); } // public String toString() { // return "(def " + name() + " " + parameters() + " " + body() + ")"; // } // }
import static stone.Parser.rule; import stone.ast.ParameterList; import stone.ast.Arguments; import stone.ast.DefStmnt;
package stone; public class FuncParser extends BasicParser { Parser param = rule().identifier(reserved);
// Path: src/stone/Parser.java // public static Parser rule() { return rule(null); } // // Path: src/stone/ast/ParameterList.java // public class ParameterList extends ASTList { // public ParameterList(List<ASTree> c) { super(c); } // public String name(int i) { return ((ASTLeaf)child(i)).token().getText(); } // public int size() { return numChildren(); } // } // // Path: src/stone/ast/Arguments.java // public class Arguments extends Postfix { // public Arguments(List<ASTree> c) { super(c); } // public int size() { return numChildren(); } // } // // Path: src/stone/ast/DefStmnt.java // public class DefStmnt extends ASTList { // public DefStmnt(List<ASTree> c) { super(c); } // public String name() { return ((ASTLeaf)child(0)).token().getText(); } // public ParameterList parameters() { return (ParameterList)child(1); } // public BlockStmnt body() { return (BlockStmnt)child(2); } // public String toString() { // return "(def " + name() + " " + parameters() + " " + body() + ")"; // } // } // Path: src/stone/FuncParser.java import static stone.Parser.rule; import stone.ast.ParameterList; import stone.ast.Arguments; import stone.ast.DefStmnt; package stone; public class FuncParser extends BasicParser { Parser param = rule().identifier(reserved);
Parser params = rule(ParameterList.class)
chibash/stone
src/stone/FuncParser.java
// Path: src/stone/Parser.java // public static Parser rule() { return rule(null); } // // Path: src/stone/ast/ParameterList.java // public class ParameterList extends ASTList { // public ParameterList(List<ASTree> c) { super(c); } // public String name(int i) { return ((ASTLeaf)child(i)).token().getText(); } // public int size() { return numChildren(); } // } // // Path: src/stone/ast/Arguments.java // public class Arguments extends Postfix { // public Arguments(List<ASTree> c) { super(c); } // public int size() { return numChildren(); } // } // // Path: src/stone/ast/DefStmnt.java // public class DefStmnt extends ASTList { // public DefStmnt(List<ASTree> c) { super(c); } // public String name() { return ((ASTLeaf)child(0)).token().getText(); } // public ParameterList parameters() { return (ParameterList)child(1); } // public BlockStmnt body() { return (BlockStmnt)child(2); } // public String toString() { // return "(def " + name() + " " + parameters() + " " + body() + ")"; // } // }
import static stone.Parser.rule; import stone.ast.ParameterList; import stone.ast.Arguments; import stone.ast.DefStmnt;
package stone; public class FuncParser extends BasicParser { Parser param = rule().identifier(reserved); Parser params = rule(ParameterList.class) .ast(param).repeat(rule().sep(",").ast(param)); Parser paramList = rule().sep("(").maybe(params).sep(")");
// Path: src/stone/Parser.java // public static Parser rule() { return rule(null); } // // Path: src/stone/ast/ParameterList.java // public class ParameterList extends ASTList { // public ParameterList(List<ASTree> c) { super(c); } // public String name(int i) { return ((ASTLeaf)child(i)).token().getText(); } // public int size() { return numChildren(); } // } // // Path: src/stone/ast/Arguments.java // public class Arguments extends Postfix { // public Arguments(List<ASTree> c) { super(c); } // public int size() { return numChildren(); } // } // // Path: src/stone/ast/DefStmnt.java // public class DefStmnt extends ASTList { // public DefStmnt(List<ASTree> c) { super(c); } // public String name() { return ((ASTLeaf)child(0)).token().getText(); } // public ParameterList parameters() { return (ParameterList)child(1); } // public BlockStmnt body() { return (BlockStmnt)child(2); } // public String toString() { // return "(def " + name() + " " + parameters() + " " + body() + ")"; // } // } // Path: src/stone/FuncParser.java import static stone.Parser.rule; import stone.ast.ParameterList; import stone.ast.Arguments; import stone.ast.DefStmnt; package stone; public class FuncParser extends BasicParser { Parser param = rule().identifier(reserved); Parser params = rule(ParameterList.class) .ast(param).repeat(rule().sep(",").ast(param)); Parser paramList = rule().sep("(").maybe(params).sep(")");
Parser def = rule(DefStmnt.class)
chibash/stone
src/stone/FuncParser.java
// Path: src/stone/Parser.java // public static Parser rule() { return rule(null); } // // Path: src/stone/ast/ParameterList.java // public class ParameterList extends ASTList { // public ParameterList(List<ASTree> c) { super(c); } // public String name(int i) { return ((ASTLeaf)child(i)).token().getText(); } // public int size() { return numChildren(); } // } // // Path: src/stone/ast/Arguments.java // public class Arguments extends Postfix { // public Arguments(List<ASTree> c) { super(c); } // public int size() { return numChildren(); } // } // // Path: src/stone/ast/DefStmnt.java // public class DefStmnt extends ASTList { // public DefStmnt(List<ASTree> c) { super(c); } // public String name() { return ((ASTLeaf)child(0)).token().getText(); } // public ParameterList parameters() { return (ParameterList)child(1); } // public BlockStmnt body() { return (BlockStmnt)child(2); } // public String toString() { // return "(def " + name() + " " + parameters() + " " + body() + ")"; // } // }
import static stone.Parser.rule; import stone.ast.ParameterList; import stone.ast.Arguments; import stone.ast.DefStmnt;
package stone; public class FuncParser extends BasicParser { Parser param = rule().identifier(reserved); Parser params = rule(ParameterList.class) .ast(param).repeat(rule().sep(",").ast(param)); Parser paramList = rule().sep("(").maybe(params).sep(")"); Parser def = rule(DefStmnt.class) .sep("def").identifier(reserved).ast(paramList).ast(block);
// Path: src/stone/Parser.java // public static Parser rule() { return rule(null); } // // Path: src/stone/ast/ParameterList.java // public class ParameterList extends ASTList { // public ParameterList(List<ASTree> c) { super(c); } // public String name(int i) { return ((ASTLeaf)child(i)).token().getText(); } // public int size() { return numChildren(); } // } // // Path: src/stone/ast/Arguments.java // public class Arguments extends Postfix { // public Arguments(List<ASTree> c) { super(c); } // public int size() { return numChildren(); } // } // // Path: src/stone/ast/DefStmnt.java // public class DefStmnt extends ASTList { // public DefStmnt(List<ASTree> c) { super(c); } // public String name() { return ((ASTLeaf)child(0)).token().getText(); } // public ParameterList parameters() { return (ParameterList)child(1); } // public BlockStmnt body() { return (BlockStmnt)child(2); } // public String toString() { // return "(def " + name() + " " + parameters() + " " + body() + ")"; // } // } // Path: src/stone/FuncParser.java import static stone.Parser.rule; import stone.ast.ParameterList; import stone.ast.Arguments; import stone.ast.DefStmnt; package stone; public class FuncParser extends BasicParser { Parser param = rule().identifier(reserved); Parser params = rule(ParameterList.class) .ast(param).repeat(rule().sep(",").ast(param)); Parser paramList = rule().sep("(").maybe(params).sep(")"); Parser def = rule(DefStmnt.class) .sep("def").identifier(reserved).ast(paramList).ast(block);
Parser args = rule(Arguments.class)
chibash/stone
src/chap7/Function.java
// Path: src/stone/ast/BlockStmnt.java // public class BlockStmnt extends ASTList { // public BlockStmnt(List<ASTree> c) { super(c); } // } // // Path: src/stone/ast/ParameterList.java // public class ParameterList extends ASTList { // public ParameterList(List<ASTree> c) { super(c); } // public String name(int i) { return ((ASTLeaf)child(i)).token().getText(); } // public int size() { return numChildren(); } // } // // Path: src/chap6/Environment.java // public interface Environment { // void put(String name, Object value); // Object get(String name); // }
import stone.ast.BlockStmnt; import stone.ast.ParameterList; import chap6.Environment;
package chap7; public class Function { protected ParameterList parameters;
// Path: src/stone/ast/BlockStmnt.java // public class BlockStmnt extends ASTList { // public BlockStmnt(List<ASTree> c) { super(c); } // } // // Path: src/stone/ast/ParameterList.java // public class ParameterList extends ASTList { // public ParameterList(List<ASTree> c) { super(c); } // public String name(int i) { return ((ASTLeaf)child(i)).token().getText(); } // public int size() { return numChildren(); } // } // // Path: src/chap6/Environment.java // public interface Environment { // void put(String name, Object value); // Object get(String name); // } // Path: src/chap7/Function.java import stone.ast.BlockStmnt; import stone.ast.ParameterList; import chap6.Environment; package chap7; public class Function { protected ParameterList parameters;
protected BlockStmnt body;
chibash/stone
src/chap7/Function.java
// Path: src/stone/ast/BlockStmnt.java // public class BlockStmnt extends ASTList { // public BlockStmnt(List<ASTree> c) { super(c); } // } // // Path: src/stone/ast/ParameterList.java // public class ParameterList extends ASTList { // public ParameterList(List<ASTree> c) { super(c); } // public String name(int i) { return ((ASTLeaf)child(i)).token().getText(); } // public int size() { return numChildren(); } // } // // Path: src/chap6/Environment.java // public interface Environment { // void put(String name, Object value); // Object get(String name); // }
import stone.ast.BlockStmnt; import stone.ast.ParameterList; import chap6.Environment;
package chap7; public class Function { protected ParameterList parameters; protected BlockStmnt body;
// Path: src/stone/ast/BlockStmnt.java // public class BlockStmnt extends ASTList { // public BlockStmnt(List<ASTree> c) { super(c); } // } // // Path: src/stone/ast/ParameterList.java // public class ParameterList extends ASTList { // public ParameterList(List<ASTree> c) { super(c); } // public String name(int i) { return ((ASTLeaf)child(i)).token().getText(); } // public int size() { return numChildren(); } // } // // Path: src/chap6/Environment.java // public interface Environment { // void put(String name, Object value); // Object get(String name); // } // Path: src/chap7/Function.java import stone.ast.BlockStmnt; import stone.ast.ParameterList; import chap6.Environment; package chap7; public class Function { protected ParameterList parameters; protected BlockStmnt body;
protected Environment env;
chibash/stone
src/chap7/ClosureEvaluator.java
// Path: src/stone/ast/ASTree.java // public abstract class ASTree implements Iterable<ASTree> { // public abstract ASTree child(int i); // public abstract int numChildren(); // public abstract Iterator<ASTree> children(); // public abstract String location(); // public Iterator<ASTree> iterator() { return children(); } // } // // Path: src/stone/ast/Fun.java // public class Fun extends ASTList { // public Fun(List<ASTree> c) { super(c); } // public ParameterList parameters() { return (ParameterList)child(0); } // public BlockStmnt body() { return (BlockStmnt)child(1); } // public String toString() { // return "(fun " + parameters() + " " + body() + ")"; // } // } // // Path: src/chap6/Environment.java // public interface Environment { // void put(String name, Object value); // Object get(String name); // }
import java.util.List; import javassist.gluonj.*; import stone.ast.ASTree; import stone.ast.Fun; import chap6.Environment;
package chap7; @Require(FuncEvaluator.class) @Reviser public class ClosureEvaluator {
// Path: src/stone/ast/ASTree.java // public abstract class ASTree implements Iterable<ASTree> { // public abstract ASTree child(int i); // public abstract int numChildren(); // public abstract Iterator<ASTree> children(); // public abstract String location(); // public Iterator<ASTree> iterator() { return children(); } // } // // Path: src/stone/ast/Fun.java // public class Fun extends ASTList { // public Fun(List<ASTree> c) { super(c); } // public ParameterList parameters() { return (ParameterList)child(0); } // public BlockStmnt body() { return (BlockStmnt)child(1); } // public String toString() { // return "(fun " + parameters() + " " + body() + ")"; // } // } // // Path: src/chap6/Environment.java // public interface Environment { // void put(String name, Object value); // Object get(String name); // } // Path: src/chap7/ClosureEvaluator.java import java.util.List; import javassist.gluonj.*; import stone.ast.ASTree; import stone.ast.Fun; import chap6.Environment; package chap7; @Require(FuncEvaluator.class) @Reviser public class ClosureEvaluator {
@Reviser public static class FunEx extends Fun {
chibash/stone
src/chap7/ClosureEvaluator.java
// Path: src/stone/ast/ASTree.java // public abstract class ASTree implements Iterable<ASTree> { // public abstract ASTree child(int i); // public abstract int numChildren(); // public abstract Iterator<ASTree> children(); // public abstract String location(); // public Iterator<ASTree> iterator() { return children(); } // } // // Path: src/stone/ast/Fun.java // public class Fun extends ASTList { // public Fun(List<ASTree> c) { super(c); } // public ParameterList parameters() { return (ParameterList)child(0); } // public BlockStmnt body() { return (BlockStmnt)child(1); } // public String toString() { // return "(fun " + parameters() + " " + body() + ")"; // } // } // // Path: src/chap6/Environment.java // public interface Environment { // void put(String name, Object value); // Object get(String name); // }
import java.util.List; import javassist.gluonj.*; import stone.ast.ASTree; import stone.ast.Fun; import chap6.Environment;
package chap7; @Require(FuncEvaluator.class) @Reviser public class ClosureEvaluator { @Reviser public static class FunEx extends Fun {
// Path: src/stone/ast/ASTree.java // public abstract class ASTree implements Iterable<ASTree> { // public abstract ASTree child(int i); // public abstract int numChildren(); // public abstract Iterator<ASTree> children(); // public abstract String location(); // public Iterator<ASTree> iterator() { return children(); } // } // // Path: src/stone/ast/Fun.java // public class Fun extends ASTList { // public Fun(List<ASTree> c) { super(c); } // public ParameterList parameters() { return (ParameterList)child(0); } // public BlockStmnt body() { return (BlockStmnt)child(1); } // public String toString() { // return "(fun " + parameters() + " " + body() + ")"; // } // } // // Path: src/chap6/Environment.java // public interface Environment { // void put(String name, Object value); // Object get(String name); // } // Path: src/chap7/ClosureEvaluator.java import java.util.List; import javassist.gluonj.*; import stone.ast.ASTree; import stone.ast.Fun; import chap6.Environment; package chap7; @Require(FuncEvaluator.class) @Reviser public class ClosureEvaluator { @Reviser public static class FunEx extends Fun {
public FunEx(List<ASTree> c) { super(c); }
chibash/stone
src/chap7/ClosureEvaluator.java
// Path: src/stone/ast/ASTree.java // public abstract class ASTree implements Iterable<ASTree> { // public abstract ASTree child(int i); // public abstract int numChildren(); // public abstract Iterator<ASTree> children(); // public abstract String location(); // public Iterator<ASTree> iterator() { return children(); } // } // // Path: src/stone/ast/Fun.java // public class Fun extends ASTList { // public Fun(List<ASTree> c) { super(c); } // public ParameterList parameters() { return (ParameterList)child(0); } // public BlockStmnt body() { return (BlockStmnt)child(1); } // public String toString() { // return "(fun " + parameters() + " " + body() + ")"; // } // } // // Path: src/chap6/Environment.java // public interface Environment { // void put(String name, Object value); // Object get(String name); // }
import java.util.List; import javassist.gluonj.*; import stone.ast.ASTree; import stone.ast.Fun; import chap6.Environment;
package chap7; @Require(FuncEvaluator.class) @Reviser public class ClosureEvaluator { @Reviser public static class FunEx extends Fun { public FunEx(List<ASTree> c) { super(c); }
// Path: src/stone/ast/ASTree.java // public abstract class ASTree implements Iterable<ASTree> { // public abstract ASTree child(int i); // public abstract int numChildren(); // public abstract Iterator<ASTree> children(); // public abstract String location(); // public Iterator<ASTree> iterator() { return children(); } // } // // Path: src/stone/ast/Fun.java // public class Fun extends ASTList { // public Fun(List<ASTree> c) { super(c); } // public ParameterList parameters() { return (ParameterList)child(0); } // public BlockStmnt body() { return (BlockStmnt)child(1); } // public String toString() { // return "(fun " + parameters() + " " + body() + ")"; // } // } // // Path: src/chap6/Environment.java // public interface Environment { // void put(String name, Object value); // Object get(String name); // } // Path: src/chap7/ClosureEvaluator.java import java.util.List; import javassist.gluonj.*; import stone.ast.ASTree; import stone.ast.Fun; import chap6.Environment; package chap7; @Require(FuncEvaluator.class) @Reviser public class ClosureEvaluator { @Reviser public static class FunEx extends Fun { public FunEx(List<ASTree> c) { super(c); }
public Object eval(Environment env) {
chibash/stone
src/chap6/BasicInterpreter.java
// Path: src/stone/ast/ASTree.java // public abstract class ASTree implements Iterable<ASTree> { // public abstract ASTree child(int i); // public abstract int numChildren(); // public abstract Iterator<ASTree> children(); // public abstract String location(); // public Iterator<ASTree> iterator() { return children(); } // } // // Path: src/stone/ast/NullStmnt.java // public class NullStmnt extends ASTList { // public NullStmnt(List<ASTree> c) { super(c); } // }
import stone.*; import stone.ast.ASTree; import stone.ast.NullStmnt;
package chap6; public class BasicInterpreter { public static void main(String[] args) throws ParseException { run(new BasicParser(), new BasicEnv()); } public static void run(BasicParser bp, Environment env) throws ParseException { Lexer lexer = new Lexer(new CodeDialog()); while (lexer.peek(0) != Token.EOF) {
// Path: src/stone/ast/ASTree.java // public abstract class ASTree implements Iterable<ASTree> { // public abstract ASTree child(int i); // public abstract int numChildren(); // public abstract Iterator<ASTree> children(); // public abstract String location(); // public Iterator<ASTree> iterator() { return children(); } // } // // Path: src/stone/ast/NullStmnt.java // public class NullStmnt extends ASTList { // public NullStmnt(List<ASTree> c) { super(c); } // } // Path: src/chap6/BasicInterpreter.java import stone.*; import stone.ast.ASTree; import stone.ast.NullStmnt; package chap6; public class BasicInterpreter { public static void main(String[] args) throws ParseException { run(new BasicParser(), new BasicEnv()); } public static void run(BasicParser bp, Environment env) throws ParseException { Lexer lexer = new Lexer(new CodeDialog()); while (lexer.peek(0) != Token.EOF) {
ASTree t = bp.parse(lexer);
chibash/stone
src/chap6/BasicInterpreter.java
// Path: src/stone/ast/ASTree.java // public abstract class ASTree implements Iterable<ASTree> { // public abstract ASTree child(int i); // public abstract int numChildren(); // public abstract Iterator<ASTree> children(); // public abstract String location(); // public Iterator<ASTree> iterator() { return children(); } // } // // Path: src/stone/ast/NullStmnt.java // public class NullStmnt extends ASTList { // public NullStmnt(List<ASTree> c) { super(c); } // }
import stone.*; import stone.ast.ASTree; import stone.ast.NullStmnt;
package chap6; public class BasicInterpreter { public static void main(String[] args) throws ParseException { run(new BasicParser(), new BasicEnv()); } public static void run(BasicParser bp, Environment env) throws ParseException { Lexer lexer = new Lexer(new CodeDialog()); while (lexer.peek(0) != Token.EOF) { ASTree t = bp.parse(lexer);
// Path: src/stone/ast/ASTree.java // public abstract class ASTree implements Iterable<ASTree> { // public abstract ASTree child(int i); // public abstract int numChildren(); // public abstract Iterator<ASTree> children(); // public abstract String location(); // public Iterator<ASTree> iterator() { return children(); } // } // // Path: src/stone/ast/NullStmnt.java // public class NullStmnt extends ASTList { // public NullStmnt(List<ASTree> c) { super(c); } // } // Path: src/chap6/BasicInterpreter.java import stone.*; import stone.ast.ASTree; import stone.ast.NullStmnt; package chap6; public class BasicInterpreter { public static void main(String[] args) throws ParseException { run(new BasicParser(), new BasicEnv()); } public static void run(BasicParser bp, Environment env) throws ParseException { Lexer lexer = new Lexer(new CodeDialog()); while (lexer.peek(0) != Token.EOF) { ASTree t = bp.parse(lexer);
if (!(t instanceof NullStmnt)) {
chibash/stone
src/chap9/ClassInterpreter.java
// Path: src/stone/ClassParser.java // public class ClassParser extends ClosureParser { // Parser member = rule().or(def, simple); // Parser class_body = rule(ClassBody.class).sep("{").option(member) // .repeat(rule().sep(";", Token.EOL).option(member)) // .sep("}"); // Parser defclass = rule(ClassStmnt.class).sep("class").identifier(reserved) // .option(rule().sep("extends").identifier(reserved)) // .ast(class_body); // public ClassParser() { // postfix.insertChoice(rule(Dot.class).sep(".").identifier(reserved)); // program.insertChoice(defclass); // } // } // // Path: src/stone/ParseException.java // public class ParseException extends Exception { // public ParseException(Token t) { // this("", t); // } // public ParseException(String msg, Token t) { // super("syntax error around " + location(t) + ". " + msg); // } // private static String location(Token t) { // if (t == Token.EOF) // return "the last line"; // else // return "\"" + t.getText() + "\" at line " + t.getLineNumber(); // } // public ParseException(IOException e) { // super(e); // } // public ParseException(String msg) { // super(msg); // } // } // // Path: src/chap6/BasicInterpreter.java // public class BasicInterpreter { // public static void main(String[] args) throws ParseException { // run(new BasicParser(), new BasicEnv()); // } // public static void run(BasicParser bp, Environment env) // throws ParseException // { // Lexer lexer = new Lexer(new CodeDialog()); // while (lexer.peek(0) != Token.EOF) { // ASTree t = bp.parse(lexer); // if (!(t instanceof NullStmnt)) { // Object r = ((BasicEvaluator.ASTreeEx)t).eval(env); // System.out.println("=> " + r); // } // } // } // } // // Path: src/chap7/NestedEnv.java // public class NestedEnv implements Environment { // protected HashMap<String,Object> values; // protected Environment outer; // public NestedEnv() { this(null); } // public NestedEnv(Environment e) { // values = new HashMap<String,Object>(); // outer = e; // } // public void setOuter(Environment e) { outer = e; } // public Object get(String name) { // Object v = values.get(name); // if (v == null && outer != null) // return outer.get(name); // else // return v; // } // public void putNew(String name, Object value) { values.put(name, value); } // public void put(String name, Object value) { // Environment e = where(name); // if (e == null) // e = this; // ((EnvEx)e).putNew(name, value); // } // public Environment where(String name) { // if (values.get(name) != null) // return this; // else if (outer == null) // return null; // else // return ((EnvEx)outer).where(name); // } // } // // Path: src/chap8/Natives.java // public class Natives { // public Environment environment(Environment env) { // appendNatives(env); // return env; // } // protected void appendNatives(Environment env) { // append(env, "print", Natives.class, "print", Object.class); // append(env, "read", Natives.class, "read"); // append(env, "length", Natives.class, "length", String.class); // append(env, "toInt", Natives.class, "toInt", Object.class); // append(env, "currentTime", Natives.class, "currentTime"); // } // protected void append(Environment env, String name, Class<?> clazz, // String methodName, Class<?> ... params) { // Method m; // try { // m = clazz.getMethod(methodName, params); // } catch (Exception e) { // throw new StoneException("cannot find a native function: " // + methodName); // } // env.put(name, new NativeFunction(methodName, m)); // } // // // native methods // public static int print(Object obj) { // System.out.println(obj.toString()); // return 0; // } // public static String read() { // return JOptionPane.showInputDialog(null); // } // public static int length(String s) { return s.length(); } // public static int toInt(Object value) { // if (value instanceof String) // return Integer.parseInt((String)value); // else if (value instanceof Integer) // return ((Integer)value).intValue(); // else // throw new NumberFormatException(value.toString()); // } // private static long startTime = System.currentTimeMillis(); // public static int currentTime() { // return (int)(System.currentTimeMillis() - startTime); // } // }
import stone.ClassParser; import stone.ParseException; import chap6.BasicInterpreter; import chap7.NestedEnv; import chap8.Natives;
package chap9; public class ClassInterpreter extends BasicInterpreter { public static void main(String[] args) throws ParseException {
// Path: src/stone/ClassParser.java // public class ClassParser extends ClosureParser { // Parser member = rule().or(def, simple); // Parser class_body = rule(ClassBody.class).sep("{").option(member) // .repeat(rule().sep(";", Token.EOL).option(member)) // .sep("}"); // Parser defclass = rule(ClassStmnt.class).sep("class").identifier(reserved) // .option(rule().sep("extends").identifier(reserved)) // .ast(class_body); // public ClassParser() { // postfix.insertChoice(rule(Dot.class).sep(".").identifier(reserved)); // program.insertChoice(defclass); // } // } // // Path: src/stone/ParseException.java // public class ParseException extends Exception { // public ParseException(Token t) { // this("", t); // } // public ParseException(String msg, Token t) { // super("syntax error around " + location(t) + ". " + msg); // } // private static String location(Token t) { // if (t == Token.EOF) // return "the last line"; // else // return "\"" + t.getText() + "\" at line " + t.getLineNumber(); // } // public ParseException(IOException e) { // super(e); // } // public ParseException(String msg) { // super(msg); // } // } // // Path: src/chap6/BasicInterpreter.java // public class BasicInterpreter { // public static void main(String[] args) throws ParseException { // run(new BasicParser(), new BasicEnv()); // } // public static void run(BasicParser bp, Environment env) // throws ParseException // { // Lexer lexer = new Lexer(new CodeDialog()); // while (lexer.peek(0) != Token.EOF) { // ASTree t = bp.parse(lexer); // if (!(t instanceof NullStmnt)) { // Object r = ((BasicEvaluator.ASTreeEx)t).eval(env); // System.out.println("=> " + r); // } // } // } // } // // Path: src/chap7/NestedEnv.java // public class NestedEnv implements Environment { // protected HashMap<String,Object> values; // protected Environment outer; // public NestedEnv() { this(null); } // public NestedEnv(Environment e) { // values = new HashMap<String,Object>(); // outer = e; // } // public void setOuter(Environment e) { outer = e; } // public Object get(String name) { // Object v = values.get(name); // if (v == null && outer != null) // return outer.get(name); // else // return v; // } // public void putNew(String name, Object value) { values.put(name, value); } // public void put(String name, Object value) { // Environment e = where(name); // if (e == null) // e = this; // ((EnvEx)e).putNew(name, value); // } // public Environment where(String name) { // if (values.get(name) != null) // return this; // else if (outer == null) // return null; // else // return ((EnvEx)outer).where(name); // } // } // // Path: src/chap8/Natives.java // public class Natives { // public Environment environment(Environment env) { // appendNatives(env); // return env; // } // protected void appendNatives(Environment env) { // append(env, "print", Natives.class, "print", Object.class); // append(env, "read", Natives.class, "read"); // append(env, "length", Natives.class, "length", String.class); // append(env, "toInt", Natives.class, "toInt", Object.class); // append(env, "currentTime", Natives.class, "currentTime"); // } // protected void append(Environment env, String name, Class<?> clazz, // String methodName, Class<?> ... params) { // Method m; // try { // m = clazz.getMethod(methodName, params); // } catch (Exception e) { // throw new StoneException("cannot find a native function: " // + methodName); // } // env.put(name, new NativeFunction(methodName, m)); // } // // // native methods // public static int print(Object obj) { // System.out.println(obj.toString()); // return 0; // } // public static String read() { // return JOptionPane.showInputDialog(null); // } // public static int length(String s) { return s.length(); } // public static int toInt(Object value) { // if (value instanceof String) // return Integer.parseInt((String)value); // else if (value instanceof Integer) // return ((Integer)value).intValue(); // else // throw new NumberFormatException(value.toString()); // } // private static long startTime = System.currentTimeMillis(); // public static int currentTime() { // return (int)(System.currentTimeMillis() - startTime); // } // } // Path: src/chap9/ClassInterpreter.java import stone.ClassParser; import stone.ParseException; import chap6.BasicInterpreter; import chap7.NestedEnv; import chap8.Natives; package chap9; public class ClassInterpreter extends BasicInterpreter { public static void main(String[] args) throws ParseException {
run(new ClassParser(), new Natives().environment(new NestedEnv()));
chibash/stone
src/chap9/ClassInterpreter.java
// Path: src/stone/ClassParser.java // public class ClassParser extends ClosureParser { // Parser member = rule().or(def, simple); // Parser class_body = rule(ClassBody.class).sep("{").option(member) // .repeat(rule().sep(";", Token.EOL).option(member)) // .sep("}"); // Parser defclass = rule(ClassStmnt.class).sep("class").identifier(reserved) // .option(rule().sep("extends").identifier(reserved)) // .ast(class_body); // public ClassParser() { // postfix.insertChoice(rule(Dot.class).sep(".").identifier(reserved)); // program.insertChoice(defclass); // } // } // // Path: src/stone/ParseException.java // public class ParseException extends Exception { // public ParseException(Token t) { // this("", t); // } // public ParseException(String msg, Token t) { // super("syntax error around " + location(t) + ". " + msg); // } // private static String location(Token t) { // if (t == Token.EOF) // return "the last line"; // else // return "\"" + t.getText() + "\" at line " + t.getLineNumber(); // } // public ParseException(IOException e) { // super(e); // } // public ParseException(String msg) { // super(msg); // } // } // // Path: src/chap6/BasicInterpreter.java // public class BasicInterpreter { // public static void main(String[] args) throws ParseException { // run(new BasicParser(), new BasicEnv()); // } // public static void run(BasicParser bp, Environment env) // throws ParseException // { // Lexer lexer = new Lexer(new CodeDialog()); // while (lexer.peek(0) != Token.EOF) { // ASTree t = bp.parse(lexer); // if (!(t instanceof NullStmnt)) { // Object r = ((BasicEvaluator.ASTreeEx)t).eval(env); // System.out.println("=> " + r); // } // } // } // } // // Path: src/chap7/NestedEnv.java // public class NestedEnv implements Environment { // protected HashMap<String,Object> values; // protected Environment outer; // public NestedEnv() { this(null); } // public NestedEnv(Environment e) { // values = new HashMap<String,Object>(); // outer = e; // } // public void setOuter(Environment e) { outer = e; } // public Object get(String name) { // Object v = values.get(name); // if (v == null && outer != null) // return outer.get(name); // else // return v; // } // public void putNew(String name, Object value) { values.put(name, value); } // public void put(String name, Object value) { // Environment e = where(name); // if (e == null) // e = this; // ((EnvEx)e).putNew(name, value); // } // public Environment where(String name) { // if (values.get(name) != null) // return this; // else if (outer == null) // return null; // else // return ((EnvEx)outer).where(name); // } // } // // Path: src/chap8/Natives.java // public class Natives { // public Environment environment(Environment env) { // appendNatives(env); // return env; // } // protected void appendNatives(Environment env) { // append(env, "print", Natives.class, "print", Object.class); // append(env, "read", Natives.class, "read"); // append(env, "length", Natives.class, "length", String.class); // append(env, "toInt", Natives.class, "toInt", Object.class); // append(env, "currentTime", Natives.class, "currentTime"); // } // protected void append(Environment env, String name, Class<?> clazz, // String methodName, Class<?> ... params) { // Method m; // try { // m = clazz.getMethod(methodName, params); // } catch (Exception e) { // throw new StoneException("cannot find a native function: " // + methodName); // } // env.put(name, new NativeFunction(methodName, m)); // } // // // native methods // public static int print(Object obj) { // System.out.println(obj.toString()); // return 0; // } // public static String read() { // return JOptionPane.showInputDialog(null); // } // public static int length(String s) { return s.length(); } // public static int toInt(Object value) { // if (value instanceof String) // return Integer.parseInt((String)value); // else if (value instanceof Integer) // return ((Integer)value).intValue(); // else // throw new NumberFormatException(value.toString()); // } // private static long startTime = System.currentTimeMillis(); // public static int currentTime() { // return (int)(System.currentTimeMillis() - startTime); // } // }
import stone.ClassParser; import stone.ParseException; import chap6.BasicInterpreter; import chap7.NestedEnv; import chap8.Natives;
package chap9; public class ClassInterpreter extends BasicInterpreter { public static void main(String[] args) throws ParseException {
// Path: src/stone/ClassParser.java // public class ClassParser extends ClosureParser { // Parser member = rule().or(def, simple); // Parser class_body = rule(ClassBody.class).sep("{").option(member) // .repeat(rule().sep(";", Token.EOL).option(member)) // .sep("}"); // Parser defclass = rule(ClassStmnt.class).sep("class").identifier(reserved) // .option(rule().sep("extends").identifier(reserved)) // .ast(class_body); // public ClassParser() { // postfix.insertChoice(rule(Dot.class).sep(".").identifier(reserved)); // program.insertChoice(defclass); // } // } // // Path: src/stone/ParseException.java // public class ParseException extends Exception { // public ParseException(Token t) { // this("", t); // } // public ParseException(String msg, Token t) { // super("syntax error around " + location(t) + ". " + msg); // } // private static String location(Token t) { // if (t == Token.EOF) // return "the last line"; // else // return "\"" + t.getText() + "\" at line " + t.getLineNumber(); // } // public ParseException(IOException e) { // super(e); // } // public ParseException(String msg) { // super(msg); // } // } // // Path: src/chap6/BasicInterpreter.java // public class BasicInterpreter { // public static void main(String[] args) throws ParseException { // run(new BasicParser(), new BasicEnv()); // } // public static void run(BasicParser bp, Environment env) // throws ParseException // { // Lexer lexer = new Lexer(new CodeDialog()); // while (lexer.peek(0) != Token.EOF) { // ASTree t = bp.parse(lexer); // if (!(t instanceof NullStmnt)) { // Object r = ((BasicEvaluator.ASTreeEx)t).eval(env); // System.out.println("=> " + r); // } // } // } // } // // Path: src/chap7/NestedEnv.java // public class NestedEnv implements Environment { // protected HashMap<String,Object> values; // protected Environment outer; // public NestedEnv() { this(null); } // public NestedEnv(Environment e) { // values = new HashMap<String,Object>(); // outer = e; // } // public void setOuter(Environment e) { outer = e; } // public Object get(String name) { // Object v = values.get(name); // if (v == null && outer != null) // return outer.get(name); // else // return v; // } // public void putNew(String name, Object value) { values.put(name, value); } // public void put(String name, Object value) { // Environment e = where(name); // if (e == null) // e = this; // ((EnvEx)e).putNew(name, value); // } // public Environment where(String name) { // if (values.get(name) != null) // return this; // else if (outer == null) // return null; // else // return ((EnvEx)outer).where(name); // } // } // // Path: src/chap8/Natives.java // public class Natives { // public Environment environment(Environment env) { // appendNatives(env); // return env; // } // protected void appendNatives(Environment env) { // append(env, "print", Natives.class, "print", Object.class); // append(env, "read", Natives.class, "read"); // append(env, "length", Natives.class, "length", String.class); // append(env, "toInt", Natives.class, "toInt", Object.class); // append(env, "currentTime", Natives.class, "currentTime"); // } // protected void append(Environment env, String name, Class<?> clazz, // String methodName, Class<?> ... params) { // Method m; // try { // m = clazz.getMethod(methodName, params); // } catch (Exception e) { // throw new StoneException("cannot find a native function: " // + methodName); // } // env.put(name, new NativeFunction(methodName, m)); // } // // // native methods // public static int print(Object obj) { // System.out.println(obj.toString()); // return 0; // } // public static String read() { // return JOptionPane.showInputDialog(null); // } // public static int length(String s) { return s.length(); } // public static int toInt(Object value) { // if (value instanceof String) // return Integer.parseInt((String)value); // else if (value instanceof Integer) // return ((Integer)value).intValue(); // else // throw new NumberFormatException(value.toString()); // } // private static long startTime = System.currentTimeMillis(); // public static int currentTime() { // return (int)(System.currentTimeMillis() - startTime); // } // } // Path: src/chap9/ClassInterpreter.java import stone.ClassParser; import stone.ParseException; import chap6.BasicInterpreter; import chap7.NestedEnv; import chap8.Natives; package chap9; public class ClassInterpreter extends BasicInterpreter { public static void main(String[] args) throws ParseException {
run(new ClassParser(), new Natives().environment(new NestedEnv()));
chibash/stone
src/chap9/ClassInterpreter.java
// Path: src/stone/ClassParser.java // public class ClassParser extends ClosureParser { // Parser member = rule().or(def, simple); // Parser class_body = rule(ClassBody.class).sep("{").option(member) // .repeat(rule().sep(";", Token.EOL).option(member)) // .sep("}"); // Parser defclass = rule(ClassStmnt.class).sep("class").identifier(reserved) // .option(rule().sep("extends").identifier(reserved)) // .ast(class_body); // public ClassParser() { // postfix.insertChoice(rule(Dot.class).sep(".").identifier(reserved)); // program.insertChoice(defclass); // } // } // // Path: src/stone/ParseException.java // public class ParseException extends Exception { // public ParseException(Token t) { // this("", t); // } // public ParseException(String msg, Token t) { // super("syntax error around " + location(t) + ". " + msg); // } // private static String location(Token t) { // if (t == Token.EOF) // return "the last line"; // else // return "\"" + t.getText() + "\" at line " + t.getLineNumber(); // } // public ParseException(IOException e) { // super(e); // } // public ParseException(String msg) { // super(msg); // } // } // // Path: src/chap6/BasicInterpreter.java // public class BasicInterpreter { // public static void main(String[] args) throws ParseException { // run(new BasicParser(), new BasicEnv()); // } // public static void run(BasicParser bp, Environment env) // throws ParseException // { // Lexer lexer = new Lexer(new CodeDialog()); // while (lexer.peek(0) != Token.EOF) { // ASTree t = bp.parse(lexer); // if (!(t instanceof NullStmnt)) { // Object r = ((BasicEvaluator.ASTreeEx)t).eval(env); // System.out.println("=> " + r); // } // } // } // } // // Path: src/chap7/NestedEnv.java // public class NestedEnv implements Environment { // protected HashMap<String,Object> values; // protected Environment outer; // public NestedEnv() { this(null); } // public NestedEnv(Environment e) { // values = new HashMap<String,Object>(); // outer = e; // } // public void setOuter(Environment e) { outer = e; } // public Object get(String name) { // Object v = values.get(name); // if (v == null && outer != null) // return outer.get(name); // else // return v; // } // public void putNew(String name, Object value) { values.put(name, value); } // public void put(String name, Object value) { // Environment e = where(name); // if (e == null) // e = this; // ((EnvEx)e).putNew(name, value); // } // public Environment where(String name) { // if (values.get(name) != null) // return this; // else if (outer == null) // return null; // else // return ((EnvEx)outer).where(name); // } // } // // Path: src/chap8/Natives.java // public class Natives { // public Environment environment(Environment env) { // appendNatives(env); // return env; // } // protected void appendNatives(Environment env) { // append(env, "print", Natives.class, "print", Object.class); // append(env, "read", Natives.class, "read"); // append(env, "length", Natives.class, "length", String.class); // append(env, "toInt", Natives.class, "toInt", Object.class); // append(env, "currentTime", Natives.class, "currentTime"); // } // protected void append(Environment env, String name, Class<?> clazz, // String methodName, Class<?> ... params) { // Method m; // try { // m = clazz.getMethod(methodName, params); // } catch (Exception e) { // throw new StoneException("cannot find a native function: " // + methodName); // } // env.put(name, new NativeFunction(methodName, m)); // } // // // native methods // public static int print(Object obj) { // System.out.println(obj.toString()); // return 0; // } // public static String read() { // return JOptionPane.showInputDialog(null); // } // public static int length(String s) { return s.length(); } // public static int toInt(Object value) { // if (value instanceof String) // return Integer.parseInt((String)value); // else if (value instanceof Integer) // return ((Integer)value).intValue(); // else // throw new NumberFormatException(value.toString()); // } // private static long startTime = System.currentTimeMillis(); // public static int currentTime() { // return (int)(System.currentTimeMillis() - startTime); // } // }
import stone.ClassParser; import stone.ParseException; import chap6.BasicInterpreter; import chap7.NestedEnv; import chap8.Natives;
package chap9; public class ClassInterpreter extends BasicInterpreter { public static void main(String[] args) throws ParseException {
// Path: src/stone/ClassParser.java // public class ClassParser extends ClosureParser { // Parser member = rule().or(def, simple); // Parser class_body = rule(ClassBody.class).sep("{").option(member) // .repeat(rule().sep(";", Token.EOL).option(member)) // .sep("}"); // Parser defclass = rule(ClassStmnt.class).sep("class").identifier(reserved) // .option(rule().sep("extends").identifier(reserved)) // .ast(class_body); // public ClassParser() { // postfix.insertChoice(rule(Dot.class).sep(".").identifier(reserved)); // program.insertChoice(defclass); // } // } // // Path: src/stone/ParseException.java // public class ParseException extends Exception { // public ParseException(Token t) { // this("", t); // } // public ParseException(String msg, Token t) { // super("syntax error around " + location(t) + ". " + msg); // } // private static String location(Token t) { // if (t == Token.EOF) // return "the last line"; // else // return "\"" + t.getText() + "\" at line " + t.getLineNumber(); // } // public ParseException(IOException e) { // super(e); // } // public ParseException(String msg) { // super(msg); // } // } // // Path: src/chap6/BasicInterpreter.java // public class BasicInterpreter { // public static void main(String[] args) throws ParseException { // run(new BasicParser(), new BasicEnv()); // } // public static void run(BasicParser bp, Environment env) // throws ParseException // { // Lexer lexer = new Lexer(new CodeDialog()); // while (lexer.peek(0) != Token.EOF) { // ASTree t = bp.parse(lexer); // if (!(t instanceof NullStmnt)) { // Object r = ((BasicEvaluator.ASTreeEx)t).eval(env); // System.out.println("=> " + r); // } // } // } // } // // Path: src/chap7/NestedEnv.java // public class NestedEnv implements Environment { // protected HashMap<String,Object> values; // protected Environment outer; // public NestedEnv() { this(null); } // public NestedEnv(Environment e) { // values = new HashMap<String,Object>(); // outer = e; // } // public void setOuter(Environment e) { outer = e; } // public Object get(String name) { // Object v = values.get(name); // if (v == null && outer != null) // return outer.get(name); // else // return v; // } // public void putNew(String name, Object value) { values.put(name, value); } // public void put(String name, Object value) { // Environment e = where(name); // if (e == null) // e = this; // ((EnvEx)e).putNew(name, value); // } // public Environment where(String name) { // if (values.get(name) != null) // return this; // else if (outer == null) // return null; // else // return ((EnvEx)outer).where(name); // } // } // // Path: src/chap8/Natives.java // public class Natives { // public Environment environment(Environment env) { // appendNatives(env); // return env; // } // protected void appendNatives(Environment env) { // append(env, "print", Natives.class, "print", Object.class); // append(env, "read", Natives.class, "read"); // append(env, "length", Natives.class, "length", String.class); // append(env, "toInt", Natives.class, "toInt", Object.class); // append(env, "currentTime", Natives.class, "currentTime"); // } // protected void append(Environment env, String name, Class<?> clazz, // String methodName, Class<?> ... params) { // Method m; // try { // m = clazz.getMethod(methodName, params); // } catch (Exception e) { // throw new StoneException("cannot find a native function: " // + methodName); // } // env.put(name, new NativeFunction(methodName, m)); // } // // // native methods // public static int print(Object obj) { // System.out.println(obj.toString()); // return 0; // } // public static String read() { // return JOptionPane.showInputDialog(null); // } // public static int length(String s) { return s.length(); } // public static int toInt(Object value) { // if (value instanceof String) // return Integer.parseInt((String)value); // else if (value instanceof Integer) // return ((Integer)value).intValue(); // else // throw new NumberFormatException(value.toString()); // } // private static long startTime = System.currentTimeMillis(); // public static int currentTime() { // return (int)(System.currentTimeMillis() - startTime); // } // } // Path: src/chap9/ClassInterpreter.java import stone.ClassParser; import stone.ParseException; import chap6.BasicInterpreter; import chap7.NestedEnv; import chap8.Natives; package chap9; public class ClassInterpreter extends BasicInterpreter { public static void main(String[] args) throws ParseException {
run(new ClassParser(), new Natives().environment(new NestedEnv()));
chibash/stone
src/chap11/OptFunction.java
// Path: src/stone/ast/BlockStmnt.java // public class BlockStmnt extends ASTList { // public BlockStmnt(List<ASTree> c) { super(c); } // } // // Path: src/stone/ast/ParameterList.java // public class ParameterList extends ASTList { // public ParameterList(List<ASTree> c) { super(c); } // public String name(int i) { return ((ASTLeaf)child(i)).token().getText(); } // public int size() { return numChildren(); } // } // // Path: src/chap6/Environment.java // public interface Environment { // void put(String name, Object value); // Object get(String name); // } // // Path: src/chap7/Function.java // public class Function { // protected ParameterList parameters; // protected BlockStmnt body; // protected Environment env; // public Function(ParameterList parameters, BlockStmnt body, Environment env) { // this.parameters = parameters; // this.body = body; // this.env = env; // } // public ParameterList parameters() { return parameters; } // public BlockStmnt body() { return body; } // public Environment makeEnv() { return new NestedEnv(env); } // @Override public String toString() { return "<fun:" + hashCode() + ">"; } // }
import stone.ast.BlockStmnt; import stone.ast.ParameterList; import chap6.Environment; import chap7.Function;
package chap11; public class OptFunction extends Function { protected int size;
// Path: src/stone/ast/BlockStmnt.java // public class BlockStmnt extends ASTList { // public BlockStmnt(List<ASTree> c) { super(c); } // } // // Path: src/stone/ast/ParameterList.java // public class ParameterList extends ASTList { // public ParameterList(List<ASTree> c) { super(c); } // public String name(int i) { return ((ASTLeaf)child(i)).token().getText(); } // public int size() { return numChildren(); } // } // // Path: src/chap6/Environment.java // public interface Environment { // void put(String name, Object value); // Object get(String name); // } // // Path: src/chap7/Function.java // public class Function { // protected ParameterList parameters; // protected BlockStmnt body; // protected Environment env; // public Function(ParameterList parameters, BlockStmnt body, Environment env) { // this.parameters = parameters; // this.body = body; // this.env = env; // } // public ParameterList parameters() { return parameters; } // public BlockStmnt body() { return body; } // public Environment makeEnv() { return new NestedEnv(env); } // @Override public String toString() { return "<fun:" + hashCode() + ">"; } // } // Path: src/chap11/OptFunction.java import stone.ast.BlockStmnt; import stone.ast.ParameterList; import chap6.Environment; import chap7.Function; package chap11; public class OptFunction extends Function { protected int size;
public OptFunction(ParameterList parameters, BlockStmnt body,
chibash/stone
src/chap11/OptFunction.java
// Path: src/stone/ast/BlockStmnt.java // public class BlockStmnt extends ASTList { // public BlockStmnt(List<ASTree> c) { super(c); } // } // // Path: src/stone/ast/ParameterList.java // public class ParameterList extends ASTList { // public ParameterList(List<ASTree> c) { super(c); } // public String name(int i) { return ((ASTLeaf)child(i)).token().getText(); } // public int size() { return numChildren(); } // } // // Path: src/chap6/Environment.java // public interface Environment { // void put(String name, Object value); // Object get(String name); // } // // Path: src/chap7/Function.java // public class Function { // protected ParameterList parameters; // protected BlockStmnt body; // protected Environment env; // public Function(ParameterList parameters, BlockStmnt body, Environment env) { // this.parameters = parameters; // this.body = body; // this.env = env; // } // public ParameterList parameters() { return parameters; } // public BlockStmnt body() { return body; } // public Environment makeEnv() { return new NestedEnv(env); } // @Override public String toString() { return "<fun:" + hashCode() + ">"; } // }
import stone.ast.BlockStmnt; import stone.ast.ParameterList; import chap6.Environment; import chap7.Function;
package chap11; public class OptFunction extends Function { protected int size;
// Path: src/stone/ast/BlockStmnt.java // public class BlockStmnt extends ASTList { // public BlockStmnt(List<ASTree> c) { super(c); } // } // // Path: src/stone/ast/ParameterList.java // public class ParameterList extends ASTList { // public ParameterList(List<ASTree> c) { super(c); } // public String name(int i) { return ((ASTLeaf)child(i)).token().getText(); } // public int size() { return numChildren(); } // } // // Path: src/chap6/Environment.java // public interface Environment { // void put(String name, Object value); // Object get(String name); // } // // Path: src/chap7/Function.java // public class Function { // protected ParameterList parameters; // protected BlockStmnt body; // protected Environment env; // public Function(ParameterList parameters, BlockStmnt body, Environment env) { // this.parameters = parameters; // this.body = body; // this.env = env; // } // public ParameterList parameters() { return parameters; } // public BlockStmnt body() { return body; } // public Environment makeEnv() { return new NestedEnv(env); } // @Override public String toString() { return "<fun:" + hashCode() + ">"; } // } // Path: src/chap11/OptFunction.java import stone.ast.BlockStmnt; import stone.ast.ParameterList; import chap6.Environment; import chap7.Function; package chap11; public class OptFunction extends Function { protected int size;
public OptFunction(ParameterList parameters, BlockStmnt body,
chibash/stone
src/chap11/OptFunction.java
// Path: src/stone/ast/BlockStmnt.java // public class BlockStmnt extends ASTList { // public BlockStmnt(List<ASTree> c) { super(c); } // } // // Path: src/stone/ast/ParameterList.java // public class ParameterList extends ASTList { // public ParameterList(List<ASTree> c) { super(c); } // public String name(int i) { return ((ASTLeaf)child(i)).token().getText(); } // public int size() { return numChildren(); } // } // // Path: src/chap6/Environment.java // public interface Environment { // void put(String name, Object value); // Object get(String name); // } // // Path: src/chap7/Function.java // public class Function { // protected ParameterList parameters; // protected BlockStmnt body; // protected Environment env; // public Function(ParameterList parameters, BlockStmnt body, Environment env) { // this.parameters = parameters; // this.body = body; // this.env = env; // } // public ParameterList parameters() { return parameters; } // public BlockStmnt body() { return body; } // public Environment makeEnv() { return new NestedEnv(env); } // @Override public String toString() { return "<fun:" + hashCode() + ">"; } // }
import stone.ast.BlockStmnt; import stone.ast.ParameterList; import chap6.Environment; import chap7.Function;
package chap11; public class OptFunction extends Function { protected int size; public OptFunction(ParameterList parameters, BlockStmnt body,
// Path: src/stone/ast/BlockStmnt.java // public class BlockStmnt extends ASTList { // public BlockStmnt(List<ASTree> c) { super(c); } // } // // Path: src/stone/ast/ParameterList.java // public class ParameterList extends ASTList { // public ParameterList(List<ASTree> c) { super(c); } // public String name(int i) { return ((ASTLeaf)child(i)).token().getText(); } // public int size() { return numChildren(); } // } // // Path: src/chap6/Environment.java // public interface Environment { // void put(String name, Object value); // Object get(String name); // } // // Path: src/chap7/Function.java // public class Function { // protected ParameterList parameters; // protected BlockStmnt body; // protected Environment env; // public Function(ParameterList parameters, BlockStmnt body, Environment env) { // this.parameters = parameters; // this.body = body; // this.env = env; // } // public ParameterList parameters() { return parameters; } // public BlockStmnt body() { return body; } // public Environment makeEnv() { return new NestedEnv(env); } // @Override public String toString() { return "<fun:" + hashCode() + ">"; } // } // Path: src/chap11/OptFunction.java import stone.ast.BlockStmnt; import stone.ast.ParameterList; import chap6.Environment; import chap7.Function; package chap11; public class OptFunction extends Function { protected int size; public OptFunction(ParameterList parameters, BlockStmnt body,
Environment env, int memorySize)
chibash/stone
src/chap10/ArrayRunner.java
// Path: src/chap7/ClosureEvaluator.java // @Require(FuncEvaluator.class) // @Reviser public class ClosureEvaluator { // @Reviser public static class FunEx extends Fun { // public FunEx(List<ASTree> c) { super(c); } // public Object eval(Environment env) { // return new Function(parameters(), body(), env); // } // } // } // // Path: src/chap8/NativeEvaluator.java // @Require(FuncEvaluator.class) // @Reviser public class NativeEvaluator { // @Reviser public static class NativeArgEx extends FuncEvaluator.ArgumentsEx { // public NativeArgEx(List<ASTree> c) { super(c); } // @Override public Object eval(Environment callerEnv, Object value) { // if (!(value instanceof NativeFunction)) // return super.eval(callerEnv, value); // // NativeFunction func = (NativeFunction)value; // int nparams = func.numOfParameters(); // if (size() != nparams) // throw new StoneException("bad number of arguments", this); // Object[] args = new Object[nparams]; // int num = 0; // for (ASTree a: this) { // ASTreeEx ae = (ASTreeEx)a; // args[num++] = ae.eval(callerEnv); // } // return func.invoke(args, this); // } // } // } // // Path: src/chap9/ClassEvaluator.java // @Require(FuncEvaluator.class) // @Reviser public class ClassEvaluator { // @Reviser public static class ClassStmntEx extends ClassStmnt { // public ClassStmntEx(List<ASTree> c) { super(c); } // public Object eval(Environment env) { // ClassInfo ci = new ClassInfo(this, env); // ((EnvEx)env).put(name(), ci); // return name(); // } // } // @Reviser public static class ClassBodyEx extends ClassBody { // public ClassBodyEx(List<ASTree> c) { super(c); } // public Object eval(Environment env) { // for (ASTree t: this) // ((ASTreeEx)t).eval(env); // return null; // } // } // @Reviser public static class DotEx extends Dot { // public DotEx(List<ASTree> c) { super(c); } // public Object eval(Environment env, Object value) { // String member = name(); // if (value instanceof ClassInfo) { // if ("new".equals(member)) { // ClassInfo ci = (ClassInfo)value; // NestedEnv e = new NestedEnv(ci.environment()); // StoneObject so = new StoneObject(e); // e.putNew("this", so); // initObject(ci, e); // return so; // } // } // else if (value instanceof StoneObject) { // try { // return ((StoneObject)value).read(member); // } catch (AccessException e) {} // } // throw new StoneException("bad member access: " + member, this); // } // protected void initObject(ClassInfo ci, Environment env) { // if (ci.superClass() != null) // initObject(ci.superClass(), env); // ((ClassBodyEx)ci.body()).eval(env); // } // } // @Reviser public static class AssignEx extends BasicEvaluator.BinaryEx { // public AssignEx(List<ASTree> c) { super(c); } // @Override // protected Object computeAssign(Environment env, Object rvalue) { // ASTree le = left(); // if (le instanceof PrimaryExpr) { // PrimaryEx p = (PrimaryEx)le; // if (p.hasPostfix(0) && p.postfix(0) instanceof Dot) { // Object t = ((PrimaryEx)le).evalSubExpr(env, 1); // if (t instanceof StoneObject) // return setField((StoneObject)t, (Dot)p.postfix(0), // rvalue); // } // } // return super.computeAssign(env, rvalue); // } // protected Object setField(StoneObject obj, Dot expr, Object rvalue) { // String name = expr.name(); // try { // obj.write(name, rvalue); // return rvalue; // } catch (AccessException e) { // throw new StoneException("bad member access " + location() // + ": " + name); // } // } // } // } // // Path: src/chap9/ClassInterpreter.java // public class ClassInterpreter extends BasicInterpreter { // public static void main(String[] args) throws ParseException { // run(new ClassParser(), new Natives().environment(new NestedEnv())); // } // }
import javassist.gluonj.util.Loader; import chap7.ClosureEvaluator; import chap8.NativeEvaluator; import chap9.ClassEvaluator; import chap9.ClassInterpreter;
package chap10; public class ArrayRunner { public static void main(String[] args) throws Throwable {
// Path: src/chap7/ClosureEvaluator.java // @Require(FuncEvaluator.class) // @Reviser public class ClosureEvaluator { // @Reviser public static class FunEx extends Fun { // public FunEx(List<ASTree> c) { super(c); } // public Object eval(Environment env) { // return new Function(parameters(), body(), env); // } // } // } // // Path: src/chap8/NativeEvaluator.java // @Require(FuncEvaluator.class) // @Reviser public class NativeEvaluator { // @Reviser public static class NativeArgEx extends FuncEvaluator.ArgumentsEx { // public NativeArgEx(List<ASTree> c) { super(c); } // @Override public Object eval(Environment callerEnv, Object value) { // if (!(value instanceof NativeFunction)) // return super.eval(callerEnv, value); // // NativeFunction func = (NativeFunction)value; // int nparams = func.numOfParameters(); // if (size() != nparams) // throw new StoneException("bad number of arguments", this); // Object[] args = new Object[nparams]; // int num = 0; // for (ASTree a: this) { // ASTreeEx ae = (ASTreeEx)a; // args[num++] = ae.eval(callerEnv); // } // return func.invoke(args, this); // } // } // } // // Path: src/chap9/ClassEvaluator.java // @Require(FuncEvaluator.class) // @Reviser public class ClassEvaluator { // @Reviser public static class ClassStmntEx extends ClassStmnt { // public ClassStmntEx(List<ASTree> c) { super(c); } // public Object eval(Environment env) { // ClassInfo ci = new ClassInfo(this, env); // ((EnvEx)env).put(name(), ci); // return name(); // } // } // @Reviser public static class ClassBodyEx extends ClassBody { // public ClassBodyEx(List<ASTree> c) { super(c); } // public Object eval(Environment env) { // for (ASTree t: this) // ((ASTreeEx)t).eval(env); // return null; // } // } // @Reviser public static class DotEx extends Dot { // public DotEx(List<ASTree> c) { super(c); } // public Object eval(Environment env, Object value) { // String member = name(); // if (value instanceof ClassInfo) { // if ("new".equals(member)) { // ClassInfo ci = (ClassInfo)value; // NestedEnv e = new NestedEnv(ci.environment()); // StoneObject so = new StoneObject(e); // e.putNew("this", so); // initObject(ci, e); // return so; // } // } // else if (value instanceof StoneObject) { // try { // return ((StoneObject)value).read(member); // } catch (AccessException e) {} // } // throw new StoneException("bad member access: " + member, this); // } // protected void initObject(ClassInfo ci, Environment env) { // if (ci.superClass() != null) // initObject(ci.superClass(), env); // ((ClassBodyEx)ci.body()).eval(env); // } // } // @Reviser public static class AssignEx extends BasicEvaluator.BinaryEx { // public AssignEx(List<ASTree> c) { super(c); } // @Override // protected Object computeAssign(Environment env, Object rvalue) { // ASTree le = left(); // if (le instanceof PrimaryExpr) { // PrimaryEx p = (PrimaryEx)le; // if (p.hasPostfix(0) && p.postfix(0) instanceof Dot) { // Object t = ((PrimaryEx)le).evalSubExpr(env, 1); // if (t instanceof StoneObject) // return setField((StoneObject)t, (Dot)p.postfix(0), // rvalue); // } // } // return super.computeAssign(env, rvalue); // } // protected Object setField(StoneObject obj, Dot expr, Object rvalue) { // String name = expr.name(); // try { // obj.write(name, rvalue); // return rvalue; // } catch (AccessException e) { // throw new StoneException("bad member access " + location() // + ": " + name); // } // } // } // } // // Path: src/chap9/ClassInterpreter.java // public class ClassInterpreter extends BasicInterpreter { // public static void main(String[] args) throws ParseException { // run(new ClassParser(), new Natives().environment(new NestedEnv())); // } // } // Path: src/chap10/ArrayRunner.java import javassist.gluonj.util.Loader; import chap7.ClosureEvaluator; import chap8.NativeEvaluator; import chap9.ClassEvaluator; import chap9.ClassInterpreter; package chap10; public class ArrayRunner { public static void main(String[] args) throws Throwable {
Loader.run(ClassInterpreter.class, args, ClassEvaluator.class,
chibash/stone
src/chap10/ArrayRunner.java
// Path: src/chap7/ClosureEvaluator.java // @Require(FuncEvaluator.class) // @Reviser public class ClosureEvaluator { // @Reviser public static class FunEx extends Fun { // public FunEx(List<ASTree> c) { super(c); } // public Object eval(Environment env) { // return new Function(parameters(), body(), env); // } // } // } // // Path: src/chap8/NativeEvaluator.java // @Require(FuncEvaluator.class) // @Reviser public class NativeEvaluator { // @Reviser public static class NativeArgEx extends FuncEvaluator.ArgumentsEx { // public NativeArgEx(List<ASTree> c) { super(c); } // @Override public Object eval(Environment callerEnv, Object value) { // if (!(value instanceof NativeFunction)) // return super.eval(callerEnv, value); // // NativeFunction func = (NativeFunction)value; // int nparams = func.numOfParameters(); // if (size() != nparams) // throw new StoneException("bad number of arguments", this); // Object[] args = new Object[nparams]; // int num = 0; // for (ASTree a: this) { // ASTreeEx ae = (ASTreeEx)a; // args[num++] = ae.eval(callerEnv); // } // return func.invoke(args, this); // } // } // } // // Path: src/chap9/ClassEvaluator.java // @Require(FuncEvaluator.class) // @Reviser public class ClassEvaluator { // @Reviser public static class ClassStmntEx extends ClassStmnt { // public ClassStmntEx(List<ASTree> c) { super(c); } // public Object eval(Environment env) { // ClassInfo ci = new ClassInfo(this, env); // ((EnvEx)env).put(name(), ci); // return name(); // } // } // @Reviser public static class ClassBodyEx extends ClassBody { // public ClassBodyEx(List<ASTree> c) { super(c); } // public Object eval(Environment env) { // for (ASTree t: this) // ((ASTreeEx)t).eval(env); // return null; // } // } // @Reviser public static class DotEx extends Dot { // public DotEx(List<ASTree> c) { super(c); } // public Object eval(Environment env, Object value) { // String member = name(); // if (value instanceof ClassInfo) { // if ("new".equals(member)) { // ClassInfo ci = (ClassInfo)value; // NestedEnv e = new NestedEnv(ci.environment()); // StoneObject so = new StoneObject(e); // e.putNew("this", so); // initObject(ci, e); // return so; // } // } // else if (value instanceof StoneObject) { // try { // return ((StoneObject)value).read(member); // } catch (AccessException e) {} // } // throw new StoneException("bad member access: " + member, this); // } // protected void initObject(ClassInfo ci, Environment env) { // if (ci.superClass() != null) // initObject(ci.superClass(), env); // ((ClassBodyEx)ci.body()).eval(env); // } // } // @Reviser public static class AssignEx extends BasicEvaluator.BinaryEx { // public AssignEx(List<ASTree> c) { super(c); } // @Override // protected Object computeAssign(Environment env, Object rvalue) { // ASTree le = left(); // if (le instanceof PrimaryExpr) { // PrimaryEx p = (PrimaryEx)le; // if (p.hasPostfix(0) && p.postfix(0) instanceof Dot) { // Object t = ((PrimaryEx)le).evalSubExpr(env, 1); // if (t instanceof StoneObject) // return setField((StoneObject)t, (Dot)p.postfix(0), // rvalue); // } // } // return super.computeAssign(env, rvalue); // } // protected Object setField(StoneObject obj, Dot expr, Object rvalue) { // String name = expr.name(); // try { // obj.write(name, rvalue); // return rvalue; // } catch (AccessException e) { // throw new StoneException("bad member access " + location() // + ": " + name); // } // } // } // } // // Path: src/chap9/ClassInterpreter.java // public class ClassInterpreter extends BasicInterpreter { // public static void main(String[] args) throws ParseException { // run(new ClassParser(), new Natives().environment(new NestedEnv())); // } // }
import javassist.gluonj.util.Loader; import chap7.ClosureEvaluator; import chap8.NativeEvaluator; import chap9.ClassEvaluator; import chap9.ClassInterpreter;
package chap10; public class ArrayRunner { public static void main(String[] args) throws Throwable {
// Path: src/chap7/ClosureEvaluator.java // @Require(FuncEvaluator.class) // @Reviser public class ClosureEvaluator { // @Reviser public static class FunEx extends Fun { // public FunEx(List<ASTree> c) { super(c); } // public Object eval(Environment env) { // return new Function(parameters(), body(), env); // } // } // } // // Path: src/chap8/NativeEvaluator.java // @Require(FuncEvaluator.class) // @Reviser public class NativeEvaluator { // @Reviser public static class NativeArgEx extends FuncEvaluator.ArgumentsEx { // public NativeArgEx(List<ASTree> c) { super(c); } // @Override public Object eval(Environment callerEnv, Object value) { // if (!(value instanceof NativeFunction)) // return super.eval(callerEnv, value); // // NativeFunction func = (NativeFunction)value; // int nparams = func.numOfParameters(); // if (size() != nparams) // throw new StoneException("bad number of arguments", this); // Object[] args = new Object[nparams]; // int num = 0; // for (ASTree a: this) { // ASTreeEx ae = (ASTreeEx)a; // args[num++] = ae.eval(callerEnv); // } // return func.invoke(args, this); // } // } // } // // Path: src/chap9/ClassEvaluator.java // @Require(FuncEvaluator.class) // @Reviser public class ClassEvaluator { // @Reviser public static class ClassStmntEx extends ClassStmnt { // public ClassStmntEx(List<ASTree> c) { super(c); } // public Object eval(Environment env) { // ClassInfo ci = new ClassInfo(this, env); // ((EnvEx)env).put(name(), ci); // return name(); // } // } // @Reviser public static class ClassBodyEx extends ClassBody { // public ClassBodyEx(List<ASTree> c) { super(c); } // public Object eval(Environment env) { // for (ASTree t: this) // ((ASTreeEx)t).eval(env); // return null; // } // } // @Reviser public static class DotEx extends Dot { // public DotEx(List<ASTree> c) { super(c); } // public Object eval(Environment env, Object value) { // String member = name(); // if (value instanceof ClassInfo) { // if ("new".equals(member)) { // ClassInfo ci = (ClassInfo)value; // NestedEnv e = new NestedEnv(ci.environment()); // StoneObject so = new StoneObject(e); // e.putNew("this", so); // initObject(ci, e); // return so; // } // } // else if (value instanceof StoneObject) { // try { // return ((StoneObject)value).read(member); // } catch (AccessException e) {} // } // throw new StoneException("bad member access: " + member, this); // } // protected void initObject(ClassInfo ci, Environment env) { // if (ci.superClass() != null) // initObject(ci.superClass(), env); // ((ClassBodyEx)ci.body()).eval(env); // } // } // @Reviser public static class AssignEx extends BasicEvaluator.BinaryEx { // public AssignEx(List<ASTree> c) { super(c); } // @Override // protected Object computeAssign(Environment env, Object rvalue) { // ASTree le = left(); // if (le instanceof PrimaryExpr) { // PrimaryEx p = (PrimaryEx)le; // if (p.hasPostfix(0) && p.postfix(0) instanceof Dot) { // Object t = ((PrimaryEx)le).evalSubExpr(env, 1); // if (t instanceof StoneObject) // return setField((StoneObject)t, (Dot)p.postfix(0), // rvalue); // } // } // return super.computeAssign(env, rvalue); // } // protected Object setField(StoneObject obj, Dot expr, Object rvalue) { // String name = expr.name(); // try { // obj.write(name, rvalue); // return rvalue; // } catch (AccessException e) { // throw new StoneException("bad member access " + location() // + ": " + name); // } // } // } // } // // Path: src/chap9/ClassInterpreter.java // public class ClassInterpreter extends BasicInterpreter { // public static void main(String[] args) throws ParseException { // run(new ClassParser(), new Natives().environment(new NestedEnv())); // } // } // Path: src/chap10/ArrayRunner.java import javassist.gluonj.util.Loader; import chap7.ClosureEvaluator; import chap8.NativeEvaluator; import chap9.ClassEvaluator; import chap9.ClassInterpreter; package chap10; public class ArrayRunner { public static void main(String[] args) throws Throwable {
Loader.run(ClassInterpreter.class, args, ClassEvaluator.class,
chibash/stone
src/chap10/ArrayRunner.java
// Path: src/chap7/ClosureEvaluator.java // @Require(FuncEvaluator.class) // @Reviser public class ClosureEvaluator { // @Reviser public static class FunEx extends Fun { // public FunEx(List<ASTree> c) { super(c); } // public Object eval(Environment env) { // return new Function(parameters(), body(), env); // } // } // } // // Path: src/chap8/NativeEvaluator.java // @Require(FuncEvaluator.class) // @Reviser public class NativeEvaluator { // @Reviser public static class NativeArgEx extends FuncEvaluator.ArgumentsEx { // public NativeArgEx(List<ASTree> c) { super(c); } // @Override public Object eval(Environment callerEnv, Object value) { // if (!(value instanceof NativeFunction)) // return super.eval(callerEnv, value); // // NativeFunction func = (NativeFunction)value; // int nparams = func.numOfParameters(); // if (size() != nparams) // throw new StoneException("bad number of arguments", this); // Object[] args = new Object[nparams]; // int num = 0; // for (ASTree a: this) { // ASTreeEx ae = (ASTreeEx)a; // args[num++] = ae.eval(callerEnv); // } // return func.invoke(args, this); // } // } // } // // Path: src/chap9/ClassEvaluator.java // @Require(FuncEvaluator.class) // @Reviser public class ClassEvaluator { // @Reviser public static class ClassStmntEx extends ClassStmnt { // public ClassStmntEx(List<ASTree> c) { super(c); } // public Object eval(Environment env) { // ClassInfo ci = new ClassInfo(this, env); // ((EnvEx)env).put(name(), ci); // return name(); // } // } // @Reviser public static class ClassBodyEx extends ClassBody { // public ClassBodyEx(List<ASTree> c) { super(c); } // public Object eval(Environment env) { // for (ASTree t: this) // ((ASTreeEx)t).eval(env); // return null; // } // } // @Reviser public static class DotEx extends Dot { // public DotEx(List<ASTree> c) { super(c); } // public Object eval(Environment env, Object value) { // String member = name(); // if (value instanceof ClassInfo) { // if ("new".equals(member)) { // ClassInfo ci = (ClassInfo)value; // NestedEnv e = new NestedEnv(ci.environment()); // StoneObject so = new StoneObject(e); // e.putNew("this", so); // initObject(ci, e); // return so; // } // } // else if (value instanceof StoneObject) { // try { // return ((StoneObject)value).read(member); // } catch (AccessException e) {} // } // throw new StoneException("bad member access: " + member, this); // } // protected void initObject(ClassInfo ci, Environment env) { // if (ci.superClass() != null) // initObject(ci.superClass(), env); // ((ClassBodyEx)ci.body()).eval(env); // } // } // @Reviser public static class AssignEx extends BasicEvaluator.BinaryEx { // public AssignEx(List<ASTree> c) { super(c); } // @Override // protected Object computeAssign(Environment env, Object rvalue) { // ASTree le = left(); // if (le instanceof PrimaryExpr) { // PrimaryEx p = (PrimaryEx)le; // if (p.hasPostfix(0) && p.postfix(0) instanceof Dot) { // Object t = ((PrimaryEx)le).evalSubExpr(env, 1); // if (t instanceof StoneObject) // return setField((StoneObject)t, (Dot)p.postfix(0), // rvalue); // } // } // return super.computeAssign(env, rvalue); // } // protected Object setField(StoneObject obj, Dot expr, Object rvalue) { // String name = expr.name(); // try { // obj.write(name, rvalue); // return rvalue; // } catch (AccessException e) { // throw new StoneException("bad member access " + location() // + ": " + name); // } // } // } // } // // Path: src/chap9/ClassInterpreter.java // public class ClassInterpreter extends BasicInterpreter { // public static void main(String[] args) throws ParseException { // run(new ClassParser(), new Natives().environment(new NestedEnv())); // } // }
import javassist.gluonj.util.Loader; import chap7.ClosureEvaluator; import chap8.NativeEvaluator; import chap9.ClassEvaluator; import chap9.ClassInterpreter;
package chap10; public class ArrayRunner { public static void main(String[] args) throws Throwable { Loader.run(ClassInterpreter.class, args, ClassEvaluator.class,
// Path: src/chap7/ClosureEvaluator.java // @Require(FuncEvaluator.class) // @Reviser public class ClosureEvaluator { // @Reviser public static class FunEx extends Fun { // public FunEx(List<ASTree> c) { super(c); } // public Object eval(Environment env) { // return new Function(parameters(), body(), env); // } // } // } // // Path: src/chap8/NativeEvaluator.java // @Require(FuncEvaluator.class) // @Reviser public class NativeEvaluator { // @Reviser public static class NativeArgEx extends FuncEvaluator.ArgumentsEx { // public NativeArgEx(List<ASTree> c) { super(c); } // @Override public Object eval(Environment callerEnv, Object value) { // if (!(value instanceof NativeFunction)) // return super.eval(callerEnv, value); // // NativeFunction func = (NativeFunction)value; // int nparams = func.numOfParameters(); // if (size() != nparams) // throw new StoneException("bad number of arguments", this); // Object[] args = new Object[nparams]; // int num = 0; // for (ASTree a: this) { // ASTreeEx ae = (ASTreeEx)a; // args[num++] = ae.eval(callerEnv); // } // return func.invoke(args, this); // } // } // } // // Path: src/chap9/ClassEvaluator.java // @Require(FuncEvaluator.class) // @Reviser public class ClassEvaluator { // @Reviser public static class ClassStmntEx extends ClassStmnt { // public ClassStmntEx(List<ASTree> c) { super(c); } // public Object eval(Environment env) { // ClassInfo ci = new ClassInfo(this, env); // ((EnvEx)env).put(name(), ci); // return name(); // } // } // @Reviser public static class ClassBodyEx extends ClassBody { // public ClassBodyEx(List<ASTree> c) { super(c); } // public Object eval(Environment env) { // for (ASTree t: this) // ((ASTreeEx)t).eval(env); // return null; // } // } // @Reviser public static class DotEx extends Dot { // public DotEx(List<ASTree> c) { super(c); } // public Object eval(Environment env, Object value) { // String member = name(); // if (value instanceof ClassInfo) { // if ("new".equals(member)) { // ClassInfo ci = (ClassInfo)value; // NestedEnv e = new NestedEnv(ci.environment()); // StoneObject so = new StoneObject(e); // e.putNew("this", so); // initObject(ci, e); // return so; // } // } // else if (value instanceof StoneObject) { // try { // return ((StoneObject)value).read(member); // } catch (AccessException e) {} // } // throw new StoneException("bad member access: " + member, this); // } // protected void initObject(ClassInfo ci, Environment env) { // if (ci.superClass() != null) // initObject(ci.superClass(), env); // ((ClassBodyEx)ci.body()).eval(env); // } // } // @Reviser public static class AssignEx extends BasicEvaluator.BinaryEx { // public AssignEx(List<ASTree> c) { super(c); } // @Override // protected Object computeAssign(Environment env, Object rvalue) { // ASTree le = left(); // if (le instanceof PrimaryExpr) { // PrimaryEx p = (PrimaryEx)le; // if (p.hasPostfix(0) && p.postfix(0) instanceof Dot) { // Object t = ((PrimaryEx)le).evalSubExpr(env, 1); // if (t instanceof StoneObject) // return setField((StoneObject)t, (Dot)p.postfix(0), // rvalue); // } // } // return super.computeAssign(env, rvalue); // } // protected Object setField(StoneObject obj, Dot expr, Object rvalue) { // String name = expr.name(); // try { // obj.write(name, rvalue); // return rvalue; // } catch (AccessException e) { // throw new StoneException("bad member access " + location() // + ": " + name); // } // } // } // } // // Path: src/chap9/ClassInterpreter.java // public class ClassInterpreter extends BasicInterpreter { // public static void main(String[] args) throws ParseException { // run(new ClassParser(), new Natives().environment(new NestedEnv())); // } // } // Path: src/chap10/ArrayRunner.java import javassist.gluonj.util.Loader; import chap7.ClosureEvaluator; import chap8.NativeEvaluator; import chap9.ClassEvaluator; import chap9.ClassInterpreter; package chap10; public class ArrayRunner { public static void main(String[] args) throws Throwable { Loader.run(ClassInterpreter.class, args, ClassEvaluator.class,
ArrayEvaluator.class, NativeEvaluator.class,
chibash/stone
src/chap10/ArrayRunner.java
// Path: src/chap7/ClosureEvaluator.java // @Require(FuncEvaluator.class) // @Reviser public class ClosureEvaluator { // @Reviser public static class FunEx extends Fun { // public FunEx(List<ASTree> c) { super(c); } // public Object eval(Environment env) { // return new Function(parameters(), body(), env); // } // } // } // // Path: src/chap8/NativeEvaluator.java // @Require(FuncEvaluator.class) // @Reviser public class NativeEvaluator { // @Reviser public static class NativeArgEx extends FuncEvaluator.ArgumentsEx { // public NativeArgEx(List<ASTree> c) { super(c); } // @Override public Object eval(Environment callerEnv, Object value) { // if (!(value instanceof NativeFunction)) // return super.eval(callerEnv, value); // // NativeFunction func = (NativeFunction)value; // int nparams = func.numOfParameters(); // if (size() != nparams) // throw new StoneException("bad number of arguments", this); // Object[] args = new Object[nparams]; // int num = 0; // for (ASTree a: this) { // ASTreeEx ae = (ASTreeEx)a; // args[num++] = ae.eval(callerEnv); // } // return func.invoke(args, this); // } // } // } // // Path: src/chap9/ClassEvaluator.java // @Require(FuncEvaluator.class) // @Reviser public class ClassEvaluator { // @Reviser public static class ClassStmntEx extends ClassStmnt { // public ClassStmntEx(List<ASTree> c) { super(c); } // public Object eval(Environment env) { // ClassInfo ci = new ClassInfo(this, env); // ((EnvEx)env).put(name(), ci); // return name(); // } // } // @Reviser public static class ClassBodyEx extends ClassBody { // public ClassBodyEx(List<ASTree> c) { super(c); } // public Object eval(Environment env) { // for (ASTree t: this) // ((ASTreeEx)t).eval(env); // return null; // } // } // @Reviser public static class DotEx extends Dot { // public DotEx(List<ASTree> c) { super(c); } // public Object eval(Environment env, Object value) { // String member = name(); // if (value instanceof ClassInfo) { // if ("new".equals(member)) { // ClassInfo ci = (ClassInfo)value; // NestedEnv e = new NestedEnv(ci.environment()); // StoneObject so = new StoneObject(e); // e.putNew("this", so); // initObject(ci, e); // return so; // } // } // else if (value instanceof StoneObject) { // try { // return ((StoneObject)value).read(member); // } catch (AccessException e) {} // } // throw new StoneException("bad member access: " + member, this); // } // protected void initObject(ClassInfo ci, Environment env) { // if (ci.superClass() != null) // initObject(ci.superClass(), env); // ((ClassBodyEx)ci.body()).eval(env); // } // } // @Reviser public static class AssignEx extends BasicEvaluator.BinaryEx { // public AssignEx(List<ASTree> c) { super(c); } // @Override // protected Object computeAssign(Environment env, Object rvalue) { // ASTree le = left(); // if (le instanceof PrimaryExpr) { // PrimaryEx p = (PrimaryEx)le; // if (p.hasPostfix(0) && p.postfix(0) instanceof Dot) { // Object t = ((PrimaryEx)le).evalSubExpr(env, 1); // if (t instanceof StoneObject) // return setField((StoneObject)t, (Dot)p.postfix(0), // rvalue); // } // } // return super.computeAssign(env, rvalue); // } // protected Object setField(StoneObject obj, Dot expr, Object rvalue) { // String name = expr.name(); // try { // obj.write(name, rvalue); // return rvalue; // } catch (AccessException e) { // throw new StoneException("bad member access " + location() // + ": " + name); // } // } // } // } // // Path: src/chap9/ClassInterpreter.java // public class ClassInterpreter extends BasicInterpreter { // public static void main(String[] args) throws ParseException { // run(new ClassParser(), new Natives().environment(new NestedEnv())); // } // }
import javassist.gluonj.util.Loader; import chap7.ClosureEvaluator; import chap8.NativeEvaluator; import chap9.ClassEvaluator; import chap9.ClassInterpreter;
package chap10; public class ArrayRunner { public static void main(String[] args) throws Throwable { Loader.run(ClassInterpreter.class, args, ClassEvaluator.class, ArrayEvaluator.class, NativeEvaluator.class,
// Path: src/chap7/ClosureEvaluator.java // @Require(FuncEvaluator.class) // @Reviser public class ClosureEvaluator { // @Reviser public static class FunEx extends Fun { // public FunEx(List<ASTree> c) { super(c); } // public Object eval(Environment env) { // return new Function(parameters(), body(), env); // } // } // } // // Path: src/chap8/NativeEvaluator.java // @Require(FuncEvaluator.class) // @Reviser public class NativeEvaluator { // @Reviser public static class NativeArgEx extends FuncEvaluator.ArgumentsEx { // public NativeArgEx(List<ASTree> c) { super(c); } // @Override public Object eval(Environment callerEnv, Object value) { // if (!(value instanceof NativeFunction)) // return super.eval(callerEnv, value); // // NativeFunction func = (NativeFunction)value; // int nparams = func.numOfParameters(); // if (size() != nparams) // throw new StoneException("bad number of arguments", this); // Object[] args = new Object[nparams]; // int num = 0; // for (ASTree a: this) { // ASTreeEx ae = (ASTreeEx)a; // args[num++] = ae.eval(callerEnv); // } // return func.invoke(args, this); // } // } // } // // Path: src/chap9/ClassEvaluator.java // @Require(FuncEvaluator.class) // @Reviser public class ClassEvaluator { // @Reviser public static class ClassStmntEx extends ClassStmnt { // public ClassStmntEx(List<ASTree> c) { super(c); } // public Object eval(Environment env) { // ClassInfo ci = new ClassInfo(this, env); // ((EnvEx)env).put(name(), ci); // return name(); // } // } // @Reviser public static class ClassBodyEx extends ClassBody { // public ClassBodyEx(List<ASTree> c) { super(c); } // public Object eval(Environment env) { // for (ASTree t: this) // ((ASTreeEx)t).eval(env); // return null; // } // } // @Reviser public static class DotEx extends Dot { // public DotEx(List<ASTree> c) { super(c); } // public Object eval(Environment env, Object value) { // String member = name(); // if (value instanceof ClassInfo) { // if ("new".equals(member)) { // ClassInfo ci = (ClassInfo)value; // NestedEnv e = new NestedEnv(ci.environment()); // StoneObject so = new StoneObject(e); // e.putNew("this", so); // initObject(ci, e); // return so; // } // } // else if (value instanceof StoneObject) { // try { // return ((StoneObject)value).read(member); // } catch (AccessException e) {} // } // throw new StoneException("bad member access: " + member, this); // } // protected void initObject(ClassInfo ci, Environment env) { // if (ci.superClass() != null) // initObject(ci.superClass(), env); // ((ClassBodyEx)ci.body()).eval(env); // } // } // @Reviser public static class AssignEx extends BasicEvaluator.BinaryEx { // public AssignEx(List<ASTree> c) { super(c); } // @Override // protected Object computeAssign(Environment env, Object rvalue) { // ASTree le = left(); // if (le instanceof PrimaryExpr) { // PrimaryEx p = (PrimaryEx)le; // if (p.hasPostfix(0) && p.postfix(0) instanceof Dot) { // Object t = ((PrimaryEx)le).evalSubExpr(env, 1); // if (t instanceof StoneObject) // return setField((StoneObject)t, (Dot)p.postfix(0), // rvalue); // } // } // return super.computeAssign(env, rvalue); // } // protected Object setField(StoneObject obj, Dot expr, Object rvalue) { // String name = expr.name(); // try { // obj.write(name, rvalue); // return rvalue; // } catch (AccessException e) { // throw new StoneException("bad member access " + location() // + ": " + name); // } // } // } // } // // Path: src/chap9/ClassInterpreter.java // public class ClassInterpreter extends BasicInterpreter { // public static void main(String[] args) throws ParseException { // run(new ClassParser(), new Natives().environment(new NestedEnv())); // } // } // Path: src/chap10/ArrayRunner.java import javassist.gluonj.util.Loader; import chap7.ClosureEvaluator; import chap8.NativeEvaluator; import chap9.ClassEvaluator; import chap9.ClassInterpreter; package chap10; public class ArrayRunner { public static void main(String[] args) throws Throwable { Loader.run(ClassInterpreter.class, args, ClassEvaluator.class, ArrayEvaluator.class, NativeEvaluator.class,
ClosureEvaluator.class);
chibash/stone
src/chap13/VmRunner.java
// Path: src/chap8/NativeEvaluator.java // @Require(FuncEvaluator.class) // @Reviser public class NativeEvaluator { // @Reviser public static class NativeArgEx extends FuncEvaluator.ArgumentsEx { // public NativeArgEx(List<ASTree> c) { super(c); } // @Override public Object eval(Environment callerEnv, Object value) { // if (!(value instanceof NativeFunction)) // return super.eval(callerEnv, value); // // NativeFunction func = (NativeFunction)value; // int nparams = func.numOfParameters(); // if (size() != nparams) // throw new StoneException("bad number of arguments", this); // Object[] args = new Object[nparams]; // int num = 0; // for (ASTree a: this) { // ASTreeEx ae = (ASTreeEx)a; // args[num++] = ae.eval(callerEnv); // } // return func.invoke(args, this); // } // } // }
import javassist.gluonj.util.Loader; import chap8.NativeEvaluator;
package chap13; public class VmRunner { public static void main(String[] args) throws Throwable { Loader.run(VmInterpreter.class, args, VmEvaluator.class,
// Path: src/chap8/NativeEvaluator.java // @Require(FuncEvaluator.class) // @Reviser public class NativeEvaluator { // @Reviser public static class NativeArgEx extends FuncEvaluator.ArgumentsEx { // public NativeArgEx(List<ASTree> c) { super(c); } // @Override public Object eval(Environment callerEnv, Object value) { // if (!(value instanceof NativeFunction)) // return super.eval(callerEnv, value); // // NativeFunction func = (NativeFunction)value; // int nparams = func.numOfParameters(); // if (size() != nparams) // throw new StoneException("bad number of arguments", this); // Object[] args = new Object[nparams]; // int num = 0; // for (ASTree a: this) { // ASTreeEx ae = (ASTreeEx)a; // args[num++] = ae.eval(callerEnv); // } // return func.invoke(args, this); // } // } // } // Path: src/chap13/VmRunner.java import javassist.gluonj.util.Loader; import chap8.NativeEvaluator; package chap13; public class VmRunner { public static void main(String[] args) throws Throwable { Loader.run(VmInterpreter.class, args, VmEvaluator.class,
NativeEvaluator.class);
chibash/stone
src/stone/Parser.java
// Path: src/stone/ast/ASTree.java // public abstract class ASTree implements Iterable<ASTree> { // public abstract ASTree child(int i); // public abstract int numChildren(); // public abstract Iterator<ASTree> children(); // public abstract String location(); // public Iterator<ASTree> iterator() { return children(); } // } // // Path: src/stone/ast/ASTLeaf.java // public class ASTLeaf extends ASTree { // private static ArrayList<ASTree> empty = new ArrayList<ASTree>(); // protected Token token; // public ASTLeaf(Token t) { token = t; } // public ASTree child(int i) { throw new IndexOutOfBoundsException(); } // public int numChildren() { return 0; } // public Iterator<ASTree> children() { return empty.iterator(); } // public String toString() { return token.getText(); } // public String location() { return "at line " + token.getLineNumber(); } // public Token token() { return token; } // } // // Path: src/stone/ast/ASTList.java // public class ASTList extends ASTree { // protected List<ASTree> children; // public ASTList(List<ASTree> list) { children = list; } // public ASTree child(int i) { return children.get(i); } // public int numChildren() { return children.size(); } // public Iterator<ASTree> children() { return children.iterator(); } // public String toString() { // StringBuilder builder = new StringBuilder(); // builder.append('('); // String sep = ""; // for (ASTree t: children) { // builder.append(sep); // sep = " "; // builder.append(t.toString()); // } // return builder.append(')').toString(); // } // public String location() { // for (ASTree t: children) { // String s = t.location(); // if (s != null) // return s; // } // return null; // } // }
import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.ArrayList; import java.lang.reflect.Method; import java.lang.reflect.Constructor; import stone.ast.ASTree; import stone.ast.ASTLeaf; import stone.ast.ASTList;
package stone; public class Parser { protected static abstract class Element {
// Path: src/stone/ast/ASTree.java // public abstract class ASTree implements Iterable<ASTree> { // public abstract ASTree child(int i); // public abstract int numChildren(); // public abstract Iterator<ASTree> children(); // public abstract String location(); // public Iterator<ASTree> iterator() { return children(); } // } // // Path: src/stone/ast/ASTLeaf.java // public class ASTLeaf extends ASTree { // private static ArrayList<ASTree> empty = new ArrayList<ASTree>(); // protected Token token; // public ASTLeaf(Token t) { token = t; } // public ASTree child(int i) { throw new IndexOutOfBoundsException(); } // public int numChildren() { return 0; } // public Iterator<ASTree> children() { return empty.iterator(); } // public String toString() { return token.getText(); } // public String location() { return "at line " + token.getLineNumber(); } // public Token token() { return token; } // } // // Path: src/stone/ast/ASTList.java // public class ASTList extends ASTree { // protected List<ASTree> children; // public ASTList(List<ASTree> list) { children = list; } // public ASTree child(int i) { return children.get(i); } // public int numChildren() { return children.size(); } // public Iterator<ASTree> children() { return children.iterator(); } // public String toString() { // StringBuilder builder = new StringBuilder(); // builder.append('('); // String sep = ""; // for (ASTree t: children) { // builder.append(sep); // sep = " "; // builder.append(t.toString()); // } // return builder.append(')').toString(); // } // public String location() { // for (ASTree t: children) { // String s = t.location(); // if (s != null) // return s; // } // return null; // } // } // Path: src/stone/Parser.java import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.ArrayList; import java.lang.reflect.Method; import java.lang.reflect.Constructor; import stone.ast.ASTree; import stone.ast.ASTLeaf; import stone.ast.ASTList; package stone; public class Parser { protected static abstract class Element {
protected abstract void parse(Lexer lexer, List<ASTree> res)
chibash/stone
src/stone/Parser.java
// Path: src/stone/ast/ASTree.java // public abstract class ASTree implements Iterable<ASTree> { // public abstract ASTree child(int i); // public abstract int numChildren(); // public abstract Iterator<ASTree> children(); // public abstract String location(); // public Iterator<ASTree> iterator() { return children(); } // } // // Path: src/stone/ast/ASTLeaf.java // public class ASTLeaf extends ASTree { // private static ArrayList<ASTree> empty = new ArrayList<ASTree>(); // protected Token token; // public ASTLeaf(Token t) { token = t; } // public ASTree child(int i) { throw new IndexOutOfBoundsException(); } // public int numChildren() { return 0; } // public Iterator<ASTree> children() { return empty.iterator(); } // public String toString() { return token.getText(); } // public String location() { return "at line " + token.getLineNumber(); } // public Token token() { return token; } // } // // Path: src/stone/ast/ASTList.java // public class ASTList extends ASTree { // protected List<ASTree> children; // public ASTList(List<ASTree> list) { children = list; } // public ASTree child(int i) { return children.get(i); } // public int numChildren() { return children.size(); } // public Iterator<ASTree> children() { return children.iterator(); } // public String toString() { // StringBuilder builder = new StringBuilder(); // builder.append('('); // String sep = ""; // for (ASTree t: children) { // builder.append(sep); // sep = " "; // builder.append(t.toString()); // } // return builder.append(')').toString(); // } // public String location() { // for (ASTree t: children) { // String s = t.location(); // if (s != null) // return s; // } // return null; // } // }
import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.ArrayList; import java.lang.reflect.Method; import java.lang.reflect.Constructor; import stone.ast.ASTree; import stone.ast.ASTLeaf; import stone.ast.ASTList;
else res.add(p.parse(lexer)); } protected boolean match(Lexer lexer) throws ParseException { return choose(lexer) != null; } protected Parser choose(Lexer lexer) throws ParseException { for (Parser p: parsers) if (p.match(lexer)) return p; return null; } protected void insert(Parser p) { Parser[] newParsers = new Parser[parsers.length + 1]; newParsers[0] = p; System.arraycopy(parsers, 0, newParsers, 1, parsers.length); parsers = newParsers; } } protected static class Repeat extends Element { protected Parser parser; protected boolean onlyOnce; protected Repeat(Parser p, boolean once) { parser = p; onlyOnce = once; } protected void parse(Lexer lexer, List<ASTree> res) throws ParseException { while (parser.match(lexer)) { ASTree t = parser.parse(lexer);
// Path: src/stone/ast/ASTree.java // public abstract class ASTree implements Iterable<ASTree> { // public abstract ASTree child(int i); // public abstract int numChildren(); // public abstract Iterator<ASTree> children(); // public abstract String location(); // public Iterator<ASTree> iterator() { return children(); } // } // // Path: src/stone/ast/ASTLeaf.java // public class ASTLeaf extends ASTree { // private static ArrayList<ASTree> empty = new ArrayList<ASTree>(); // protected Token token; // public ASTLeaf(Token t) { token = t; } // public ASTree child(int i) { throw new IndexOutOfBoundsException(); } // public int numChildren() { return 0; } // public Iterator<ASTree> children() { return empty.iterator(); } // public String toString() { return token.getText(); } // public String location() { return "at line " + token.getLineNumber(); } // public Token token() { return token; } // } // // Path: src/stone/ast/ASTList.java // public class ASTList extends ASTree { // protected List<ASTree> children; // public ASTList(List<ASTree> list) { children = list; } // public ASTree child(int i) { return children.get(i); } // public int numChildren() { return children.size(); } // public Iterator<ASTree> children() { return children.iterator(); } // public String toString() { // StringBuilder builder = new StringBuilder(); // builder.append('('); // String sep = ""; // for (ASTree t: children) { // builder.append(sep); // sep = " "; // builder.append(t.toString()); // } // return builder.append(')').toString(); // } // public String location() { // for (ASTree t: children) { // String s = t.location(); // if (s != null) // return s; // } // return null; // } // } // Path: src/stone/Parser.java import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.ArrayList; import java.lang.reflect.Method; import java.lang.reflect.Constructor; import stone.ast.ASTree; import stone.ast.ASTLeaf; import stone.ast.ASTList; else res.add(p.parse(lexer)); } protected boolean match(Lexer lexer) throws ParseException { return choose(lexer) != null; } protected Parser choose(Lexer lexer) throws ParseException { for (Parser p: parsers) if (p.match(lexer)) return p; return null; } protected void insert(Parser p) { Parser[] newParsers = new Parser[parsers.length + 1]; newParsers[0] = p; System.arraycopy(parsers, 0, newParsers, 1, parsers.length); parsers = newParsers; } } protected static class Repeat extends Element { protected Parser parser; protected boolean onlyOnce; protected Repeat(Parser p, boolean once) { parser = p; onlyOnce = once; } protected void parse(Lexer lexer, List<ASTree> res) throws ParseException { while (parser.match(lexer)) { ASTree t = parser.parse(lexer);
if (t.getClass() != ASTList.class || t.numChildren() > 0)
chibash/stone
src/stone/Parser.java
// Path: src/stone/ast/ASTree.java // public abstract class ASTree implements Iterable<ASTree> { // public abstract ASTree child(int i); // public abstract int numChildren(); // public abstract Iterator<ASTree> children(); // public abstract String location(); // public Iterator<ASTree> iterator() { return children(); } // } // // Path: src/stone/ast/ASTLeaf.java // public class ASTLeaf extends ASTree { // private static ArrayList<ASTree> empty = new ArrayList<ASTree>(); // protected Token token; // public ASTLeaf(Token t) { token = t; } // public ASTree child(int i) { throw new IndexOutOfBoundsException(); } // public int numChildren() { return 0; } // public Iterator<ASTree> children() { return empty.iterator(); } // public String toString() { return token.getText(); } // public String location() { return "at line " + token.getLineNumber(); } // public Token token() { return token; } // } // // Path: src/stone/ast/ASTList.java // public class ASTList extends ASTree { // protected List<ASTree> children; // public ASTList(List<ASTree> list) { children = list; } // public ASTree child(int i) { return children.get(i); } // public int numChildren() { return children.size(); } // public Iterator<ASTree> children() { return children.iterator(); } // public String toString() { // StringBuilder builder = new StringBuilder(); // builder.append('('); // String sep = ""; // for (ASTree t: children) { // builder.append(sep); // sep = " "; // builder.append(t.toString()); // } // return builder.append(')').toString(); // } // public String location() { // for (ASTree t: children) { // String s = t.location(); // if (s != null) // return s; // } // return null; // } // }
import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.ArrayList; import java.lang.reflect.Method; import java.lang.reflect.Constructor; import stone.ast.ASTree; import stone.ast.ASTLeaf; import stone.ast.ASTList;
protected void insert(Parser p) { Parser[] newParsers = new Parser[parsers.length + 1]; newParsers[0] = p; System.arraycopy(parsers, 0, newParsers, 1, parsers.length); parsers = newParsers; } } protected static class Repeat extends Element { protected Parser parser; protected boolean onlyOnce; protected Repeat(Parser p, boolean once) { parser = p; onlyOnce = once; } protected void parse(Lexer lexer, List<ASTree> res) throws ParseException { while (parser.match(lexer)) { ASTree t = parser.parse(lexer); if (t.getClass() != ASTList.class || t.numChildren() > 0) res.add(t); if (onlyOnce) break; } } protected boolean match(Lexer lexer) throws ParseException { return parser.match(lexer); } } protected static abstract class AToken extends Element { protected Factory factory;
// Path: src/stone/ast/ASTree.java // public abstract class ASTree implements Iterable<ASTree> { // public abstract ASTree child(int i); // public abstract int numChildren(); // public abstract Iterator<ASTree> children(); // public abstract String location(); // public Iterator<ASTree> iterator() { return children(); } // } // // Path: src/stone/ast/ASTLeaf.java // public class ASTLeaf extends ASTree { // private static ArrayList<ASTree> empty = new ArrayList<ASTree>(); // protected Token token; // public ASTLeaf(Token t) { token = t; } // public ASTree child(int i) { throw new IndexOutOfBoundsException(); } // public int numChildren() { return 0; } // public Iterator<ASTree> children() { return empty.iterator(); } // public String toString() { return token.getText(); } // public String location() { return "at line " + token.getLineNumber(); } // public Token token() { return token; } // } // // Path: src/stone/ast/ASTList.java // public class ASTList extends ASTree { // protected List<ASTree> children; // public ASTList(List<ASTree> list) { children = list; } // public ASTree child(int i) { return children.get(i); } // public int numChildren() { return children.size(); } // public Iterator<ASTree> children() { return children.iterator(); } // public String toString() { // StringBuilder builder = new StringBuilder(); // builder.append('('); // String sep = ""; // for (ASTree t: children) { // builder.append(sep); // sep = " "; // builder.append(t.toString()); // } // return builder.append(')').toString(); // } // public String location() { // for (ASTree t: children) { // String s = t.location(); // if (s != null) // return s; // } // return null; // } // } // Path: src/stone/Parser.java import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.ArrayList; import java.lang.reflect.Method; import java.lang.reflect.Constructor; import stone.ast.ASTree; import stone.ast.ASTLeaf; import stone.ast.ASTList; protected void insert(Parser p) { Parser[] newParsers = new Parser[parsers.length + 1]; newParsers[0] = p; System.arraycopy(parsers, 0, newParsers, 1, parsers.length); parsers = newParsers; } } protected static class Repeat extends Element { protected Parser parser; protected boolean onlyOnce; protected Repeat(Parser p, boolean once) { parser = p; onlyOnce = once; } protected void parse(Lexer lexer, List<ASTree> res) throws ParseException { while (parser.match(lexer)) { ASTree t = parser.parse(lexer); if (t.getClass() != ASTList.class || t.numChildren() > 0) res.add(t); if (onlyOnce) break; } } protected boolean match(Lexer lexer) throws ParseException { return parser.match(lexer); } } protected static abstract class AToken extends Element { protected Factory factory;
protected AToken(Class<? extends ASTLeaf> type) {
chibash/stone
src/chap8/NativeInterpreter.java
// Path: src/stone/ClosureParser.java // public class ClosureParser extends FuncParser { // public ClosureParser() { // primary.insertChoice(rule(Fun.class) // .sep("fun").ast(paramList).ast(block)); // } // } // // Path: src/stone/ParseException.java // public class ParseException extends Exception { // public ParseException(Token t) { // this("", t); // } // public ParseException(String msg, Token t) { // super("syntax error around " + location(t) + ". " + msg); // } // private static String location(Token t) { // if (t == Token.EOF) // return "the last line"; // else // return "\"" + t.getText() + "\" at line " + t.getLineNumber(); // } // public ParseException(IOException e) { // super(e); // } // public ParseException(String msg) { // super(msg); // } // } // // Path: src/chap6/BasicInterpreter.java // public class BasicInterpreter { // public static void main(String[] args) throws ParseException { // run(new BasicParser(), new BasicEnv()); // } // public static void run(BasicParser bp, Environment env) // throws ParseException // { // Lexer lexer = new Lexer(new CodeDialog()); // while (lexer.peek(0) != Token.EOF) { // ASTree t = bp.parse(lexer); // if (!(t instanceof NullStmnt)) { // Object r = ((BasicEvaluator.ASTreeEx)t).eval(env); // System.out.println("=> " + r); // } // } // } // } // // Path: src/chap7/NestedEnv.java // public class NestedEnv implements Environment { // protected HashMap<String,Object> values; // protected Environment outer; // public NestedEnv() { this(null); } // public NestedEnv(Environment e) { // values = new HashMap<String,Object>(); // outer = e; // } // public void setOuter(Environment e) { outer = e; } // public Object get(String name) { // Object v = values.get(name); // if (v == null && outer != null) // return outer.get(name); // else // return v; // } // public void putNew(String name, Object value) { values.put(name, value); } // public void put(String name, Object value) { // Environment e = where(name); // if (e == null) // e = this; // ((EnvEx)e).putNew(name, value); // } // public Environment where(String name) { // if (values.get(name) != null) // return this; // else if (outer == null) // return null; // else // return ((EnvEx)outer).where(name); // } // }
import stone.ClosureParser; import stone.ParseException; import chap6.BasicInterpreter; import chap7.NestedEnv;
package chap8; public class NativeInterpreter extends BasicInterpreter { public static void main(String[] args) throws ParseException {
// Path: src/stone/ClosureParser.java // public class ClosureParser extends FuncParser { // public ClosureParser() { // primary.insertChoice(rule(Fun.class) // .sep("fun").ast(paramList).ast(block)); // } // } // // Path: src/stone/ParseException.java // public class ParseException extends Exception { // public ParseException(Token t) { // this("", t); // } // public ParseException(String msg, Token t) { // super("syntax error around " + location(t) + ". " + msg); // } // private static String location(Token t) { // if (t == Token.EOF) // return "the last line"; // else // return "\"" + t.getText() + "\" at line " + t.getLineNumber(); // } // public ParseException(IOException e) { // super(e); // } // public ParseException(String msg) { // super(msg); // } // } // // Path: src/chap6/BasicInterpreter.java // public class BasicInterpreter { // public static void main(String[] args) throws ParseException { // run(new BasicParser(), new BasicEnv()); // } // public static void run(BasicParser bp, Environment env) // throws ParseException // { // Lexer lexer = new Lexer(new CodeDialog()); // while (lexer.peek(0) != Token.EOF) { // ASTree t = bp.parse(lexer); // if (!(t instanceof NullStmnt)) { // Object r = ((BasicEvaluator.ASTreeEx)t).eval(env); // System.out.println("=> " + r); // } // } // } // } // // Path: src/chap7/NestedEnv.java // public class NestedEnv implements Environment { // protected HashMap<String,Object> values; // protected Environment outer; // public NestedEnv() { this(null); } // public NestedEnv(Environment e) { // values = new HashMap<String,Object>(); // outer = e; // } // public void setOuter(Environment e) { outer = e; } // public Object get(String name) { // Object v = values.get(name); // if (v == null && outer != null) // return outer.get(name); // else // return v; // } // public void putNew(String name, Object value) { values.put(name, value); } // public void put(String name, Object value) { // Environment e = where(name); // if (e == null) // e = this; // ((EnvEx)e).putNew(name, value); // } // public Environment where(String name) { // if (values.get(name) != null) // return this; // else if (outer == null) // return null; // else // return ((EnvEx)outer).where(name); // } // } // Path: src/chap8/NativeInterpreter.java import stone.ClosureParser; import stone.ParseException; import chap6.BasicInterpreter; import chap7.NestedEnv; package chap8; public class NativeInterpreter extends BasicInterpreter { public static void main(String[] args) throws ParseException {
run(new ClosureParser(),
chibash/stone
src/chap8/NativeInterpreter.java
// Path: src/stone/ClosureParser.java // public class ClosureParser extends FuncParser { // public ClosureParser() { // primary.insertChoice(rule(Fun.class) // .sep("fun").ast(paramList).ast(block)); // } // } // // Path: src/stone/ParseException.java // public class ParseException extends Exception { // public ParseException(Token t) { // this("", t); // } // public ParseException(String msg, Token t) { // super("syntax error around " + location(t) + ". " + msg); // } // private static String location(Token t) { // if (t == Token.EOF) // return "the last line"; // else // return "\"" + t.getText() + "\" at line " + t.getLineNumber(); // } // public ParseException(IOException e) { // super(e); // } // public ParseException(String msg) { // super(msg); // } // } // // Path: src/chap6/BasicInterpreter.java // public class BasicInterpreter { // public static void main(String[] args) throws ParseException { // run(new BasicParser(), new BasicEnv()); // } // public static void run(BasicParser bp, Environment env) // throws ParseException // { // Lexer lexer = new Lexer(new CodeDialog()); // while (lexer.peek(0) != Token.EOF) { // ASTree t = bp.parse(lexer); // if (!(t instanceof NullStmnt)) { // Object r = ((BasicEvaluator.ASTreeEx)t).eval(env); // System.out.println("=> " + r); // } // } // } // } // // Path: src/chap7/NestedEnv.java // public class NestedEnv implements Environment { // protected HashMap<String,Object> values; // protected Environment outer; // public NestedEnv() { this(null); } // public NestedEnv(Environment e) { // values = new HashMap<String,Object>(); // outer = e; // } // public void setOuter(Environment e) { outer = e; } // public Object get(String name) { // Object v = values.get(name); // if (v == null && outer != null) // return outer.get(name); // else // return v; // } // public void putNew(String name, Object value) { values.put(name, value); } // public void put(String name, Object value) { // Environment e = where(name); // if (e == null) // e = this; // ((EnvEx)e).putNew(name, value); // } // public Environment where(String name) { // if (values.get(name) != null) // return this; // else if (outer == null) // return null; // else // return ((EnvEx)outer).where(name); // } // }
import stone.ClosureParser; import stone.ParseException; import chap6.BasicInterpreter; import chap7.NestedEnv;
package chap8; public class NativeInterpreter extends BasicInterpreter { public static void main(String[] args) throws ParseException { run(new ClosureParser(),
// Path: src/stone/ClosureParser.java // public class ClosureParser extends FuncParser { // public ClosureParser() { // primary.insertChoice(rule(Fun.class) // .sep("fun").ast(paramList).ast(block)); // } // } // // Path: src/stone/ParseException.java // public class ParseException extends Exception { // public ParseException(Token t) { // this("", t); // } // public ParseException(String msg, Token t) { // super("syntax error around " + location(t) + ". " + msg); // } // private static String location(Token t) { // if (t == Token.EOF) // return "the last line"; // else // return "\"" + t.getText() + "\" at line " + t.getLineNumber(); // } // public ParseException(IOException e) { // super(e); // } // public ParseException(String msg) { // super(msg); // } // } // // Path: src/chap6/BasicInterpreter.java // public class BasicInterpreter { // public static void main(String[] args) throws ParseException { // run(new BasicParser(), new BasicEnv()); // } // public static void run(BasicParser bp, Environment env) // throws ParseException // { // Lexer lexer = new Lexer(new CodeDialog()); // while (lexer.peek(0) != Token.EOF) { // ASTree t = bp.parse(lexer); // if (!(t instanceof NullStmnt)) { // Object r = ((BasicEvaluator.ASTreeEx)t).eval(env); // System.out.println("=> " + r); // } // } // } // } // // Path: src/chap7/NestedEnv.java // public class NestedEnv implements Environment { // protected HashMap<String,Object> values; // protected Environment outer; // public NestedEnv() { this(null); } // public NestedEnv(Environment e) { // values = new HashMap<String,Object>(); // outer = e; // } // public void setOuter(Environment e) { outer = e; } // public Object get(String name) { // Object v = values.get(name); // if (v == null && outer != null) // return outer.get(name); // else // return v; // } // public void putNew(String name, Object value) { values.put(name, value); } // public void put(String name, Object value) { // Environment e = where(name); // if (e == null) // e = this; // ((EnvEx)e).putNew(name, value); // } // public Environment where(String name) { // if (values.get(name) != null) // return this; // else if (outer == null) // return null; // else // return ((EnvEx)outer).where(name); // } // } // Path: src/chap8/NativeInterpreter.java import stone.ClosureParser; import stone.ParseException; import chap6.BasicInterpreter; import chap7.NestedEnv; package chap8; public class NativeInterpreter extends BasicInterpreter { public static void main(String[] args) throws ParseException { run(new ClosureParser(),
new Natives().environment(new NestedEnv()));
chibash/stone
src/chap14/TypeEnv.java
// Path: src/stone/StoneException.java // public class StoneException extends RuntimeException { // public StoneException(String m) { super(m); } // public StoneException(String m, ASTree t) { // super(m + " " + t.location()); // } // }
import java.util.Arrays; import stone.StoneException;
package chap14; public class TypeEnv { protected TypeEnv outer; protected TypeInfo[] types; public TypeEnv() { this(8, null); } public TypeEnv(int size, TypeEnv out) { outer = out; types = new TypeInfo[size]; } public TypeInfo get(int nest, int index) { if (nest == 0) if (index < types.length) return types[index]; else return null; else if (outer == null) return null; else return outer.get(nest - 1, index); } public TypeInfo put(int nest, int index, TypeInfo value) { TypeInfo oldValue; if (nest == 0) { access(index); oldValue = types[index]; types[index] = value; return oldValue; // may be null } else if (outer == null)
// Path: src/stone/StoneException.java // public class StoneException extends RuntimeException { // public StoneException(String m) { super(m); } // public StoneException(String m, ASTree t) { // super(m + " " + t.location()); // } // } // Path: src/chap14/TypeEnv.java import java.util.Arrays; import stone.StoneException; package chap14; public class TypeEnv { protected TypeEnv outer; protected TypeInfo[] types; public TypeEnv() { this(8, null); } public TypeEnv(int size, TypeEnv out) { outer = out; types = new TypeInfo[size]; } public TypeInfo get(int nest, int index) { if (nest == 0) if (index < types.length) return types[index]; else return null; else if (outer == null) return null; else return outer.get(nest - 1, index); } public TypeInfo put(int nest, int index, TypeInfo value) { TypeInfo oldValue; if (nest == 0) { access(index); oldValue = types[index]; types[index] = value; return oldValue; // may be null } else if (outer == null)
throw new StoneException("no outer type environment");
chibash/stone
src/chap8/NativeFunction.java
// Path: src/stone/StoneException.java // public class StoneException extends RuntimeException { // public StoneException(String m) { super(m); } // public StoneException(String m, ASTree t) { // super(m + " " + t.location()); // } // } // // Path: src/stone/ast/ASTree.java // public abstract class ASTree implements Iterable<ASTree> { // public abstract ASTree child(int i); // public abstract int numChildren(); // public abstract Iterator<ASTree> children(); // public abstract String location(); // public Iterator<ASTree> iterator() { return children(); } // }
import java.lang.reflect.Method; import stone.StoneException; import stone.ast.ASTree;
package chap8; public class NativeFunction { protected Method method; protected String name; protected int numParams; public NativeFunction(String n, Method m) { name = n; method = m; numParams = m.getParameterTypes().length; } @Override public String toString() { return "<native:" + hashCode() + ">"; } public int numOfParameters() { return numParams; }
// Path: src/stone/StoneException.java // public class StoneException extends RuntimeException { // public StoneException(String m) { super(m); } // public StoneException(String m, ASTree t) { // super(m + " " + t.location()); // } // } // // Path: src/stone/ast/ASTree.java // public abstract class ASTree implements Iterable<ASTree> { // public abstract ASTree child(int i); // public abstract int numChildren(); // public abstract Iterator<ASTree> children(); // public abstract String location(); // public Iterator<ASTree> iterator() { return children(); } // } // Path: src/chap8/NativeFunction.java import java.lang.reflect.Method; import stone.StoneException; import stone.ast.ASTree; package chap8; public class NativeFunction { protected Method method; protected String name; protected int numParams; public NativeFunction(String n, Method m) { name = n; method = m; numParams = m.getParameterTypes().length; } @Override public String toString() { return "<native:" + hashCode() + ">"; } public int numOfParameters() { return numParams; }
public Object invoke(Object[] args, ASTree tree) {
chibash/stone
src/chap8/NativeFunction.java
// Path: src/stone/StoneException.java // public class StoneException extends RuntimeException { // public StoneException(String m) { super(m); } // public StoneException(String m, ASTree t) { // super(m + " " + t.location()); // } // } // // Path: src/stone/ast/ASTree.java // public abstract class ASTree implements Iterable<ASTree> { // public abstract ASTree child(int i); // public abstract int numChildren(); // public abstract Iterator<ASTree> children(); // public abstract String location(); // public Iterator<ASTree> iterator() { return children(); } // }
import java.lang.reflect.Method; import stone.StoneException; import stone.ast.ASTree;
package chap8; public class NativeFunction { protected Method method; protected String name; protected int numParams; public NativeFunction(String n, Method m) { name = n; method = m; numParams = m.getParameterTypes().length; } @Override public String toString() { return "<native:" + hashCode() + ">"; } public int numOfParameters() { return numParams; } public Object invoke(Object[] args, ASTree tree) { try { return method.invoke(null, args); } catch (Exception e) {
// Path: src/stone/StoneException.java // public class StoneException extends RuntimeException { // public StoneException(String m) { super(m); } // public StoneException(String m, ASTree t) { // super(m + " " + t.location()); // } // } // // Path: src/stone/ast/ASTree.java // public abstract class ASTree implements Iterable<ASTree> { // public abstract ASTree child(int i); // public abstract int numChildren(); // public abstract Iterator<ASTree> children(); // public abstract String location(); // public Iterator<ASTree> iterator() { return children(); } // } // Path: src/chap8/NativeFunction.java import java.lang.reflect.Method; import stone.StoneException; import stone.ast.ASTree; package chap8; public class NativeFunction { protected Method method; protected String name; protected int numParams; public NativeFunction(String n, Method m) { name = n; method = m; numParams = m.getParameterTypes().length; } @Override public String toString() { return "<native:" + hashCode() + ">"; } public int numOfParameters() { return numParams; } public Object invoke(Object[] args, ASTree tree) { try { return method.invoke(null, args); } catch (Exception e) {
throw new StoneException("bad native function call: " + name, tree);
chibash/stone
src/chap5/ParserRunner.java
// Path: src/stone/ast/ASTree.java // public abstract class ASTree implements Iterable<ASTree> { // public abstract ASTree child(int i); // public abstract int numChildren(); // public abstract Iterator<ASTree> children(); // public abstract String location(); // public Iterator<ASTree> iterator() { return children(); } // }
import stone.ast.ASTree; import stone.*;
package chap5; public class ParserRunner { public static void main(String[] args) throws ParseException { Lexer l = new Lexer(new CodeDialog()); BasicParser bp = new BasicParser(); while (l.peek(0) != Token.EOF) {
// Path: src/stone/ast/ASTree.java // public abstract class ASTree implements Iterable<ASTree> { // public abstract ASTree child(int i); // public abstract int numChildren(); // public abstract Iterator<ASTree> children(); // public abstract String location(); // public Iterator<ASTree> iterator() { return children(); } // } // Path: src/chap5/ParserRunner.java import stone.ast.ASTree; import stone.*; package chap5; public class ParserRunner { public static void main(String[] args) throws ParseException { Lexer l = new Lexer(new CodeDialog()); BasicParser bp = new BasicParser(); while (l.peek(0) != Token.EOF) {
ASTree ast = bp.parse(l);
chibash/stone
src/chap14/java/currentTime.java
// Path: src/chap11/ArrayEnv.java // public class ArrayEnv implements Environment { // protected Object[] values; // protected Environment outer; // public ArrayEnv(int size, Environment out) { // values = new Object[size]; // outer = out; // } // public Symbols symbols() { throw new StoneException("no symbols"); } // public Object get(int nest, int index) { // if (nest == 0) // return values[index]; // else if (outer == null) // return null; // else // return ((EnvEx2)outer).get(nest - 1, index); // } // public void put(int nest, int index, Object value) { // if (nest == 0) // values[index] = value; // else if (outer == null) // throw new StoneException("no outer environment"); // else // ((EnvEx2)outer).put(nest - 1, index, value); // } // public Object get(String name) { error(name); return null; } // public void put(String name, Object value) { error(name); } // public void putNew(String name, Object value) { error(name); } // public Environment where(String name) { error(name); return null; } // public void setOuter(Environment e) { outer = e; } // private void error(String name) { // throw new StoneException("cannot access by name: " + name); // } // }
import chap11.ArrayEnv;
package chap14.java; public class currentTime { private static long startTime = System.currentTimeMillis();
// Path: src/chap11/ArrayEnv.java // public class ArrayEnv implements Environment { // protected Object[] values; // protected Environment outer; // public ArrayEnv(int size, Environment out) { // values = new Object[size]; // outer = out; // } // public Symbols symbols() { throw new StoneException("no symbols"); } // public Object get(int nest, int index) { // if (nest == 0) // return values[index]; // else if (outer == null) // return null; // else // return ((EnvEx2)outer).get(nest - 1, index); // } // public void put(int nest, int index, Object value) { // if (nest == 0) // values[index] = value; // else if (outer == null) // throw new StoneException("no outer environment"); // else // ((EnvEx2)outer).put(nest - 1, index, value); // } // public Object get(String name) { error(name); return null; } // public void put(String name, Object value) { error(name); } // public void putNew(String name, Object value) { error(name); } // public Environment where(String name) { error(name); return null; } // public void setOuter(Environment e) { outer = e; } // private void error(String name) { // throw new StoneException("cannot access by name: " + name); // } // } // Path: src/chap14/java/currentTime.java import chap11.ArrayEnv; package chap14.java; public class currentTime { private static long startTime = System.currentTimeMillis();
public static int m(ArrayEnv env) { return m(); }
chibash/stone
src/chap14/Runtime.java
// Path: src/chap11/ArrayEnv.java // public class ArrayEnv implements Environment { // protected Object[] values; // protected Environment outer; // public ArrayEnv(int size, Environment out) { // values = new Object[size]; // outer = out; // } // public Symbols symbols() { throw new StoneException("no symbols"); } // public Object get(int nest, int index) { // if (nest == 0) // return values[index]; // else if (outer == null) // return null; // else // return ((EnvEx2)outer).get(nest - 1, index); // } // public void put(int nest, int index, Object value) { // if (nest == 0) // values[index] = value; // else if (outer == null) // throw new StoneException("no outer environment"); // else // ((EnvEx2)outer).put(nest - 1, index, value); // } // public Object get(String name) { error(name); return null; } // public void put(String name, Object value) { error(name); } // public void putNew(String name, Object value) { error(name); } // public Environment where(String name) { error(name); return null; } // public void setOuter(Environment e) { outer = e; } // private void error(String name) { // throw new StoneException("cannot access by name: " + name); // } // }
import chap11.ArrayEnv;
package chap14; public class Runtime { public static int eq(Object a, Object b) { if (a == null) return b == null ? 1 : 0; else return a.equals(b) ? 1 : 0; } public static Object plus(Object a, Object b) { if (a instanceof Integer && b instanceof Integer) return ((Integer)a).intValue() + ((Integer)b).intValue(); else return a.toString().concat(b.toString()); }
// Path: src/chap11/ArrayEnv.java // public class ArrayEnv implements Environment { // protected Object[] values; // protected Environment outer; // public ArrayEnv(int size, Environment out) { // values = new Object[size]; // outer = out; // } // public Symbols symbols() { throw new StoneException("no symbols"); } // public Object get(int nest, int index) { // if (nest == 0) // return values[index]; // else if (outer == null) // return null; // else // return ((EnvEx2)outer).get(nest - 1, index); // } // public void put(int nest, int index, Object value) { // if (nest == 0) // values[index] = value; // else if (outer == null) // throw new StoneException("no outer environment"); // else // ((EnvEx2)outer).put(nest - 1, index, value); // } // public Object get(String name) { error(name); return null; } // public void put(String name, Object value) { error(name); } // public void putNew(String name, Object value) { error(name); } // public Environment where(String name) { error(name); return null; } // public void setOuter(Environment e) { outer = e; } // private void error(String name) { // throw new StoneException("cannot access by name: " + name); // } // } // Path: src/chap14/Runtime.java import chap11.ArrayEnv; package chap14; public class Runtime { public static int eq(Object a, Object b) { if (a == null) return b == null ? 1 : 0; else return a.equals(b) ? 1 : 0; } public static Object plus(Object a, Object b) { if (a instanceof Integer && b instanceof Integer) return ((Integer)a).intValue() + ((Integer)b).intValue(); else return a.toString().concat(b.toString()); }
public static int writeInt(ArrayEnv env, int index, int value) {