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
manuzhang/storm-benchmark
src/test/java/storm/benchmark/benchmarks/PageViewCountTest.java
// Path: src/main/java/storm/benchmark/benchmarks/common/StormBenchmark.java // public abstract class StormBenchmark implements IBenchmark { // // private static final Logger LOG = Logger.getLogger(StormBenchmark.class); // public static final String DEFAULT_TOPOLOGY_NAME = "benchmark"; // // @Override // public IMetricsCollector getMetricsCollector(Config config, StormTopology topology) { // // Set<MetricsItem> items = Sets.newHashSet( // MetricsItem.SUPERVISOR_STATS, // MetricsItem.TOPOLOGY_STATS, // MetricsItem.THROUGHPUT, // MetricsItem.SPOUT_THROUGHPUT, // MetricsItem.SPOUT_LATENCY // ); // return new BasicMetricsCollector(config, topology, items); // } // // // }
import backtype.storm.Config; import backtype.storm.generated.StormTopology; import backtype.storm.utils.Utils; import org.testng.annotations.Test; import storm.benchmark.benchmarks.common.StormBenchmark; import storm.benchmark.util.TestUtils; import static org.fest.assertions.api.Assertions.assertThat;
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 storm.benchmark.benchmarks; public class PageViewCountTest { @Test public void componentParallelismCouldBeSetThroughConfig() {
// Path: src/main/java/storm/benchmark/benchmarks/common/StormBenchmark.java // public abstract class StormBenchmark implements IBenchmark { // // private static final Logger LOG = Logger.getLogger(StormBenchmark.class); // public static final String DEFAULT_TOPOLOGY_NAME = "benchmark"; // // @Override // public IMetricsCollector getMetricsCollector(Config config, StormTopology topology) { // // Set<MetricsItem> items = Sets.newHashSet( // MetricsItem.SUPERVISOR_STATS, // MetricsItem.TOPOLOGY_STATS, // MetricsItem.THROUGHPUT, // MetricsItem.SPOUT_THROUGHPUT, // MetricsItem.SPOUT_LATENCY // ); // return new BasicMetricsCollector(config, topology, items); // } // // // } // Path: src/test/java/storm/benchmark/benchmarks/PageViewCountTest.java import backtype.storm.Config; import backtype.storm.generated.StormTopology; import backtype.storm.utils.Utils; import org.testng.annotations.Test; import storm.benchmark.benchmarks.common.StormBenchmark; import storm.benchmark.util.TestUtils; import static org.fest.assertions.api.Assertions.assertThat; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 storm.benchmark.benchmarks; public class PageViewCountTest { @Test public void componentParallelismCouldBeSetThroughConfig() {
StormBenchmark benchmark = new PageViewCount();
manuzhang/storm-benchmark
src/main/java/storm/benchmark/benchmarks/FileReadWordCount.java
// Path: src/main/java/storm/benchmark/lib/spout/FileReadSpout.java // public class FileReadSpout extends BaseRichSpout { // private static final Logger LOG = Logger.getLogger(FileReadSpout.class); // private static final long serialVersionUID = -2582705611472467172L; // // public static final String DEFAULT_FILE = "/resources/A_Tale_of_Two_City.txt"; // public static final boolean DEFAULT_ACK = false; // public static final String FIELDS = "sentence"; // // public final boolean ackEnabled; // public final FileReader reader; // private SpoutOutputCollector collector; // // private long count = 0; // // // public FileReadSpout() { // this(DEFAULT_ACK, DEFAULT_FILE); // } // // // public FileReadSpout(boolean ackEnabled) { // this(ackEnabled, DEFAULT_FILE); // } // // public FileReadSpout(boolean ackEnabled, String file) { // this(ackEnabled, new FileReader(file)); // } // // public FileReadSpout(boolean ackEnabled, FileReader reader) { // this.ackEnabled = ackEnabled; // this.reader = reader; // } // // @Override // public void open(Map conf, TopologyContext context, // SpoutOutputCollector collector) { // this.collector = collector; // } // // @Override // public void nextTuple() { // if (ackEnabled) { // collector.emit(new Values(reader.nextLine()), count); // count++; // } else { // collector.emit(new Values(reader.nextLine())); // } // } // // @Override // public void declareOutputFields(OutputFieldsDeclarer declarer) { // declarer.declare(new Fields(FIELDS)); // } // } // // Path: src/main/java/storm/benchmark/util/BenchmarkUtils.java // public final class BenchmarkUtils { // private static final Logger LOG = Logger.getLogger(BenchmarkUtils.class); // // private BenchmarkUtils() { // } // // public static double max(Iterable<Double> iterable) { // Iterator<Double> iterator = iterable.iterator(); // double max = Double.MIN_VALUE; // while (iterator.hasNext()) { // double d = iterator.next(); // if (d > max) { // max = d; // } // } // return max; // } // // public static double avg(Iterable<Double> iterable) { // Iterator<Double> iterator = iterable.iterator(); // double total = 0.0; // int num = 0; // while (iterator.hasNext()) { // total += iterator.next(); // num++; // } // return total / num; // } // // public static void putIfAbsent(Map map, Object key, Object val) { // if (!map.containsKey(key)) { // map.put(key, val); // } // } // // public static int getInt(Map map, Object key, int def) { // return Utils.getInt(Utils.get(map, key, def)); // } // // public static boolean ifAckEnabled(Config config) { // Object ackers = config.get(Config.TOPOLOGY_ACKER_EXECUTORS); // if (null == ackers) { // LOG.warn("acker executors are null"); // return false; // } // return Utils.getInt(ackers) > 0; // }}
import backtype.storm.Config; import backtype.storm.generated.StormTopology; import storm.benchmark.benchmarks.common.WordCount; import storm.benchmark.lib.spout.FileReadSpout; import storm.benchmark.util.BenchmarkUtils;
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 storm.benchmark.benchmarks; public class FileReadWordCount extends WordCount { @Override public StormTopology getTopology(Config config) {
// Path: src/main/java/storm/benchmark/lib/spout/FileReadSpout.java // public class FileReadSpout extends BaseRichSpout { // private static final Logger LOG = Logger.getLogger(FileReadSpout.class); // private static final long serialVersionUID = -2582705611472467172L; // // public static final String DEFAULT_FILE = "/resources/A_Tale_of_Two_City.txt"; // public static final boolean DEFAULT_ACK = false; // public static final String FIELDS = "sentence"; // // public final boolean ackEnabled; // public final FileReader reader; // private SpoutOutputCollector collector; // // private long count = 0; // // // public FileReadSpout() { // this(DEFAULT_ACK, DEFAULT_FILE); // } // // // public FileReadSpout(boolean ackEnabled) { // this(ackEnabled, DEFAULT_FILE); // } // // public FileReadSpout(boolean ackEnabled, String file) { // this(ackEnabled, new FileReader(file)); // } // // public FileReadSpout(boolean ackEnabled, FileReader reader) { // this.ackEnabled = ackEnabled; // this.reader = reader; // } // // @Override // public void open(Map conf, TopologyContext context, // SpoutOutputCollector collector) { // this.collector = collector; // } // // @Override // public void nextTuple() { // if (ackEnabled) { // collector.emit(new Values(reader.nextLine()), count); // count++; // } else { // collector.emit(new Values(reader.nextLine())); // } // } // // @Override // public void declareOutputFields(OutputFieldsDeclarer declarer) { // declarer.declare(new Fields(FIELDS)); // } // } // // Path: src/main/java/storm/benchmark/util/BenchmarkUtils.java // public final class BenchmarkUtils { // private static final Logger LOG = Logger.getLogger(BenchmarkUtils.class); // // private BenchmarkUtils() { // } // // public static double max(Iterable<Double> iterable) { // Iterator<Double> iterator = iterable.iterator(); // double max = Double.MIN_VALUE; // while (iterator.hasNext()) { // double d = iterator.next(); // if (d > max) { // max = d; // } // } // return max; // } // // public static double avg(Iterable<Double> iterable) { // Iterator<Double> iterator = iterable.iterator(); // double total = 0.0; // int num = 0; // while (iterator.hasNext()) { // total += iterator.next(); // num++; // } // return total / num; // } // // public static void putIfAbsent(Map map, Object key, Object val) { // if (!map.containsKey(key)) { // map.put(key, val); // } // } // // public static int getInt(Map map, Object key, int def) { // return Utils.getInt(Utils.get(map, key, def)); // } // // public static boolean ifAckEnabled(Config config) { // Object ackers = config.get(Config.TOPOLOGY_ACKER_EXECUTORS); // if (null == ackers) { // LOG.warn("acker executors are null"); // return false; // } // return Utils.getInt(ackers) > 0; // }} // Path: src/main/java/storm/benchmark/benchmarks/FileReadWordCount.java import backtype.storm.Config; import backtype.storm.generated.StormTopology; import storm.benchmark.benchmarks.common.WordCount; import storm.benchmark.lib.spout.FileReadSpout; import storm.benchmark.util.BenchmarkUtils; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 storm.benchmark.benchmarks; public class FileReadWordCount extends WordCount { @Override public StormTopology getTopology(Config config) {
spout = new FileReadSpout(BenchmarkUtils.ifAckEnabled(config));
manuzhang/storm-benchmark
src/main/java/storm/benchmark/benchmarks/FileReadWordCount.java
// Path: src/main/java/storm/benchmark/lib/spout/FileReadSpout.java // public class FileReadSpout extends BaseRichSpout { // private static final Logger LOG = Logger.getLogger(FileReadSpout.class); // private static final long serialVersionUID = -2582705611472467172L; // // public static final String DEFAULT_FILE = "/resources/A_Tale_of_Two_City.txt"; // public static final boolean DEFAULT_ACK = false; // public static final String FIELDS = "sentence"; // // public final boolean ackEnabled; // public final FileReader reader; // private SpoutOutputCollector collector; // // private long count = 0; // // // public FileReadSpout() { // this(DEFAULT_ACK, DEFAULT_FILE); // } // // // public FileReadSpout(boolean ackEnabled) { // this(ackEnabled, DEFAULT_FILE); // } // // public FileReadSpout(boolean ackEnabled, String file) { // this(ackEnabled, new FileReader(file)); // } // // public FileReadSpout(boolean ackEnabled, FileReader reader) { // this.ackEnabled = ackEnabled; // this.reader = reader; // } // // @Override // public void open(Map conf, TopologyContext context, // SpoutOutputCollector collector) { // this.collector = collector; // } // // @Override // public void nextTuple() { // if (ackEnabled) { // collector.emit(new Values(reader.nextLine()), count); // count++; // } else { // collector.emit(new Values(reader.nextLine())); // } // } // // @Override // public void declareOutputFields(OutputFieldsDeclarer declarer) { // declarer.declare(new Fields(FIELDS)); // } // } // // Path: src/main/java/storm/benchmark/util/BenchmarkUtils.java // public final class BenchmarkUtils { // private static final Logger LOG = Logger.getLogger(BenchmarkUtils.class); // // private BenchmarkUtils() { // } // // public static double max(Iterable<Double> iterable) { // Iterator<Double> iterator = iterable.iterator(); // double max = Double.MIN_VALUE; // while (iterator.hasNext()) { // double d = iterator.next(); // if (d > max) { // max = d; // } // } // return max; // } // // public static double avg(Iterable<Double> iterable) { // Iterator<Double> iterator = iterable.iterator(); // double total = 0.0; // int num = 0; // while (iterator.hasNext()) { // total += iterator.next(); // num++; // } // return total / num; // } // // public static void putIfAbsent(Map map, Object key, Object val) { // if (!map.containsKey(key)) { // map.put(key, val); // } // } // // public static int getInt(Map map, Object key, int def) { // return Utils.getInt(Utils.get(map, key, def)); // } // // public static boolean ifAckEnabled(Config config) { // Object ackers = config.get(Config.TOPOLOGY_ACKER_EXECUTORS); // if (null == ackers) { // LOG.warn("acker executors are null"); // return false; // } // return Utils.getInt(ackers) > 0; // }}
import backtype.storm.Config; import backtype.storm.generated.StormTopology; import storm.benchmark.benchmarks.common.WordCount; import storm.benchmark.lib.spout.FileReadSpout; import storm.benchmark.util.BenchmarkUtils;
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 storm.benchmark.benchmarks; public class FileReadWordCount extends WordCount { @Override public StormTopology getTopology(Config config) {
// Path: src/main/java/storm/benchmark/lib/spout/FileReadSpout.java // public class FileReadSpout extends BaseRichSpout { // private static final Logger LOG = Logger.getLogger(FileReadSpout.class); // private static final long serialVersionUID = -2582705611472467172L; // // public static final String DEFAULT_FILE = "/resources/A_Tale_of_Two_City.txt"; // public static final boolean DEFAULT_ACK = false; // public static final String FIELDS = "sentence"; // // public final boolean ackEnabled; // public final FileReader reader; // private SpoutOutputCollector collector; // // private long count = 0; // // // public FileReadSpout() { // this(DEFAULT_ACK, DEFAULT_FILE); // } // // // public FileReadSpout(boolean ackEnabled) { // this(ackEnabled, DEFAULT_FILE); // } // // public FileReadSpout(boolean ackEnabled, String file) { // this(ackEnabled, new FileReader(file)); // } // // public FileReadSpout(boolean ackEnabled, FileReader reader) { // this.ackEnabled = ackEnabled; // this.reader = reader; // } // // @Override // public void open(Map conf, TopologyContext context, // SpoutOutputCollector collector) { // this.collector = collector; // } // // @Override // public void nextTuple() { // if (ackEnabled) { // collector.emit(new Values(reader.nextLine()), count); // count++; // } else { // collector.emit(new Values(reader.nextLine())); // } // } // // @Override // public void declareOutputFields(OutputFieldsDeclarer declarer) { // declarer.declare(new Fields(FIELDS)); // } // } // // Path: src/main/java/storm/benchmark/util/BenchmarkUtils.java // public final class BenchmarkUtils { // private static final Logger LOG = Logger.getLogger(BenchmarkUtils.class); // // private BenchmarkUtils() { // } // // public static double max(Iterable<Double> iterable) { // Iterator<Double> iterator = iterable.iterator(); // double max = Double.MIN_VALUE; // while (iterator.hasNext()) { // double d = iterator.next(); // if (d > max) { // max = d; // } // } // return max; // } // // public static double avg(Iterable<Double> iterable) { // Iterator<Double> iterator = iterable.iterator(); // double total = 0.0; // int num = 0; // while (iterator.hasNext()) { // total += iterator.next(); // num++; // } // return total / num; // } // // public static void putIfAbsent(Map map, Object key, Object val) { // if (!map.containsKey(key)) { // map.put(key, val); // } // } // // public static int getInt(Map map, Object key, int def) { // return Utils.getInt(Utils.get(map, key, def)); // } // // public static boolean ifAckEnabled(Config config) { // Object ackers = config.get(Config.TOPOLOGY_ACKER_EXECUTORS); // if (null == ackers) { // LOG.warn("acker executors are null"); // return false; // } // return Utils.getInt(ackers) > 0; // }} // Path: src/main/java/storm/benchmark/benchmarks/FileReadWordCount.java import backtype.storm.Config; import backtype.storm.generated.StormTopology; import storm.benchmark.benchmarks.common.WordCount; import storm.benchmark.lib.spout.FileReadSpout; import storm.benchmark.util.BenchmarkUtils; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 storm.benchmark.benchmarks; public class FileReadWordCount extends WordCount { @Override public StormTopology getTopology(Config config) {
spout = new FileReadSpout(BenchmarkUtils.ifAckEnabled(config));
manuzhang/storm-benchmark
src/test/java/storm/benchmark/tools/SlotsTest.java
// Path: src/main/java/storm/benchmark/lib/reducer/Reducer.java // public interface Reducer<V> extends Serializable { // public V reduce(V v1, V v2); // public V zero(); // public boolean isZero(V v); // } // // Path: src/main/java/storm/benchmark/tools/SlidingWindow.java // public static class Slots<K, V> implements Serializable { // // private static final long serialVersionUID = 4858185737378394432L; // private static final Logger LOG = Logger.getLogger(Slots.class); // // private final Map<K, MutableObject[]> objToValues = new HashMap<K, MutableObject[]>(); // private final int numSlots; // private final Reducer<V> reducer; // // public Slots(Reducer reducer, int numSlots) { // if (numSlots <= 0) { // throw new IllegalArgumentException("Number of slots must be greater than zero (you requested " + numSlots + ")"); // } // this.numSlots = numSlots; // this.reducer = reducer; // } // // public void add(K obj, V val, int slot) { // if (slot < 0 || slot >= numSlots) { // throw new IllegalArgumentException("the range of slot must be [0, numSlots)"); // } // MutableObject[] values = objToValues.get(obj); // if (null == values) { // values = initSlots(numSlots, slot, val); // objToValues.put(obj, values); // } else { // MutableObject mut = values[slot]; // mut.setObject(reducer.reduce((V) mut.getObject(), val)); // } // } // // public Map<K, V> reduceByKey() { // Map<K, V> reduced = new HashMap<K, V>(); // for (K obj : objToValues.keySet()) { // reduced.put(obj, reduce(obj)); // } // return reduced; // } // // public V reduce(K obj) { // if (!objToValues.containsKey(obj)) { // LOG.warn("the object does not exist"); // return null; // } // MutableObject[] values = objToValues.get(obj); // final int len = values.length; // V val = reducer.zero(); // for (int i = 0; i < len; i++) { // MutableObject mut = values[i]; // val = reducer.reduce(val, (V) mut.getObject()); // } // return val; // } // // public void wipeSlot(int slot) { // if (slot < 0 || slot >= numSlots) { // throw new IllegalArgumentException("the range of slot must be [0, numSlots)"); // } // for (K obj : objToValues.keySet()) { // MutableObject m = objToValues.get(obj)[slot]; // if (m != null) { // m.setObject(reducer.zero()); // } // } // } // // public void wipeZeros() { // Set<K> toBeRemoved = new HashSet<K>(); // for (K obj : objToValues.keySet()) { // if (shouldBeRemoved(obj)) { // toBeRemoved.add(obj); // } // } // for (K obj : toBeRemoved) { // wipe(obj); // } // } // // public boolean contains(K obj) { // return objToValues.containsKey(obj); // } // // public MutableObject[] getValues(K obj) { // return objToValues.get(obj); // } // // private void wipe(K obj) { // objToValues.remove(obj); // } // // private boolean shouldBeRemoved(K obj) { // return reducer.isZero(reduce(obj)); // } // // private MutableObject[] initSlots(int numSlots, int slot, V val) { // MutableObject[] muts = new MutableObject[numSlots]; // for (int i = 0; i < numSlots; i++) { // if (i == slot) { // muts[i] = new MutableObject(val); // } else { // muts[i] = new MutableObject(reducer.zero()); // } // } // return muts; // } // }
import backtype.storm.utils.MutableObject; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import storm.benchmark.lib.reducer.Reducer; import static storm.benchmark.tools.SlidingWindow.Slots; import static org.fest.assertions.api.Assertions.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when;
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 storm.benchmark.tools; public class SlotsTest { private static final Object ANY_OBJECT = "ANY_OBJECT"; private static final Object ANY_VALUE = "ANY_VALUE"; private static final int ANY_NUM_SLOTS = 1; private static final int ANY_SLOT = 0;
// Path: src/main/java/storm/benchmark/lib/reducer/Reducer.java // public interface Reducer<V> extends Serializable { // public V reduce(V v1, V v2); // public V zero(); // public boolean isZero(V v); // } // // Path: src/main/java/storm/benchmark/tools/SlidingWindow.java // public static class Slots<K, V> implements Serializable { // // private static final long serialVersionUID = 4858185737378394432L; // private static final Logger LOG = Logger.getLogger(Slots.class); // // private final Map<K, MutableObject[]> objToValues = new HashMap<K, MutableObject[]>(); // private final int numSlots; // private final Reducer<V> reducer; // // public Slots(Reducer reducer, int numSlots) { // if (numSlots <= 0) { // throw new IllegalArgumentException("Number of slots must be greater than zero (you requested " + numSlots + ")"); // } // this.numSlots = numSlots; // this.reducer = reducer; // } // // public void add(K obj, V val, int slot) { // if (slot < 0 || slot >= numSlots) { // throw new IllegalArgumentException("the range of slot must be [0, numSlots)"); // } // MutableObject[] values = objToValues.get(obj); // if (null == values) { // values = initSlots(numSlots, slot, val); // objToValues.put(obj, values); // } else { // MutableObject mut = values[slot]; // mut.setObject(reducer.reduce((V) mut.getObject(), val)); // } // } // // public Map<K, V> reduceByKey() { // Map<K, V> reduced = new HashMap<K, V>(); // for (K obj : objToValues.keySet()) { // reduced.put(obj, reduce(obj)); // } // return reduced; // } // // public V reduce(K obj) { // if (!objToValues.containsKey(obj)) { // LOG.warn("the object does not exist"); // return null; // } // MutableObject[] values = objToValues.get(obj); // final int len = values.length; // V val = reducer.zero(); // for (int i = 0; i < len; i++) { // MutableObject mut = values[i]; // val = reducer.reduce(val, (V) mut.getObject()); // } // return val; // } // // public void wipeSlot(int slot) { // if (slot < 0 || slot >= numSlots) { // throw new IllegalArgumentException("the range of slot must be [0, numSlots)"); // } // for (K obj : objToValues.keySet()) { // MutableObject m = objToValues.get(obj)[slot]; // if (m != null) { // m.setObject(reducer.zero()); // } // } // } // // public void wipeZeros() { // Set<K> toBeRemoved = new HashSet<K>(); // for (K obj : objToValues.keySet()) { // if (shouldBeRemoved(obj)) { // toBeRemoved.add(obj); // } // } // for (K obj : toBeRemoved) { // wipe(obj); // } // } // // public boolean contains(K obj) { // return objToValues.containsKey(obj); // } // // public MutableObject[] getValues(K obj) { // return objToValues.get(obj); // } // // private void wipe(K obj) { // objToValues.remove(obj); // } // // private boolean shouldBeRemoved(K obj) { // return reducer.isZero(reduce(obj)); // } // // private MutableObject[] initSlots(int numSlots, int slot, V val) { // MutableObject[] muts = new MutableObject[numSlots]; // for (int i = 0; i < numSlots; i++) { // if (i == slot) { // muts[i] = new MutableObject(val); // } else { // muts[i] = new MutableObject(reducer.zero()); // } // } // return muts; // } // } // Path: src/test/java/storm/benchmark/tools/SlotsTest.java import backtype.storm.utils.MutableObject; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import storm.benchmark.lib.reducer.Reducer; import static storm.benchmark.tools.SlidingWindow.Slots; import static org.fest.assertions.api.Assertions.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 storm.benchmark.tools; public class SlotsTest { private static final Object ANY_OBJECT = "ANY_OBJECT"; private static final Object ANY_VALUE = "ANY_VALUE"; private static final int ANY_NUM_SLOTS = 1; private static final int ANY_SLOT = 0;
private static final Reducer ANY_REDUCER = mock(Reducer.class);
manuzhang/storm-benchmark
src/test/java/storm/benchmark/tools/SlotsTest.java
// Path: src/main/java/storm/benchmark/lib/reducer/Reducer.java // public interface Reducer<V> extends Serializable { // public V reduce(V v1, V v2); // public V zero(); // public boolean isZero(V v); // } // // Path: src/main/java/storm/benchmark/tools/SlidingWindow.java // public static class Slots<K, V> implements Serializable { // // private static final long serialVersionUID = 4858185737378394432L; // private static final Logger LOG = Logger.getLogger(Slots.class); // // private final Map<K, MutableObject[]> objToValues = new HashMap<K, MutableObject[]>(); // private final int numSlots; // private final Reducer<V> reducer; // // public Slots(Reducer reducer, int numSlots) { // if (numSlots <= 0) { // throw new IllegalArgumentException("Number of slots must be greater than zero (you requested " + numSlots + ")"); // } // this.numSlots = numSlots; // this.reducer = reducer; // } // // public void add(K obj, V val, int slot) { // if (slot < 0 || slot >= numSlots) { // throw new IllegalArgumentException("the range of slot must be [0, numSlots)"); // } // MutableObject[] values = objToValues.get(obj); // if (null == values) { // values = initSlots(numSlots, slot, val); // objToValues.put(obj, values); // } else { // MutableObject mut = values[slot]; // mut.setObject(reducer.reduce((V) mut.getObject(), val)); // } // } // // public Map<K, V> reduceByKey() { // Map<K, V> reduced = new HashMap<K, V>(); // for (K obj : objToValues.keySet()) { // reduced.put(obj, reduce(obj)); // } // return reduced; // } // // public V reduce(K obj) { // if (!objToValues.containsKey(obj)) { // LOG.warn("the object does not exist"); // return null; // } // MutableObject[] values = objToValues.get(obj); // final int len = values.length; // V val = reducer.zero(); // for (int i = 0; i < len; i++) { // MutableObject mut = values[i]; // val = reducer.reduce(val, (V) mut.getObject()); // } // return val; // } // // public void wipeSlot(int slot) { // if (slot < 0 || slot >= numSlots) { // throw new IllegalArgumentException("the range of slot must be [0, numSlots)"); // } // for (K obj : objToValues.keySet()) { // MutableObject m = objToValues.get(obj)[slot]; // if (m != null) { // m.setObject(reducer.zero()); // } // } // } // // public void wipeZeros() { // Set<K> toBeRemoved = new HashSet<K>(); // for (K obj : objToValues.keySet()) { // if (shouldBeRemoved(obj)) { // toBeRemoved.add(obj); // } // } // for (K obj : toBeRemoved) { // wipe(obj); // } // } // // public boolean contains(K obj) { // return objToValues.containsKey(obj); // } // // public MutableObject[] getValues(K obj) { // return objToValues.get(obj); // } // // private void wipe(K obj) { // objToValues.remove(obj); // } // // private boolean shouldBeRemoved(K obj) { // return reducer.isZero(reduce(obj)); // } // // private MutableObject[] initSlots(int numSlots, int slot, V val) { // MutableObject[] muts = new MutableObject[numSlots]; // for (int i = 0; i < numSlots; i++) { // if (i == slot) { // muts[i] = new MutableObject(val); // } else { // muts[i] = new MutableObject(reducer.zero()); // } // } // return muts; // } // }
import backtype.storm.utils.MutableObject; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import storm.benchmark.lib.reducer.Reducer; import static storm.benchmark.tools.SlidingWindow.Slots; import static org.fest.assertions.api.Assertions.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when;
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 storm.benchmark.tools; public class SlotsTest { private static final Object ANY_OBJECT = "ANY_OBJECT"; private static final Object ANY_VALUE = "ANY_VALUE"; private static final int ANY_NUM_SLOTS = 1; private static final int ANY_SLOT = 0; private static final Reducer ANY_REDUCER = mock(Reducer.class); @Test(expectedExceptions = IllegalArgumentException.class, dataProvider = "illegalNumSlots") public void lessThanOneSlotShouldThrowIAE(int numSlots) {
// Path: src/main/java/storm/benchmark/lib/reducer/Reducer.java // public interface Reducer<V> extends Serializable { // public V reduce(V v1, V v2); // public V zero(); // public boolean isZero(V v); // } // // Path: src/main/java/storm/benchmark/tools/SlidingWindow.java // public static class Slots<K, V> implements Serializable { // // private static final long serialVersionUID = 4858185737378394432L; // private static final Logger LOG = Logger.getLogger(Slots.class); // // private final Map<K, MutableObject[]> objToValues = new HashMap<K, MutableObject[]>(); // private final int numSlots; // private final Reducer<V> reducer; // // public Slots(Reducer reducer, int numSlots) { // if (numSlots <= 0) { // throw new IllegalArgumentException("Number of slots must be greater than zero (you requested " + numSlots + ")"); // } // this.numSlots = numSlots; // this.reducer = reducer; // } // // public void add(K obj, V val, int slot) { // if (slot < 0 || slot >= numSlots) { // throw new IllegalArgumentException("the range of slot must be [0, numSlots)"); // } // MutableObject[] values = objToValues.get(obj); // if (null == values) { // values = initSlots(numSlots, slot, val); // objToValues.put(obj, values); // } else { // MutableObject mut = values[slot]; // mut.setObject(reducer.reduce((V) mut.getObject(), val)); // } // } // // public Map<K, V> reduceByKey() { // Map<K, V> reduced = new HashMap<K, V>(); // for (K obj : objToValues.keySet()) { // reduced.put(obj, reduce(obj)); // } // return reduced; // } // // public V reduce(K obj) { // if (!objToValues.containsKey(obj)) { // LOG.warn("the object does not exist"); // return null; // } // MutableObject[] values = objToValues.get(obj); // final int len = values.length; // V val = reducer.zero(); // for (int i = 0; i < len; i++) { // MutableObject mut = values[i]; // val = reducer.reduce(val, (V) mut.getObject()); // } // return val; // } // // public void wipeSlot(int slot) { // if (slot < 0 || slot >= numSlots) { // throw new IllegalArgumentException("the range of slot must be [0, numSlots)"); // } // for (K obj : objToValues.keySet()) { // MutableObject m = objToValues.get(obj)[slot]; // if (m != null) { // m.setObject(reducer.zero()); // } // } // } // // public void wipeZeros() { // Set<K> toBeRemoved = new HashSet<K>(); // for (K obj : objToValues.keySet()) { // if (shouldBeRemoved(obj)) { // toBeRemoved.add(obj); // } // } // for (K obj : toBeRemoved) { // wipe(obj); // } // } // // public boolean contains(K obj) { // return objToValues.containsKey(obj); // } // // public MutableObject[] getValues(K obj) { // return objToValues.get(obj); // } // // private void wipe(K obj) { // objToValues.remove(obj); // } // // private boolean shouldBeRemoved(K obj) { // return reducer.isZero(reduce(obj)); // } // // private MutableObject[] initSlots(int numSlots, int slot, V val) { // MutableObject[] muts = new MutableObject[numSlots]; // for (int i = 0; i < numSlots; i++) { // if (i == slot) { // muts[i] = new MutableObject(val); // } else { // muts[i] = new MutableObject(reducer.zero()); // } // } // return muts; // } // } // Path: src/test/java/storm/benchmark/tools/SlotsTest.java import backtype.storm.utils.MutableObject; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import storm.benchmark.lib.reducer.Reducer; import static storm.benchmark.tools.SlidingWindow.Slots; import static org.fest.assertions.api.Assertions.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 storm.benchmark.tools; public class SlotsTest { private static final Object ANY_OBJECT = "ANY_OBJECT"; private static final Object ANY_VALUE = "ANY_VALUE"; private static final int ANY_NUM_SLOTS = 1; private static final int ANY_SLOT = 0; private static final Reducer ANY_REDUCER = mock(Reducer.class); @Test(expectedExceptions = IllegalArgumentException.class, dataProvider = "illegalNumSlots") public void lessThanOneSlotShouldThrowIAE(int numSlots) {
new Slots<Object, Object>(ANY_REDUCER, numSlots);
manuzhang/storm-benchmark
src/test/java/storm/benchmark/tools/producer/kafka/KafkaProducerTest.java
// Path: src/main/java/storm/benchmark/tools/producer/kafka/FileReadKafkaProducer.java // public class FileReadKafkaProducer extends KafkaProducer { // // public static final String FILE = "/resources/A_Tale_of_Two_City.txt"; // // @Override // public StormTopology getTopology(Config config) { // spout = new FileReadSpout(FILE); // return super.getTopology(config); // } // // static class FileReadSpout extends KafkaProducerSpout { // // private static final long serialVersionUID = -7503987913879480348L; // private final FileReader reader; // // public FileReadSpout(String file) { // this.reader = new FileReader(file); // } // // public FileReadSpout(FileReader reader) { // this.reader = reader; // } // // @Override // public void nextTuple() { // nextMessage(reader.nextLine()); // } // } // } // // Path: src/main/java/storm/benchmark/tools/producer/kafka/KafkaProducer.java // public abstract class KafkaProducer implements IProducer { // // public static final String SPOUT_ID = "spout"; // public static final String SPOUT_NUM = "component.spout_num"; // public static final String BOLT_ID = "bolt"; // public static final String BOLT_NUM = "component.bolt_num"; // public static final String BROKER_LIST = "broker.list"; // public static final String TOPIC = "topic"; // // public static final int DEFAULT_SPOUT_NUM = 4; // public static final int DEFAULT_BOLT_NUM = 4; // // protected IRichSpout spout; // protected final IRichBolt bolt = new KafkaBolt<String, String>(); // // @Override // public StormTopology getTopology(Config config) { // config.putAll(getKafkaConfig(config)); // // final int spoutNum = BenchmarkUtils.getInt(config , SPOUT_NUM, DEFAULT_SPOUT_NUM); // final int boltNum = BenchmarkUtils.getInt(config, BOLT_NUM, DEFAULT_BOLT_NUM); // // TopologyBuilder builder = new TopologyBuilder(); // builder.setSpout(SPOUT_ID, spout, spoutNum); // builder.setBolt(BOLT_ID, bolt, boltNum).localOrShuffleGrouping(SPOUT_ID); // return builder.createTopology(); // } // // public IRichSpout getSpout() { // return spout; // } // // private Map getKafkaConfig(Map options) { // Map kafkaConfig = new HashMap(); // Map brokerConfig = new HashMap(); // String brokers = (String) Utils.get(options, BROKER_LIST, "localhost:9092"); // String topic = (String) Utils.get(options, TOPIC, KafkaUtils.DEFAULT_TOPIC); // brokerConfig.put("metadata.broker.list", brokers); // brokerConfig.put("serializer.class", "kafka.serializer.StringEncoder"); // brokerConfig.put("key.serializer.class", "kafka.serializer.StringEncoder"); // brokerConfig.put("request.required.acks", "1"); // kafkaConfig.put(KafkaBolt.KAFKA_BROKER_PROPERTIES, brokerConfig); // kafkaConfig.put(KafkaBolt.TOPIC, topic); // return kafkaConfig; // } // // /** // * KafkaProducerSpout generates source data for downstream KafkaBolt to // * write into Kafka. The output fields consist of BOLT_KEY and BOLT_MESSAGE. // * BOLT_KEY will decide the Kafka partition to write into and BOLT_MESSAGE the // * actual message. Users set the number of partitions and by default messages will // * be written into each partition in a round-robin way. // */ // public static abstract class KafkaProducerSpout extends BaseRichSpout { // // private static final long serialVersionUID = -3823006007489002720L; // private final Random random; // protected SpoutOutputCollector collector; // // public KafkaProducerSpout() { // random = new Random(); // } // // @Override // public void declareOutputFields(OutputFieldsDeclarer declarer) { // declarer.declare(new Fields(FieldNameBasedTupleToKafkaMapper.BOLT_KEY, // FieldNameBasedTupleToKafkaMapper.BOLT_MESSAGE)); // } // // @Override // public void open(Map conf, TopologyContext context, SpoutOutputCollector collector) { // this.collector = collector; // } // // protected void nextMessage(String message) { // collector.emit(new Values(random.nextInt() + "", message)); // } // } // }
import backtype.storm.Config; import backtype.storm.generated.StormTopology; import backtype.storm.utils.Utils; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import storm.benchmark.tools.producer.kafka.FileReadKafkaProducer; import storm.benchmark.tools.producer.kafka.PageViewKafkaProducer; import storm.benchmark.tools.producer.kafka.KafkaProducer; import storm.benchmark.util.TestUtils; import static org.fest.assertions.api.Assertions.assertThat;
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 storm.benchmark.tools.producer.kafka; public class KafkaProducerTest { @Test(dataProvider = "getKafkaProducer")
// Path: src/main/java/storm/benchmark/tools/producer/kafka/FileReadKafkaProducer.java // public class FileReadKafkaProducer extends KafkaProducer { // // public static final String FILE = "/resources/A_Tale_of_Two_City.txt"; // // @Override // public StormTopology getTopology(Config config) { // spout = new FileReadSpout(FILE); // return super.getTopology(config); // } // // static class FileReadSpout extends KafkaProducerSpout { // // private static final long serialVersionUID = -7503987913879480348L; // private final FileReader reader; // // public FileReadSpout(String file) { // this.reader = new FileReader(file); // } // // public FileReadSpout(FileReader reader) { // this.reader = reader; // } // // @Override // public void nextTuple() { // nextMessage(reader.nextLine()); // } // } // } // // Path: src/main/java/storm/benchmark/tools/producer/kafka/KafkaProducer.java // public abstract class KafkaProducer implements IProducer { // // public static final String SPOUT_ID = "spout"; // public static final String SPOUT_NUM = "component.spout_num"; // public static final String BOLT_ID = "bolt"; // public static final String BOLT_NUM = "component.bolt_num"; // public static final String BROKER_LIST = "broker.list"; // public static final String TOPIC = "topic"; // // public static final int DEFAULT_SPOUT_NUM = 4; // public static final int DEFAULT_BOLT_NUM = 4; // // protected IRichSpout spout; // protected final IRichBolt bolt = new KafkaBolt<String, String>(); // // @Override // public StormTopology getTopology(Config config) { // config.putAll(getKafkaConfig(config)); // // final int spoutNum = BenchmarkUtils.getInt(config , SPOUT_NUM, DEFAULT_SPOUT_NUM); // final int boltNum = BenchmarkUtils.getInt(config, BOLT_NUM, DEFAULT_BOLT_NUM); // // TopologyBuilder builder = new TopologyBuilder(); // builder.setSpout(SPOUT_ID, spout, spoutNum); // builder.setBolt(BOLT_ID, bolt, boltNum).localOrShuffleGrouping(SPOUT_ID); // return builder.createTopology(); // } // // public IRichSpout getSpout() { // return spout; // } // // private Map getKafkaConfig(Map options) { // Map kafkaConfig = new HashMap(); // Map brokerConfig = new HashMap(); // String brokers = (String) Utils.get(options, BROKER_LIST, "localhost:9092"); // String topic = (String) Utils.get(options, TOPIC, KafkaUtils.DEFAULT_TOPIC); // brokerConfig.put("metadata.broker.list", brokers); // brokerConfig.put("serializer.class", "kafka.serializer.StringEncoder"); // brokerConfig.put("key.serializer.class", "kafka.serializer.StringEncoder"); // brokerConfig.put("request.required.acks", "1"); // kafkaConfig.put(KafkaBolt.KAFKA_BROKER_PROPERTIES, brokerConfig); // kafkaConfig.put(KafkaBolt.TOPIC, topic); // return kafkaConfig; // } // // /** // * KafkaProducerSpout generates source data for downstream KafkaBolt to // * write into Kafka. The output fields consist of BOLT_KEY and BOLT_MESSAGE. // * BOLT_KEY will decide the Kafka partition to write into and BOLT_MESSAGE the // * actual message. Users set the number of partitions and by default messages will // * be written into each partition in a round-robin way. // */ // public static abstract class KafkaProducerSpout extends BaseRichSpout { // // private static final long serialVersionUID = -3823006007489002720L; // private final Random random; // protected SpoutOutputCollector collector; // // public KafkaProducerSpout() { // random = new Random(); // } // // @Override // public void declareOutputFields(OutputFieldsDeclarer declarer) { // declarer.declare(new Fields(FieldNameBasedTupleToKafkaMapper.BOLT_KEY, // FieldNameBasedTupleToKafkaMapper.BOLT_MESSAGE)); // } // // @Override // public void open(Map conf, TopologyContext context, SpoutOutputCollector collector) { // this.collector = collector; // } // // protected void nextMessage(String message) { // collector.emit(new Values(random.nextInt() + "", message)); // } // } // } // Path: src/test/java/storm/benchmark/tools/producer/kafka/KafkaProducerTest.java import backtype.storm.Config; import backtype.storm.generated.StormTopology; import backtype.storm.utils.Utils; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import storm.benchmark.tools.producer.kafka.FileReadKafkaProducer; import storm.benchmark.tools.producer.kafka.PageViewKafkaProducer; import storm.benchmark.tools.producer.kafka.KafkaProducer; import storm.benchmark.util.TestUtils; import static org.fest.assertions.api.Assertions.assertThat; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 storm.benchmark.tools.producer.kafka; public class KafkaProducerTest { @Test(dataProvider = "getKafkaProducer")
public void componentParallelismCouldBeSetThroughConfig(KafkaProducer producer) {
manuzhang/storm-benchmark
src/test/java/storm/benchmark/tools/producer/kafka/FileReadKafkaProducerTest.java
// Path: src/main/java/storm/benchmark/tools/producer/kafka/FileReadKafkaProducer.java // static class FileReadSpout extends KafkaProducerSpout { // // private static final long serialVersionUID = -7503987913879480348L; // private final FileReader reader; // // public FileReadSpout(String file) { // this.reader = new FileReader(file); // } // // public FileReadSpout(FileReader reader) { // this.reader = reader; // } // // @Override // public void nextTuple() { // nextMessage(reader.nextLine()); // } // }
import static storm.benchmark.tools.producer.kafka.FileReadKafkaProducer.FileReadSpout; import backtype.storm.Config; import backtype.storm.spout.SpoutOutputCollector; import backtype.storm.task.TopologyContext; import backtype.storm.tuple.Values; import org.testng.annotations.Test; import storm.benchmark.tools.FileReader; import java.util.HashMap; import java.util.Map; import static org.fest.assertions.api.Assertions.assertThat; import static org.mockito.Mockito.*;
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 storm.benchmark.tools.producer.kafka; public class FileReadKafkaProducerTest { private static final Map ANY_CONF = new HashMap(); @Test public void spoutShouldBeKafkaFileReadSpout() { KafkaProducer producer = new FileReadKafkaProducer(); producer.getTopology(new Config());
// Path: src/main/java/storm/benchmark/tools/producer/kafka/FileReadKafkaProducer.java // static class FileReadSpout extends KafkaProducerSpout { // // private static final long serialVersionUID = -7503987913879480348L; // private final FileReader reader; // // public FileReadSpout(String file) { // this.reader = new FileReader(file); // } // // public FileReadSpout(FileReader reader) { // this.reader = reader; // } // // @Override // public void nextTuple() { // nextMessage(reader.nextLine()); // } // } // Path: src/test/java/storm/benchmark/tools/producer/kafka/FileReadKafkaProducerTest.java import static storm.benchmark.tools.producer.kafka.FileReadKafkaProducer.FileReadSpout; import backtype.storm.Config; import backtype.storm.spout.SpoutOutputCollector; import backtype.storm.task.TopologyContext; import backtype.storm.tuple.Values; import org.testng.annotations.Test; import storm.benchmark.tools.FileReader; import java.util.HashMap; import java.util.Map; import static org.fest.assertions.api.Assertions.assertThat; import static org.mockito.Mockito.*; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 storm.benchmark.tools.producer.kafka; public class FileReadKafkaProducerTest { private static final Map ANY_CONF = new HashMap(); @Test public void spoutShouldBeKafkaFileReadSpout() { KafkaProducer producer = new FileReadKafkaProducer(); producer.getTopology(new Config());
assertThat(producer.getSpout()).isInstanceOf(FileReadSpout.class);
manuzhang/storm-benchmark
src/test/java/storm/benchmark/lib/bolt/FilterBoltTest.java
// Path: src/test/java/storm/benchmark/util/MockTupleHelpers.java // public final class MockTupleHelpers { // public static final String ANY_COMPONENT_ID = "any_component_id"; // public static final String ANY_STREAM_ID = "any_stream_id"; // // private MockTupleHelpers() { // } // // public static Tuple mockTickTuple() { // return mockTuple(Constants.SYSTEM_COMPONENT_ID, Constants.SYSTEM_TICK_STREAM_ID); // } // // public static Tuple mockAnyTuple() { // return mockTuple(ANY_COMPONENT_ID, ANY_STREAM_ID); // } // // public static Tuple mockTuple(String componentId, String streamId) { // Tuple tuple = mock(Tuple.class); // when(tuple.getSourceComponent()).thenReturn(componentId); // when(tuple.getSourceStreamId()).thenReturn(streamId); // return tuple; // } // }
import backtype.storm.topology.BasicOutputCollector; import backtype.storm.topology.OutputFieldsDeclarer; import backtype.storm.tuple.Fields; import backtype.storm.tuple.Tuple; import backtype.storm.tuple.Values; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import storm.benchmark.util.MockTupleHelpers; import static org.mockito.Matchers.any; import static org.mockito.Mockito.*;
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 storm.benchmark.lib.bolt; public class FilterBoltTest { private static final String TO_FILTER = "to_filter"; private static final String NON_FILTER = "non_filter"; private FilterBolt bolt; private Tuple tuple; private BasicOutputCollector collector; private OutputFieldsDeclarer declarer; @BeforeMethod public void setUp() { bolt = new FilterBolt(TO_FILTER);
// Path: src/test/java/storm/benchmark/util/MockTupleHelpers.java // public final class MockTupleHelpers { // public static final String ANY_COMPONENT_ID = "any_component_id"; // public static final String ANY_STREAM_ID = "any_stream_id"; // // private MockTupleHelpers() { // } // // public static Tuple mockTickTuple() { // return mockTuple(Constants.SYSTEM_COMPONENT_ID, Constants.SYSTEM_TICK_STREAM_ID); // } // // public static Tuple mockAnyTuple() { // return mockTuple(ANY_COMPONENT_ID, ANY_STREAM_ID); // } // // public static Tuple mockTuple(String componentId, String streamId) { // Tuple tuple = mock(Tuple.class); // when(tuple.getSourceComponent()).thenReturn(componentId); // when(tuple.getSourceStreamId()).thenReturn(streamId); // return tuple; // } // } // Path: src/test/java/storm/benchmark/lib/bolt/FilterBoltTest.java import backtype.storm.topology.BasicOutputCollector; import backtype.storm.topology.OutputFieldsDeclarer; import backtype.storm.tuple.Fields; import backtype.storm.tuple.Tuple; import backtype.storm.tuple.Values; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import storm.benchmark.util.MockTupleHelpers; import static org.mockito.Matchers.any; import static org.mockito.Mockito.*; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 storm.benchmark.lib.bolt; public class FilterBoltTest { private static final String TO_FILTER = "to_filter"; private static final String NON_FILTER = "non_filter"; private FilterBolt bolt; private Tuple tuple; private BasicOutputCollector collector; private OutputFieldsDeclarer declarer; @BeforeMethod public void setUp() { bolt = new FilterBolt(TO_FILTER);
tuple = MockTupleHelpers.mockAnyTuple();
coverity/pie
examples/spring-security/src/main/java/com/coverity/security/pie/plugin/springsecurity/PieAccessDecisionManager.java
// Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/model/Role.java // public enum Role { // GUEST, USER, ADMIN, SYSTEM; // }
import java.util.Collection; import org.aopalliance.intercept.MethodInvocation; import org.springframework.security.access.AccessDecisionManager; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.access.ConfigAttribute; import org.springframework.security.authentication.InsufficientAuthenticationException; import org.springframework.security.core.Authentication; import com.coverity.security.pie.example.model.Role;
package com.coverity.security.pie.plugin.springsecurity; public class PieAccessDecisionManager implements AccessDecisionManager { private final SpringSecurityPolicyEnforcer policyEnforcer; public PieAccessDecisionManager(SpringSecurityPolicyEnforcer policyEnforcer) { this.policyEnforcer = policyEnforcer; } @Override public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException { if (!(object instanceof MethodInvocation)) { throw new IllegalStateException("Only operates on methods."); } MethodInvocation methodInvocation = (MethodInvocation)object;
// Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/model/Role.java // public enum Role { // GUEST, USER, ADMIN, SYSTEM; // } // Path: examples/spring-security/src/main/java/com/coverity/security/pie/plugin/springsecurity/PieAccessDecisionManager.java import java.util.Collection; import org.aopalliance.intercept.MethodInvocation; import org.springframework.security.access.AccessDecisionManager; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.access.ConfigAttribute; import org.springframework.security.authentication.InsufficientAuthenticationException; import org.springframework.security.core.Authentication; import com.coverity.security.pie.example.model.Role; package com.coverity.security.pie.plugin.springsecurity; public class PieAccessDecisionManager implements AccessDecisionManager { private final SpringSecurityPolicyEnforcer policyEnforcer; public PieAccessDecisionManager(SpringSecurityPolicyEnforcer policyEnforcer) { this.policyEnforcer = policyEnforcer; } @Override public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException { if (!(object instanceof MethodInvocation)) { throw new IllegalStateException("Only operates on methods."); } MethodInvocation methodInvocation = (MethodInvocation)object;
Role role = null;
coverity/pie
pie-sm/src/test/java/com/coverity/security/pie/policy/securitymanager/SecurityManagerPolicyEnforcerTest.java
// Path: pie-core/src/main/java/com/coverity/security/pie/core/PieConfig.java // public class PieConfig { // // private final Properties properties = new Properties(); // // public PieConfig() { // loadProps(this.getClass().getClassLoader().getResource("pieConfig.default.properties")); // File propFile = new File("pieConfig.properties"); // if (propFile.exists()) { // try { // loadProps(propFile.toURI().toURL()); // } catch (MalformedURLException e) { // throw new RuntimeException(e); // } // } else { // loadProps(this.getClass().getClassLoader().getResource("pieConfig.properties")); // } // } // public PieConfig(URL propertiesUrl) { // loadProps(this.getClass().getClassLoader().getResource("pieConfig.default.properties")); // loadProps(propertiesUrl); // } // private void loadProps(URL propertiesUrl) { // if (propertiesUrl != null) { // InputStream is = null; // try { // is = propertiesUrl.openStream(); // if (is != null) { // properties.load(is); // is.close(); // } // } catch (IOException e) { // IOUtil.closeSilently(is); // throw new RuntimeException(e); // } // } // // } // // public Properties getProperties() { // return properties; // } // // private boolean getBoolean(String prop, boolean defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Boolean.parseBoolean(v); // } // // private String getProperty(String name) { // return properties.getProperty("pie." + name); // } // // public boolean isEnabled() { // return getBoolean("enabled", true); // } // // public boolean isRegenerateOnShutdown() { // return getBoolean("regenerateOnShutdown", true); // } // // public boolean isAdminInterfaceEnabled() { // return getBoolean("admininterface.enabled", false); // } // // public boolean isLoggingEnabled() { return getBoolean("loggingEnabled", false); } // // public String getLogPath() { return getProperty("logPath"); } // }
import com.coverity.security.pie.core.PieConfig; import org.testng.annotations.Test; import javax.servlet.ServletContext; import java.security.Permission; import static org.easymock.EasyMock.*; import static org.testng.Assert.*;
package com.coverity.security.pie.policy.securitymanager; public class SecurityManagerPolicyEnforcerTest { @Test public void testApplyPolicy() { // Setup a stub SecurityManager that will let us clear out the Java policy set later assertNull(System.getSecurityManager()); System.setSecurityManager(new StubSecurityManager()); try { SecurityManagerPolicyEnforcer policyEnforcer = new SecurityManagerPolicyEnforcer();
// Path: pie-core/src/main/java/com/coverity/security/pie/core/PieConfig.java // public class PieConfig { // // private final Properties properties = new Properties(); // // public PieConfig() { // loadProps(this.getClass().getClassLoader().getResource("pieConfig.default.properties")); // File propFile = new File("pieConfig.properties"); // if (propFile.exists()) { // try { // loadProps(propFile.toURI().toURL()); // } catch (MalformedURLException e) { // throw new RuntimeException(e); // } // } else { // loadProps(this.getClass().getClassLoader().getResource("pieConfig.properties")); // } // } // public PieConfig(URL propertiesUrl) { // loadProps(this.getClass().getClassLoader().getResource("pieConfig.default.properties")); // loadProps(propertiesUrl); // } // private void loadProps(URL propertiesUrl) { // if (propertiesUrl != null) { // InputStream is = null; // try { // is = propertiesUrl.openStream(); // if (is != null) { // properties.load(is); // is.close(); // } // } catch (IOException e) { // IOUtil.closeSilently(is); // throw new RuntimeException(e); // } // } // // } // // public Properties getProperties() { // return properties; // } // // private boolean getBoolean(String prop, boolean defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Boolean.parseBoolean(v); // } // // private String getProperty(String name) { // return properties.getProperty("pie." + name); // } // // public boolean isEnabled() { // return getBoolean("enabled", true); // } // // public boolean isRegenerateOnShutdown() { // return getBoolean("regenerateOnShutdown", true); // } // // public boolean isAdminInterfaceEnabled() { // return getBoolean("admininterface.enabled", false); // } // // public boolean isLoggingEnabled() { return getBoolean("loggingEnabled", false); } // // public String getLogPath() { return getProperty("logPath"); } // } // Path: pie-sm/src/test/java/com/coverity/security/pie/policy/securitymanager/SecurityManagerPolicyEnforcerTest.java import com.coverity.security.pie.core.PieConfig; import org.testng.annotations.Test; import javax.servlet.ServletContext; import java.security.Permission; import static org.easymock.EasyMock.*; import static org.testng.Assert.*; package com.coverity.security.pie.policy.securitymanager; public class SecurityManagerPolicyEnforcerTest { @Test public void testApplyPolicy() { // Setup a stub SecurityManager that will let us clear out the Java policy set later assertNull(System.getSecurityManager()); System.setSecurityManager(new StubSecurityManager()); try { SecurityManagerPolicyEnforcer policyEnforcer = new SecurityManagerPolicyEnforcer();
policyEnforcer.init(new PieConfig());
coverity/pie
examples/spring-security/src/main/java/com/coverity/security/pie/example/util/DoPrivileged.java
// Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/model/Role.java // public enum Role { // GUEST, USER, ADMIN, SYSTEM; // }
import java.util.Arrays; import java.util.concurrent.Callable; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken; import com.coverity.security.pie.example.model.Role;
package com.coverity.security.pie.example.util; public class DoPrivileged { public static <T> T asSystem(Callable<T> callable) throws Exception { final SecurityContext priorContext = SecurityContextHolder.getContext(); try { SecurityContextHolder.setContext(SecurityContextHolder.createEmptyContext()); PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(
// Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/model/Role.java // public enum Role { // GUEST, USER, ADMIN, SYSTEM; // } // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/util/DoPrivileged.java import java.util.Arrays; import java.util.concurrent.Callable; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken; import com.coverity.security.pie.example.model.Role; package com.coverity.security.pie.example.util; public class DoPrivileged { public static <T> T asSystem(Callable<T> callable) throws Exception { final SecurityContext priorContext = SecurityContextHolder.getContext(); try { SecurityContextHolder.setContext(SecurityContextHolder.createEmptyContext()); PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(
"system", null, Arrays.asList(new SimpleGrantedAuthority(Role.SYSTEM.toString())));
coverity/pie
pie-sm/src/main/java/com/coverity/security/pie/policy/securitymanager/DynamicJavaPolicy.java
// Path: pie-core/src/main/java/com/coverity/security/pie/core/PolicyConfig.java // public class PolicyConfig { // private final String name; // private final PieConfig pieConfig; // // public PolicyConfig(String name, PieConfig pieConfig) { // this.name = name; // this.pieConfig = pieConfig; // } // // public boolean isEnabled() { // return getBoolean("isEnabled", true); // } // // public boolean isReportOnlyMode() { // return getBoolean("isReportOnlyMode", true); // } // // public boolean isCollapseEnabled() { // return getBoolean("isCollapseEnabled", true); // } // // public URL getPolicyFile() { // String policyFile = getProperty("policyFile"); // if (policyFile != null) { // try { // return new URL(policyFile); // } catch (MalformedURLException e) { // throw new IllegalStateException("Invalid policy URL: " + policyFile); // } // } // URL resource = this.getClass().getClassLoader().getResource(name + ".policy"); // if (resource != null) { // return resource; // } // String catalinaHome = System.getProperty("catalina.home"); // if (catalinaHome != null) { // try { // return new File(catalinaHome + File.separatorChar + "conf" + File.separatorChar + name + ".policy").toURI().toURL(); // } catch (MalformedURLException e) { // throw new IllegalStateException("Could not build default policy file path."); // } // } // // // Default to file in the CWD // try { // return new File(name + ".policy").toURI().toURL(); // } catch (MalformedURLException e) { // throw new RuntimeException(e); // } // } // // public boolean getBoolean(String prop, boolean defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Boolean.parseBoolean(v); // } // public int getInteger(String prop, int defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Integer.parseInt(v); // } // // // public String getProperty(String name) { // return pieConfig.getProperties().getProperty(this.name + "." + name); // } // } // // Path: pie-core/src/main/java/com/coverity/security/pie/util/IOUtil.java // public class IOUtil { // public static void closeSilently(Closeable closeable) { // if (closeable != null) { // try { // closeable.close(); // } catch (IOException e) { // // Do nothing // } // } // } // // public static String readFile(File file) throws IOException { // return toString(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8)); // } // public static String readFile(String file) throws IOException { // return toString(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8)); // } // public static String readFile(URL file) throws IOException { // return toString(file.openStream()); // } // // public static String toString(InputStream is) throws IOException { // try { // return toString(new InputStreamReader(is, StandardCharsets.UTF_8)); // } finally { // closeSilently(is); // } // } // public static String toString(Reader reader) throws IOException { // StringBuilder sb = new StringBuilder(); // try { // char buffer[] = new char[4096]; // int n; // while ((n = reader.read(buffer)) > 0) { // sb.append(buffer, 0, n); // } // reader.close(); // } catch (IOException e) { // closeSilently(reader); // throw e; // } // return sb.toString(); // } // // // public static void writeFile(File file, String content) throws IOException { // writeFile(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8), content); // } // private static void writeFile(Writer fw, String content) throws IOException { // try { // fw.write(content); // fw.close(); // } catch (IOException e) { // closeSilently(fw); // throw e; // } // } // // }
import java.io.IOException; import java.io.InputStream; import java.security.GeneralSecurityException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.Permission; import java.security.Policy; import java.security.ProtectionDomain; import java.security.PublicKey; import java.security.SignatureException; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.util.ArrayList; import java.util.Collection; import com.coverity.security.pie.core.PolicyConfig; import com.coverity.security.pie.util.IOUtil;
package com.coverity.security.pie.policy.securitymanager; /** * An implementation of the Java SecurityManager Policy class, which delegates policy decisions to the PIE policy. * Whitelists permissions for PIE classes based on their certificate signature. */ public class DynamicJavaPolicy extends Policy { private final Collection<Policy> parentPolicies; private final PublicKey coverityPublicKey; private final SecurityManagerPolicy policy;
// Path: pie-core/src/main/java/com/coverity/security/pie/core/PolicyConfig.java // public class PolicyConfig { // private final String name; // private final PieConfig pieConfig; // // public PolicyConfig(String name, PieConfig pieConfig) { // this.name = name; // this.pieConfig = pieConfig; // } // // public boolean isEnabled() { // return getBoolean("isEnabled", true); // } // // public boolean isReportOnlyMode() { // return getBoolean("isReportOnlyMode", true); // } // // public boolean isCollapseEnabled() { // return getBoolean("isCollapseEnabled", true); // } // // public URL getPolicyFile() { // String policyFile = getProperty("policyFile"); // if (policyFile != null) { // try { // return new URL(policyFile); // } catch (MalformedURLException e) { // throw new IllegalStateException("Invalid policy URL: " + policyFile); // } // } // URL resource = this.getClass().getClassLoader().getResource(name + ".policy"); // if (resource != null) { // return resource; // } // String catalinaHome = System.getProperty("catalina.home"); // if (catalinaHome != null) { // try { // return new File(catalinaHome + File.separatorChar + "conf" + File.separatorChar + name + ".policy").toURI().toURL(); // } catch (MalformedURLException e) { // throw new IllegalStateException("Could not build default policy file path."); // } // } // // // Default to file in the CWD // try { // return new File(name + ".policy").toURI().toURL(); // } catch (MalformedURLException e) { // throw new RuntimeException(e); // } // } // // public boolean getBoolean(String prop, boolean defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Boolean.parseBoolean(v); // } // public int getInteger(String prop, int defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Integer.parseInt(v); // } // // // public String getProperty(String name) { // return pieConfig.getProperties().getProperty(this.name + "." + name); // } // } // // Path: pie-core/src/main/java/com/coverity/security/pie/util/IOUtil.java // public class IOUtil { // public static void closeSilently(Closeable closeable) { // if (closeable != null) { // try { // closeable.close(); // } catch (IOException e) { // // Do nothing // } // } // } // // public static String readFile(File file) throws IOException { // return toString(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8)); // } // public static String readFile(String file) throws IOException { // return toString(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8)); // } // public static String readFile(URL file) throws IOException { // return toString(file.openStream()); // } // // public static String toString(InputStream is) throws IOException { // try { // return toString(new InputStreamReader(is, StandardCharsets.UTF_8)); // } finally { // closeSilently(is); // } // } // public static String toString(Reader reader) throws IOException { // StringBuilder sb = new StringBuilder(); // try { // char buffer[] = new char[4096]; // int n; // while ((n = reader.read(buffer)) > 0) { // sb.append(buffer, 0, n); // } // reader.close(); // } catch (IOException e) { // closeSilently(reader); // throw e; // } // return sb.toString(); // } // // // public static void writeFile(File file, String content) throws IOException { // writeFile(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8), content); // } // private static void writeFile(Writer fw, String content) throws IOException { // try { // fw.write(content); // fw.close(); // } catch (IOException e) { // closeSilently(fw); // throw e; // } // } // // } // Path: pie-sm/src/main/java/com/coverity/security/pie/policy/securitymanager/DynamicJavaPolicy.java import java.io.IOException; import java.io.InputStream; import java.security.GeneralSecurityException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.Permission; import java.security.Policy; import java.security.ProtectionDomain; import java.security.PublicKey; import java.security.SignatureException; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.util.ArrayList; import java.util.Collection; import com.coverity.security.pie.core.PolicyConfig; import com.coverity.security.pie.util.IOUtil; package com.coverity.security.pie.policy.securitymanager; /** * An implementation of the Java SecurityManager Policy class, which delegates policy decisions to the PIE policy. * Whitelists permissions for PIE classes based on their certificate signature. */ public class DynamicJavaPolicy extends Policy { private final Collection<Policy> parentPolicies; private final PublicKey coverityPublicKey; private final SecurityManagerPolicy policy;
private final PolicyConfig policyConfig;
coverity/pie
pie-sm/src/main/java/com/coverity/security/pie/policy/securitymanager/DynamicJavaPolicy.java
// Path: pie-core/src/main/java/com/coverity/security/pie/core/PolicyConfig.java // public class PolicyConfig { // private final String name; // private final PieConfig pieConfig; // // public PolicyConfig(String name, PieConfig pieConfig) { // this.name = name; // this.pieConfig = pieConfig; // } // // public boolean isEnabled() { // return getBoolean("isEnabled", true); // } // // public boolean isReportOnlyMode() { // return getBoolean("isReportOnlyMode", true); // } // // public boolean isCollapseEnabled() { // return getBoolean("isCollapseEnabled", true); // } // // public URL getPolicyFile() { // String policyFile = getProperty("policyFile"); // if (policyFile != null) { // try { // return new URL(policyFile); // } catch (MalformedURLException e) { // throw new IllegalStateException("Invalid policy URL: " + policyFile); // } // } // URL resource = this.getClass().getClassLoader().getResource(name + ".policy"); // if (resource != null) { // return resource; // } // String catalinaHome = System.getProperty("catalina.home"); // if (catalinaHome != null) { // try { // return new File(catalinaHome + File.separatorChar + "conf" + File.separatorChar + name + ".policy").toURI().toURL(); // } catch (MalformedURLException e) { // throw new IllegalStateException("Could not build default policy file path."); // } // } // // // Default to file in the CWD // try { // return new File(name + ".policy").toURI().toURL(); // } catch (MalformedURLException e) { // throw new RuntimeException(e); // } // } // // public boolean getBoolean(String prop, boolean defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Boolean.parseBoolean(v); // } // public int getInteger(String prop, int defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Integer.parseInt(v); // } // // // public String getProperty(String name) { // return pieConfig.getProperties().getProperty(this.name + "." + name); // } // } // // Path: pie-core/src/main/java/com/coverity/security/pie/util/IOUtil.java // public class IOUtil { // public static void closeSilently(Closeable closeable) { // if (closeable != null) { // try { // closeable.close(); // } catch (IOException e) { // // Do nothing // } // } // } // // public static String readFile(File file) throws IOException { // return toString(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8)); // } // public static String readFile(String file) throws IOException { // return toString(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8)); // } // public static String readFile(URL file) throws IOException { // return toString(file.openStream()); // } // // public static String toString(InputStream is) throws IOException { // try { // return toString(new InputStreamReader(is, StandardCharsets.UTF_8)); // } finally { // closeSilently(is); // } // } // public static String toString(Reader reader) throws IOException { // StringBuilder sb = new StringBuilder(); // try { // char buffer[] = new char[4096]; // int n; // while ((n = reader.read(buffer)) > 0) { // sb.append(buffer, 0, n); // } // reader.close(); // } catch (IOException e) { // closeSilently(reader); // throw e; // } // return sb.toString(); // } // // // public static void writeFile(File file, String content) throws IOException { // writeFile(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8), content); // } // private static void writeFile(Writer fw, String content) throws IOException { // try { // fw.write(content); // fw.close(); // } catch (IOException e) { // closeSilently(fw); // throw e; // } // } // // }
import java.io.IOException; import java.io.InputStream; import java.security.GeneralSecurityException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.Permission; import java.security.Policy; import java.security.ProtectionDomain; import java.security.PublicKey; import java.security.SignatureException; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.util.ArrayList; import java.util.Collection; import com.coverity.security.pie.core.PolicyConfig; import com.coverity.security.pie.util.IOUtil;
private final PolicyConfig policyConfig; public DynamicJavaPolicy(Policy parentPolicy, SecurityManagerPolicy policy, PolicyConfig policyConfig) { this.parentPolicies = new ArrayList<Policy>(); if (parentPolicy != null) { this.parentPolicies.add(parentPolicy); } this.policy = policy; this.policyConfig = policyConfig; try { coverityPublicKey = loadPublicX509("/coverity.crt").getPublicKey(); } catch (Exception e) { throw new RuntimeException(e); } } private Certificate loadPublicX509(String fileName) throws GeneralSecurityException, IOException { InputStream is = null; try { is = this.getClass().getResourceAsStream(fileName); if (is == null) { throw new IllegalArgumentException("Could not find resource: " + fileName); } CertificateFactory cf = CertificateFactory.getInstance("X.509"); Certificate crt = cf.generateCertificate(is); is.close(); return crt; } catch (IOException | GeneralSecurityException e) {
// Path: pie-core/src/main/java/com/coverity/security/pie/core/PolicyConfig.java // public class PolicyConfig { // private final String name; // private final PieConfig pieConfig; // // public PolicyConfig(String name, PieConfig pieConfig) { // this.name = name; // this.pieConfig = pieConfig; // } // // public boolean isEnabled() { // return getBoolean("isEnabled", true); // } // // public boolean isReportOnlyMode() { // return getBoolean("isReportOnlyMode", true); // } // // public boolean isCollapseEnabled() { // return getBoolean("isCollapseEnabled", true); // } // // public URL getPolicyFile() { // String policyFile = getProperty("policyFile"); // if (policyFile != null) { // try { // return new URL(policyFile); // } catch (MalformedURLException e) { // throw new IllegalStateException("Invalid policy URL: " + policyFile); // } // } // URL resource = this.getClass().getClassLoader().getResource(name + ".policy"); // if (resource != null) { // return resource; // } // String catalinaHome = System.getProperty("catalina.home"); // if (catalinaHome != null) { // try { // return new File(catalinaHome + File.separatorChar + "conf" + File.separatorChar + name + ".policy").toURI().toURL(); // } catch (MalformedURLException e) { // throw new IllegalStateException("Could not build default policy file path."); // } // } // // // Default to file in the CWD // try { // return new File(name + ".policy").toURI().toURL(); // } catch (MalformedURLException e) { // throw new RuntimeException(e); // } // } // // public boolean getBoolean(String prop, boolean defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Boolean.parseBoolean(v); // } // public int getInteger(String prop, int defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Integer.parseInt(v); // } // // // public String getProperty(String name) { // return pieConfig.getProperties().getProperty(this.name + "." + name); // } // } // // Path: pie-core/src/main/java/com/coverity/security/pie/util/IOUtil.java // public class IOUtil { // public static void closeSilently(Closeable closeable) { // if (closeable != null) { // try { // closeable.close(); // } catch (IOException e) { // // Do nothing // } // } // } // // public static String readFile(File file) throws IOException { // return toString(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8)); // } // public static String readFile(String file) throws IOException { // return toString(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8)); // } // public static String readFile(URL file) throws IOException { // return toString(file.openStream()); // } // // public static String toString(InputStream is) throws IOException { // try { // return toString(new InputStreamReader(is, StandardCharsets.UTF_8)); // } finally { // closeSilently(is); // } // } // public static String toString(Reader reader) throws IOException { // StringBuilder sb = new StringBuilder(); // try { // char buffer[] = new char[4096]; // int n; // while ((n = reader.read(buffer)) > 0) { // sb.append(buffer, 0, n); // } // reader.close(); // } catch (IOException e) { // closeSilently(reader); // throw e; // } // return sb.toString(); // } // // // public static void writeFile(File file, String content) throws IOException { // writeFile(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8), content); // } // private static void writeFile(Writer fw, String content) throws IOException { // try { // fw.write(content); // fw.close(); // } catch (IOException e) { // closeSilently(fw); // throw e; // } // } // // } // Path: pie-sm/src/main/java/com/coverity/security/pie/policy/securitymanager/DynamicJavaPolicy.java import java.io.IOException; import java.io.InputStream; import java.security.GeneralSecurityException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.Permission; import java.security.Policy; import java.security.ProtectionDomain; import java.security.PublicKey; import java.security.SignatureException; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.util.ArrayList; import java.util.Collection; import com.coverity.security.pie.core.PolicyConfig; import com.coverity.security.pie.util.IOUtil; private final PolicyConfig policyConfig; public DynamicJavaPolicy(Policy parentPolicy, SecurityManagerPolicy policy, PolicyConfig policyConfig) { this.parentPolicies = new ArrayList<Policy>(); if (parentPolicy != null) { this.parentPolicies.add(parentPolicy); } this.policy = policy; this.policyConfig = policyConfig; try { coverityPublicKey = loadPublicX509("/coverity.crt").getPublicKey(); } catch (Exception e) { throw new RuntimeException(e); } } private Certificate loadPublicX509(String fileName) throws GeneralSecurityException, IOException { InputStream is = null; try { is = this.getClass().getResourceAsStream(fileName); if (is == null) { throw new IllegalArgumentException("Could not find resource: " + fileName); } CertificateFactory cf = CertificateFactory.getInstance("X.509"); Certificate crt = cf.generateCertificate(is); is.close(); return crt; } catch (IOException | GeneralSecurityException e) {
IOUtil.closeSilently(is);
coverity/pie
examples/spring-security/src/main/java/com/coverity/security/pie/example/config/WebAppInitializer.java
// Path: examples/spring-security/src/main/java/com/coverity/security/pie/plugin/springsecurity/PieMethodSecurityConfig.java // @Configuration // @EnableGlobalMethodSecurity(securedEnabled = true, proxyTargetClass = true) // public class PieMethodSecurityConfig extends GlobalMethodSecurityConfiguration { // // @Autowired // private ServletContext servletContext; // // @Override // protected AccessDecisionManager accessDecisionManager() { // final SpringSecurityPolicyEnforcer policyEnforcer = (SpringSecurityPolicyEnforcer)servletContext.getAttribute(SpringSecurityPolicyEnforcer.SPRING_SECURITY_POLICY_ATTRIBUTE); // if (policyEnforcer == null) { // throw new IllegalStateException("Spring policy enforcer wasn't initialized."); // } // // return new PieAccessDecisionManager(policyEnforcer); // } // }
import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRegistration; import org.springframework.web.WebApplicationInitializer; import org.springframework.web.context.ContextLoaderListener; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import org.springframework.web.servlet.DispatcherServlet; import com.coverity.security.pie.plugin.springsecurity.PieMethodSecurityConfig;
package com.coverity.security.pie.example.config; public class WebAppInitializer implements WebApplicationInitializer { @Override public void onStartup(ServletContext servletContext) throws ServletException { AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();
// Path: examples/spring-security/src/main/java/com/coverity/security/pie/plugin/springsecurity/PieMethodSecurityConfig.java // @Configuration // @EnableGlobalMethodSecurity(securedEnabled = true, proxyTargetClass = true) // public class PieMethodSecurityConfig extends GlobalMethodSecurityConfiguration { // // @Autowired // private ServletContext servletContext; // // @Override // protected AccessDecisionManager accessDecisionManager() { // final SpringSecurityPolicyEnforcer policyEnforcer = (SpringSecurityPolicyEnforcer)servletContext.getAttribute(SpringSecurityPolicyEnforcer.SPRING_SECURITY_POLICY_ATTRIBUTE); // if (policyEnforcer == null) { // throw new IllegalStateException("Spring policy enforcer wasn't initialized."); // } // // return new PieAccessDecisionManager(policyEnforcer); // } // } // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/config/WebAppInitializer.java import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRegistration; import org.springframework.web.WebApplicationInitializer; import org.springframework.web.context.ContextLoaderListener; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import org.springframework.web.servlet.DispatcherServlet; import com.coverity.security.pie.plugin.springsecurity.PieMethodSecurityConfig; package com.coverity.security.pie.example.config; public class WebAppInitializer implements WebApplicationInitializer { @Override public void onStartup(ServletContext servletContext) throws ServletException { AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();
applicationContext.register(AppConfig.class, SecurityConfig.class, PieMethodSecurityConfig.class);
coverity/pie
pie-core/src/test/java/com/coverity/security/pie/dropwizard/PieBundleTest.java
// Path: pie-core/src/test/java/com/coverity/security/pie/core/test/TestPolicyEnforcer.java // public class TestPolicyEnforcer implements PolicyEnforcer { // // private static TestPolicyEnforcer instance = null; // // public static TestPolicyEnforcer getInstance() { // return instance; // } // // private SimplePolicy policy; // private PolicyConfig policyConfig; // private boolean isApplied = false; // // public TestPolicyEnforcer() { // if (instance != null) { // throw new IllegalStateException("Cannot instantiate more than one TestPolicyEnforcer at a time."); // } // instance = this; // } // // @Override // public void init(PieConfig pieConfig) { // this.policy = new SimplePolicy(); // this.policyConfig = new PolicyConfig(policy.getName(), pieConfig); // } // // @Override // public SimplePolicy getPolicy() { // return policy; // } // // @Override // public PolicyConfig getPolicyConfig() { // return policyConfig; // } // // @Override // public void applyPolicy(ServletContext cx) { // isApplied = true; // } // // @Override // public void shutdown() { // instance = null; // } // // public boolean isApplied() { // return isApplied; // } // } // // Path: pie-core/src/main/java/com/coverity/security/pie/util/IOUtil.java // public class IOUtil { // public static void closeSilently(Closeable closeable) { // if (closeable != null) { // try { // closeable.close(); // } catch (IOException e) { // // Do nothing // } // } // } // // public static String readFile(File file) throws IOException { // return toString(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8)); // } // public static String readFile(String file) throws IOException { // return toString(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8)); // } // public static String readFile(URL file) throws IOException { // return toString(file.openStream()); // } // // public static String toString(InputStream is) throws IOException { // try { // return toString(new InputStreamReader(is, StandardCharsets.UTF_8)); // } finally { // closeSilently(is); // } // } // public static String toString(Reader reader) throws IOException { // StringBuilder sb = new StringBuilder(); // try { // char buffer[] = new char[4096]; // int n; // while ((n = reader.read(buffer)) > 0) { // sb.append(buffer, 0, n); // } // reader.close(); // } catch (IOException e) { // closeSilently(reader); // throw e; // } // return sb.toString(); // } // // // public static void writeFile(File file, String content) throws IOException { // writeFile(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8), content); // } // private static void writeFile(Writer fw, String content) throws IOException { // try { // fw.write(content); // fw.close(); // } catch (IOException e) { // closeSilently(fw); // throw e; // } // } // // }
import com.codahale.metrics.annotation.Timed; import com.codahale.metrics.health.HealthCheck; import com.coverity.security.pie.core.test.TestPolicyEnforcer; import com.coverity.security.pie.util.IOUtil; import io.dropwizard.Configuration; import io.dropwizard.setup.Bootstrap; import io.dropwizard.setup.Environment; import org.eclipse.jetty.server.Server; import org.testng.annotations.Test; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import java.io.File; import static org.testng.Assert.*;
} @Override public void run(Configuration configuration, Environment environment) throws Exception { this.environment = environment; environment.healthChecks().register("helloWorld", new HelloWorldHealthCheck()); environment.jersey().register(new HelloWorldResource()); } } @Path("/hello-world") @Produces(MediaType.APPLICATION_JSON) private static class HelloWorldResource { @GET @Timed public String sayHello() { return "Hello, World!"; } } private static class HelloWorldHealthCheck extends HealthCheck { @Override protected Result check() throws Exception { return Result.healthy(); } } private static Server startupDropwizard() throws Exception { File file = File.createTempFile("dropwizard.yml", null);
// Path: pie-core/src/test/java/com/coverity/security/pie/core/test/TestPolicyEnforcer.java // public class TestPolicyEnforcer implements PolicyEnforcer { // // private static TestPolicyEnforcer instance = null; // // public static TestPolicyEnforcer getInstance() { // return instance; // } // // private SimplePolicy policy; // private PolicyConfig policyConfig; // private boolean isApplied = false; // // public TestPolicyEnforcer() { // if (instance != null) { // throw new IllegalStateException("Cannot instantiate more than one TestPolicyEnforcer at a time."); // } // instance = this; // } // // @Override // public void init(PieConfig pieConfig) { // this.policy = new SimplePolicy(); // this.policyConfig = new PolicyConfig(policy.getName(), pieConfig); // } // // @Override // public SimplePolicy getPolicy() { // return policy; // } // // @Override // public PolicyConfig getPolicyConfig() { // return policyConfig; // } // // @Override // public void applyPolicy(ServletContext cx) { // isApplied = true; // } // // @Override // public void shutdown() { // instance = null; // } // // public boolean isApplied() { // return isApplied; // } // } // // Path: pie-core/src/main/java/com/coverity/security/pie/util/IOUtil.java // public class IOUtil { // public static void closeSilently(Closeable closeable) { // if (closeable != null) { // try { // closeable.close(); // } catch (IOException e) { // // Do nothing // } // } // } // // public static String readFile(File file) throws IOException { // return toString(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8)); // } // public static String readFile(String file) throws IOException { // return toString(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8)); // } // public static String readFile(URL file) throws IOException { // return toString(file.openStream()); // } // // public static String toString(InputStream is) throws IOException { // try { // return toString(new InputStreamReader(is, StandardCharsets.UTF_8)); // } finally { // closeSilently(is); // } // } // public static String toString(Reader reader) throws IOException { // StringBuilder sb = new StringBuilder(); // try { // char buffer[] = new char[4096]; // int n; // while ((n = reader.read(buffer)) > 0) { // sb.append(buffer, 0, n); // } // reader.close(); // } catch (IOException e) { // closeSilently(reader); // throw e; // } // return sb.toString(); // } // // // public static void writeFile(File file, String content) throws IOException { // writeFile(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8), content); // } // private static void writeFile(Writer fw, String content) throws IOException { // try { // fw.write(content); // fw.close(); // } catch (IOException e) { // closeSilently(fw); // throw e; // } // } // // } // Path: pie-core/src/test/java/com/coverity/security/pie/dropwizard/PieBundleTest.java import com.codahale.metrics.annotation.Timed; import com.codahale.metrics.health.HealthCheck; import com.coverity.security.pie.core.test.TestPolicyEnforcer; import com.coverity.security.pie.util.IOUtil; import io.dropwizard.Configuration; import io.dropwizard.setup.Bootstrap; import io.dropwizard.setup.Environment; import org.eclipse.jetty.server.Server; import org.testng.annotations.Test; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import java.io.File; import static org.testng.Assert.*; } @Override public void run(Configuration configuration, Environment environment) throws Exception { this.environment = environment; environment.healthChecks().register("helloWorld", new HelloWorldHealthCheck()); environment.jersey().register(new HelloWorldResource()); } } @Path("/hello-world") @Produces(MediaType.APPLICATION_JSON) private static class HelloWorldResource { @GET @Timed public String sayHello() { return "Hello, World!"; } } private static class HelloWorldHealthCheck extends HealthCheck { @Override protected Result check() throws Exception { return Result.healthy(); } } private static Server startupDropwizard() throws Exception { File file = File.createTempFile("dropwizard.yml", null);
IOUtil.writeFile(file,
coverity/pie
pie-core/src/test/java/com/coverity/security/pie/dropwizard/PieBundleTest.java
// Path: pie-core/src/test/java/com/coverity/security/pie/core/test/TestPolicyEnforcer.java // public class TestPolicyEnforcer implements PolicyEnforcer { // // private static TestPolicyEnforcer instance = null; // // public static TestPolicyEnforcer getInstance() { // return instance; // } // // private SimplePolicy policy; // private PolicyConfig policyConfig; // private boolean isApplied = false; // // public TestPolicyEnforcer() { // if (instance != null) { // throw new IllegalStateException("Cannot instantiate more than one TestPolicyEnforcer at a time."); // } // instance = this; // } // // @Override // public void init(PieConfig pieConfig) { // this.policy = new SimplePolicy(); // this.policyConfig = new PolicyConfig(policy.getName(), pieConfig); // } // // @Override // public SimplePolicy getPolicy() { // return policy; // } // // @Override // public PolicyConfig getPolicyConfig() { // return policyConfig; // } // // @Override // public void applyPolicy(ServletContext cx) { // isApplied = true; // } // // @Override // public void shutdown() { // instance = null; // } // // public boolean isApplied() { // return isApplied; // } // } // // Path: pie-core/src/main/java/com/coverity/security/pie/util/IOUtil.java // public class IOUtil { // public static void closeSilently(Closeable closeable) { // if (closeable != null) { // try { // closeable.close(); // } catch (IOException e) { // // Do nothing // } // } // } // // public static String readFile(File file) throws IOException { // return toString(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8)); // } // public static String readFile(String file) throws IOException { // return toString(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8)); // } // public static String readFile(URL file) throws IOException { // return toString(file.openStream()); // } // // public static String toString(InputStream is) throws IOException { // try { // return toString(new InputStreamReader(is, StandardCharsets.UTF_8)); // } finally { // closeSilently(is); // } // } // public static String toString(Reader reader) throws IOException { // StringBuilder sb = new StringBuilder(); // try { // char buffer[] = new char[4096]; // int n; // while ((n = reader.read(buffer)) > 0) { // sb.append(buffer, 0, n); // } // reader.close(); // } catch (IOException e) { // closeSilently(reader); // throw e; // } // return sb.toString(); // } // // // public static void writeFile(File file, String content) throws IOException { // writeFile(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8), content); // } // private static void writeFile(Writer fw, String content) throws IOException { // try { // fw.write(content); // fw.close(); // } catch (IOException e) { // closeSilently(fw); // throw e; // } // } // // }
import com.codahale.metrics.annotation.Timed; import com.codahale.metrics.health.HealthCheck; import com.coverity.security.pie.core.test.TestPolicyEnforcer; import com.coverity.security.pie.util.IOUtil; import io.dropwizard.Configuration; import io.dropwizard.setup.Bootstrap; import io.dropwizard.setup.Environment; import org.eclipse.jetty.server.Server; import org.testng.annotations.Test; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import java.io.File; import static org.testng.Assert.*;
private static class HelloWorldHealthCheck extends HealthCheck { @Override protected Result check() throws Exception { return Result.healthy(); } } private static Server startupDropwizard() throws Exception { File file = File.createTempFile("dropwizard.yml", null); IOUtil.writeFile(file, "server:\n" + " applicationConnectors:\n" + " - type: http\n" + " port: 18885\n" + " adminConnectors:\n" + " - type: http\n" + " port: 18886\n"); PieDropwizardApplication application = new PieDropwizardApplication(); application.run(new String[]{"server", file.getAbsolutePath()}); return application.environment.getApplicationContext().getServer(); } @Test public void testDropwizardPieBundle() throws Exception { IOUtil.writeFile(new File("target/test-classes/pieConfig.properties"), "simple.policyFile = file:target/test-classes/simple.policy"); final Server server = startupDropwizard(); try {
// Path: pie-core/src/test/java/com/coverity/security/pie/core/test/TestPolicyEnforcer.java // public class TestPolicyEnforcer implements PolicyEnforcer { // // private static TestPolicyEnforcer instance = null; // // public static TestPolicyEnforcer getInstance() { // return instance; // } // // private SimplePolicy policy; // private PolicyConfig policyConfig; // private boolean isApplied = false; // // public TestPolicyEnforcer() { // if (instance != null) { // throw new IllegalStateException("Cannot instantiate more than one TestPolicyEnforcer at a time."); // } // instance = this; // } // // @Override // public void init(PieConfig pieConfig) { // this.policy = new SimplePolicy(); // this.policyConfig = new PolicyConfig(policy.getName(), pieConfig); // } // // @Override // public SimplePolicy getPolicy() { // return policy; // } // // @Override // public PolicyConfig getPolicyConfig() { // return policyConfig; // } // // @Override // public void applyPolicy(ServletContext cx) { // isApplied = true; // } // // @Override // public void shutdown() { // instance = null; // } // // public boolean isApplied() { // return isApplied; // } // } // // Path: pie-core/src/main/java/com/coverity/security/pie/util/IOUtil.java // public class IOUtil { // public static void closeSilently(Closeable closeable) { // if (closeable != null) { // try { // closeable.close(); // } catch (IOException e) { // // Do nothing // } // } // } // // public static String readFile(File file) throws IOException { // return toString(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8)); // } // public static String readFile(String file) throws IOException { // return toString(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8)); // } // public static String readFile(URL file) throws IOException { // return toString(file.openStream()); // } // // public static String toString(InputStream is) throws IOException { // try { // return toString(new InputStreamReader(is, StandardCharsets.UTF_8)); // } finally { // closeSilently(is); // } // } // public static String toString(Reader reader) throws IOException { // StringBuilder sb = new StringBuilder(); // try { // char buffer[] = new char[4096]; // int n; // while ((n = reader.read(buffer)) > 0) { // sb.append(buffer, 0, n); // } // reader.close(); // } catch (IOException e) { // closeSilently(reader); // throw e; // } // return sb.toString(); // } // // // public static void writeFile(File file, String content) throws IOException { // writeFile(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8), content); // } // private static void writeFile(Writer fw, String content) throws IOException { // try { // fw.write(content); // fw.close(); // } catch (IOException e) { // closeSilently(fw); // throw e; // } // } // // } // Path: pie-core/src/test/java/com/coverity/security/pie/dropwizard/PieBundleTest.java import com.codahale.metrics.annotation.Timed; import com.codahale.metrics.health.HealthCheck; import com.coverity.security.pie.core.test.TestPolicyEnforcer; import com.coverity.security.pie.util.IOUtil; import io.dropwizard.Configuration; import io.dropwizard.setup.Bootstrap; import io.dropwizard.setup.Environment; import org.eclipse.jetty.server.Server; import org.testng.annotations.Test; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import java.io.File; import static org.testng.Assert.*; private static class HelloWorldHealthCheck extends HealthCheck { @Override protected Result check() throws Exception { return Result.healthy(); } } private static Server startupDropwizard() throws Exception { File file = File.createTempFile("dropwizard.yml", null); IOUtil.writeFile(file, "server:\n" + " applicationConnectors:\n" + " - type: http\n" + " port: 18885\n" + " adminConnectors:\n" + " - type: http\n" + " port: 18886\n"); PieDropwizardApplication application = new PieDropwizardApplication(); application.run(new String[]{"server", file.getAbsolutePath()}); return application.environment.getApplicationContext().getServer(); } @Test public void testDropwizardPieBundle() throws Exception { IOUtil.writeFile(new File("target/test-classes/pieConfig.properties"), "simple.policyFile = file:target/test-classes/simple.policy"); final Server server = startupDropwizard(); try {
assertNotNull(TestPolicyEnforcer.getInstance());
coverity/pie
examples/spring-security/src/main/java/com/coverity/security/pie/plugin/springsecurity/SpringSecurityPolicyEnforcer.java
// Path: pie-core/src/main/java/com/coverity/security/pie/core/PieConfig.java // public class PieConfig { // // private final Properties properties = new Properties(); // // public PieConfig() { // loadProps(this.getClass().getClassLoader().getResource("pieConfig.default.properties")); // File propFile = new File("pieConfig.properties"); // if (propFile.exists()) { // try { // loadProps(propFile.toURI().toURL()); // } catch (MalformedURLException e) { // throw new RuntimeException(e); // } // } else { // loadProps(this.getClass().getClassLoader().getResource("pieConfig.properties")); // } // } // public PieConfig(URL propertiesUrl) { // loadProps(this.getClass().getClassLoader().getResource("pieConfig.default.properties")); // loadProps(propertiesUrl); // } // private void loadProps(URL propertiesUrl) { // if (propertiesUrl != null) { // InputStream is = null; // try { // is = propertiesUrl.openStream(); // if (is != null) { // properties.load(is); // is.close(); // } // } catch (IOException e) { // IOUtil.closeSilently(is); // throw new RuntimeException(e); // } // } // // } // // public Properties getProperties() { // return properties; // } // // private boolean getBoolean(String prop, boolean defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Boolean.parseBoolean(v); // } // // private String getProperty(String name) { // return properties.getProperty("pie." + name); // } // // public boolean isEnabled() { // return getBoolean("enabled", true); // } // // public boolean isRegenerateOnShutdown() { // return getBoolean("regenerateOnShutdown", true); // } // // public boolean isAdminInterfaceEnabled() { // return getBoolean("admininterface.enabled", false); // } // // public boolean isLoggingEnabled() { return getBoolean("loggingEnabled", false); } // // public String getLogPath() { return getProperty("logPath"); } // } // // Path: pie-core/src/main/java/com/coverity/security/pie/core/PolicyConfig.java // public class PolicyConfig { // private final String name; // private final PieConfig pieConfig; // // public PolicyConfig(String name, PieConfig pieConfig) { // this.name = name; // this.pieConfig = pieConfig; // } // // public boolean isEnabled() { // return getBoolean("isEnabled", true); // } // // public boolean isReportOnlyMode() { // return getBoolean("isReportOnlyMode", true); // } // // public boolean isCollapseEnabled() { // return getBoolean("isCollapseEnabled", true); // } // // public URL getPolicyFile() { // String policyFile = getProperty("policyFile"); // if (policyFile != null) { // try { // return new URL(policyFile); // } catch (MalformedURLException e) { // throw new IllegalStateException("Invalid policy URL: " + policyFile); // } // } // URL resource = this.getClass().getClassLoader().getResource(name + ".policy"); // if (resource != null) { // return resource; // } // String catalinaHome = System.getProperty("catalina.home"); // if (catalinaHome != null) { // try { // return new File(catalinaHome + File.separatorChar + "conf" + File.separatorChar + name + ".policy").toURI().toURL(); // } catch (MalformedURLException e) { // throw new IllegalStateException("Could not build default policy file path."); // } // } // // // Default to file in the CWD // try { // return new File(name + ".policy").toURI().toURL(); // } catch (MalformedURLException e) { // throw new RuntimeException(e); // } // } // // public boolean getBoolean(String prop, boolean defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Boolean.parseBoolean(v); // } // public int getInteger(String prop, int defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Integer.parseInt(v); // } // // // public String getProperty(String name) { // return pieConfig.getProperties().getProperty(this.name + "." + name); // } // } // // Path: pie-core/src/main/java/com/coverity/security/pie/core/PolicyEnforcer.java // public interface PolicyEnforcer { // // public Policy getPolicy(); // public PolicyConfig getPolicyConfig(); // // public void init(PieConfig pieConfig); // // /** // * Apply the policy to the servlet context being initialized. This enforcer should configure // * itself to both apply its policy to permission requests and keep an internal record of any // * policy violations. // * // * @param cx The servlet context currently being initialized. // */ // public void applyPolicy(ServletContext cx); // // /** // * The ServletContext to which this policy is applied is shutting down. The enforcer // * should do any cleanup it needs. // */ // public void shutdown(); // // }
import javax.servlet.ServletContext; import com.coverity.security.pie.core.PieConfig; import com.coverity.security.pie.core.PolicyConfig; import com.coverity.security.pie.core.PolicyEnforcer;
package com.coverity.security.pie.plugin.springsecurity; public class SpringSecurityPolicyEnforcer implements PolicyEnforcer { public static final String SPRING_SECURITY_POLICY_ATTRIBUTE = "com.coverity.pie.plugin.springsecurity.CONTEXT"; private SpringSecurityPolicy policy;
// Path: pie-core/src/main/java/com/coverity/security/pie/core/PieConfig.java // public class PieConfig { // // private final Properties properties = new Properties(); // // public PieConfig() { // loadProps(this.getClass().getClassLoader().getResource("pieConfig.default.properties")); // File propFile = new File("pieConfig.properties"); // if (propFile.exists()) { // try { // loadProps(propFile.toURI().toURL()); // } catch (MalformedURLException e) { // throw new RuntimeException(e); // } // } else { // loadProps(this.getClass().getClassLoader().getResource("pieConfig.properties")); // } // } // public PieConfig(URL propertiesUrl) { // loadProps(this.getClass().getClassLoader().getResource("pieConfig.default.properties")); // loadProps(propertiesUrl); // } // private void loadProps(URL propertiesUrl) { // if (propertiesUrl != null) { // InputStream is = null; // try { // is = propertiesUrl.openStream(); // if (is != null) { // properties.load(is); // is.close(); // } // } catch (IOException e) { // IOUtil.closeSilently(is); // throw new RuntimeException(e); // } // } // // } // // public Properties getProperties() { // return properties; // } // // private boolean getBoolean(String prop, boolean defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Boolean.parseBoolean(v); // } // // private String getProperty(String name) { // return properties.getProperty("pie." + name); // } // // public boolean isEnabled() { // return getBoolean("enabled", true); // } // // public boolean isRegenerateOnShutdown() { // return getBoolean("regenerateOnShutdown", true); // } // // public boolean isAdminInterfaceEnabled() { // return getBoolean("admininterface.enabled", false); // } // // public boolean isLoggingEnabled() { return getBoolean("loggingEnabled", false); } // // public String getLogPath() { return getProperty("logPath"); } // } // // Path: pie-core/src/main/java/com/coverity/security/pie/core/PolicyConfig.java // public class PolicyConfig { // private final String name; // private final PieConfig pieConfig; // // public PolicyConfig(String name, PieConfig pieConfig) { // this.name = name; // this.pieConfig = pieConfig; // } // // public boolean isEnabled() { // return getBoolean("isEnabled", true); // } // // public boolean isReportOnlyMode() { // return getBoolean("isReportOnlyMode", true); // } // // public boolean isCollapseEnabled() { // return getBoolean("isCollapseEnabled", true); // } // // public URL getPolicyFile() { // String policyFile = getProperty("policyFile"); // if (policyFile != null) { // try { // return new URL(policyFile); // } catch (MalformedURLException e) { // throw new IllegalStateException("Invalid policy URL: " + policyFile); // } // } // URL resource = this.getClass().getClassLoader().getResource(name + ".policy"); // if (resource != null) { // return resource; // } // String catalinaHome = System.getProperty("catalina.home"); // if (catalinaHome != null) { // try { // return new File(catalinaHome + File.separatorChar + "conf" + File.separatorChar + name + ".policy").toURI().toURL(); // } catch (MalformedURLException e) { // throw new IllegalStateException("Could not build default policy file path."); // } // } // // // Default to file in the CWD // try { // return new File(name + ".policy").toURI().toURL(); // } catch (MalformedURLException e) { // throw new RuntimeException(e); // } // } // // public boolean getBoolean(String prop, boolean defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Boolean.parseBoolean(v); // } // public int getInteger(String prop, int defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Integer.parseInt(v); // } // // // public String getProperty(String name) { // return pieConfig.getProperties().getProperty(this.name + "." + name); // } // } // // Path: pie-core/src/main/java/com/coverity/security/pie/core/PolicyEnforcer.java // public interface PolicyEnforcer { // // public Policy getPolicy(); // public PolicyConfig getPolicyConfig(); // // public void init(PieConfig pieConfig); // // /** // * Apply the policy to the servlet context being initialized. This enforcer should configure // * itself to both apply its policy to permission requests and keep an internal record of any // * policy violations. // * // * @param cx The servlet context currently being initialized. // */ // public void applyPolicy(ServletContext cx); // // /** // * The ServletContext to which this policy is applied is shutting down. The enforcer // * should do any cleanup it needs. // */ // public void shutdown(); // // } // Path: examples/spring-security/src/main/java/com/coverity/security/pie/plugin/springsecurity/SpringSecurityPolicyEnforcer.java import javax.servlet.ServletContext; import com.coverity.security.pie.core.PieConfig; import com.coverity.security.pie.core.PolicyConfig; import com.coverity.security.pie.core.PolicyEnforcer; package com.coverity.security.pie.plugin.springsecurity; public class SpringSecurityPolicyEnforcer implements PolicyEnforcer { public static final String SPRING_SECURITY_POLICY_ATTRIBUTE = "com.coverity.pie.plugin.springsecurity.CONTEXT"; private SpringSecurityPolicy policy;
private PolicyConfig policyConfig;
coverity/pie
examples/spring-security/src/main/java/com/coverity/security/pie/plugin/springsecurity/SpringSecurityPolicyEnforcer.java
// Path: pie-core/src/main/java/com/coverity/security/pie/core/PieConfig.java // public class PieConfig { // // private final Properties properties = new Properties(); // // public PieConfig() { // loadProps(this.getClass().getClassLoader().getResource("pieConfig.default.properties")); // File propFile = new File("pieConfig.properties"); // if (propFile.exists()) { // try { // loadProps(propFile.toURI().toURL()); // } catch (MalformedURLException e) { // throw new RuntimeException(e); // } // } else { // loadProps(this.getClass().getClassLoader().getResource("pieConfig.properties")); // } // } // public PieConfig(URL propertiesUrl) { // loadProps(this.getClass().getClassLoader().getResource("pieConfig.default.properties")); // loadProps(propertiesUrl); // } // private void loadProps(URL propertiesUrl) { // if (propertiesUrl != null) { // InputStream is = null; // try { // is = propertiesUrl.openStream(); // if (is != null) { // properties.load(is); // is.close(); // } // } catch (IOException e) { // IOUtil.closeSilently(is); // throw new RuntimeException(e); // } // } // // } // // public Properties getProperties() { // return properties; // } // // private boolean getBoolean(String prop, boolean defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Boolean.parseBoolean(v); // } // // private String getProperty(String name) { // return properties.getProperty("pie." + name); // } // // public boolean isEnabled() { // return getBoolean("enabled", true); // } // // public boolean isRegenerateOnShutdown() { // return getBoolean("regenerateOnShutdown", true); // } // // public boolean isAdminInterfaceEnabled() { // return getBoolean("admininterface.enabled", false); // } // // public boolean isLoggingEnabled() { return getBoolean("loggingEnabled", false); } // // public String getLogPath() { return getProperty("logPath"); } // } // // Path: pie-core/src/main/java/com/coverity/security/pie/core/PolicyConfig.java // public class PolicyConfig { // private final String name; // private final PieConfig pieConfig; // // public PolicyConfig(String name, PieConfig pieConfig) { // this.name = name; // this.pieConfig = pieConfig; // } // // public boolean isEnabled() { // return getBoolean("isEnabled", true); // } // // public boolean isReportOnlyMode() { // return getBoolean("isReportOnlyMode", true); // } // // public boolean isCollapseEnabled() { // return getBoolean("isCollapseEnabled", true); // } // // public URL getPolicyFile() { // String policyFile = getProperty("policyFile"); // if (policyFile != null) { // try { // return new URL(policyFile); // } catch (MalformedURLException e) { // throw new IllegalStateException("Invalid policy URL: " + policyFile); // } // } // URL resource = this.getClass().getClassLoader().getResource(name + ".policy"); // if (resource != null) { // return resource; // } // String catalinaHome = System.getProperty("catalina.home"); // if (catalinaHome != null) { // try { // return new File(catalinaHome + File.separatorChar + "conf" + File.separatorChar + name + ".policy").toURI().toURL(); // } catch (MalformedURLException e) { // throw new IllegalStateException("Could not build default policy file path."); // } // } // // // Default to file in the CWD // try { // return new File(name + ".policy").toURI().toURL(); // } catch (MalformedURLException e) { // throw new RuntimeException(e); // } // } // // public boolean getBoolean(String prop, boolean defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Boolean.parseBoolean(v); // } // public int getInteger(String prop, int defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Integer.parseInt(v); // } // // // public String getProperty(String name) { // return pieConfig.getProperties().getProperty(this.name + "." + name); // } // } // // Path: pie-core/src/main/java/com/coverity/security/pie/core/PolicyEnforcer.java // public interface PolicyEnforcer { // // public Policy getPolicy(); // public PolicyConfig getPolicyConfig(); // // public void init(PieConfig pieConfig); // // /** // * Apply the policy to the servlet context being initialized. This enforcer should configure // * itself to both apply its policy to permission requests and keep an internal record of any // * policy violations. // * // * @param cx The servlet context currently being initialized. // */ // public void applyPolicy(ServletContext cx); // // /** // * The ServletContext to which this policy is applied is shutting down. The enforcer // * should do any cleanup it needs. // */ // public void shutdown(); // // }
import javax.servlet.ServletContext; import com.coverity.security.pie.core.PieConfig; import com.coverity.security.pie.core.PolicyConfig; import com.coverity.security.pie.core.PolicyEnforcer;
package com.coverity.security.pie.plugin.springsecurity; public class SpringSecurityPolicyEnforcer implements PolicyEnforcer { public static final String SPRING_SECURITY_POLICY_ATTRIBUTE = "com.coverity.pie.plugin.springsecurity.CONTEXT"; private SpringSecurityPolicy policy; private PolicyConfig policyConfig; @Override public SpringSecurityPolicy getPolicy() { return policy; } @Override public PolicyConfig getPolicyConfig() { return policyConfig; } @Override
// Path: pie-core/src/main/java/com/coverity/security/pie/core/PieConfig.java // public class PieConfig { // // private final Properties properties = new Properties(); // // public PieConfig() { // loadProps(this.getClass().getClassLoader().getResource("pieConfig.default.properties")); // File propFile = new File("pieConfig.properties"); // if (propFile.exists()) { // try { // loadProps(propFile.toURI().toURL()); // } catch (MalformedURLException e) { // throw new RuntimeException(e); // } // } else { // loadProps(this.getClass().getClassLoader().getResource("pieConfig.properties")); // } // } // public PieConfig(URL propertiesUrl) { // loadProps(this.getClass().getClassLoader().getResource("pieConfig.default.properties")); // loadProps(propertiesUrl); // } // private void loadProps(URL propertiesUrl) { // if (propertiesUrl != null) { // InputStream is = null; // try { // is = propertiesUrl.openStream(); // if (is != null) { // properties.load(is); // is.close(); // } // } catch (IOException e) { // IOUtil.closeSilently(is); // throw new RuntimeException(e); // } // } // // } // // public Properties getProperties() { // return properties; // } // // private boolean getBoolean(String prop, boolean defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Boolean.parseBoolean(v); // } // // private String getProperty(String name) { // return properties.getProperty("pie." + name); // } // // public boolean isEnabled() { // return getBoolean("enabled", true); // } // // public boolean isRegenerateOnShutdown() { // return getBoolean("regenerateOnShutdown", true); // } // // public boolean isAdminInterfaceEnabled() { // return getBoolean("admininterface.enabled", false); // } // // public boolean isLoggingEnabled() { return getBoolean("loggingEnabled", false); } // // public String getLogPath() { return getProperty("logPath"); } // } // // Path: pie-core/src/main/java/com/coverity/security/pie/core/PolicyConfig.java // public class PolicyConfig { // private final String name; // private final PieConfig pieConfig; // // public PolicyConfig(String name, PieConfig pieConfig) { // this.name = name; // this.pieConfig = pieConfig; // } // // public boolean isEnabled() { // return getBoolean("isEnabled", true); // } // // public boolean isReportOnlyMode() { // return getBoolean("isReportOnlyMode", true); // } // // public boolean isCollapseEnabled() { // return getBoolean("isCollapseEnabled", true); // } // // public URL getPolicyFile() { // String policyFile = getProperty("policyFile"); // if (policyFile != null) { // try { // return new URL(policyFile); // } catch (MalformedURLException e) { // throw new IllegalStateException("Invalid policy URL: " + policyFile); // } // } // URL resource = this.getClass().getClassLoader().getResource(name + ".policy"); // if (resource != null) { // return resource; // } // String catalinaHome = System.getProperty("catalina.home"); // if (catalinaHome != null) { // try { // return new File(catalinaHome + File.separatorChar + "conf" + File.separatorChar + name + ".policy").toURI().toURL(); // } catch (MalformedURLException e) { // throw new IllegalStateException("Could not build default policy file path."); // } // } // // // Default to file in the CWD // try { // return new File(name + ".policy").toURI().toURL(); // } catch (MalformedURLException e) { // throw new RuntimeException(e); // } // } // // public boolean getBoolean(String prop, boolean defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Boolean.parseBoolean(v); // } // public int getInteger(String prop, int defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Integer.parseInt(v); // } // // // public String getProperty(String name) { // return pieConfig.getProperties().getProperty(this.name + "." + name); // } // } // // Path: pie-core/src/main/java/com/coverity/security/pie/core/PolicyEnforcer.java // public interface PolicyEnforcer { // // public Policy getPolicy(); // public PolicyConfig getPolicyConfig(); // // public void init(PieConfig pieConfig); // // /** // * Apply the policy to the servlet context being initialized. This enforcer should configure // * itself to both apply its policy to permission requests and keep an internal record of any // * policy violations. // * // * @param cx The servlet context currently being initialized. // */ // public void applyPolicy(ServletContext cx); // // /** // * The ServletContext to which this policy is applied is shutting down. The enforcer // * should do any cleanup it needs. // */ // public void shutdown(); // // } // Path: examples/spring-security/src/main/java/com/coverity/security/pie/plugin/springsecurity/SpringSecurityPolicyEnforcer.java import javax.servlet.ServletContext; import com.coverity.security.pie.core.PieConfig; import com.coverity.security.pie.core.PolicyConfig; import com.coverity.security.pie.core.PolicyEnforcer; package com.coverity.security.pie.plugin.springsecurity; public class SpringSecurityPolicyEnforcer implements PolicyEnforcer { public static final String SPRING_SECURITY_POLICY_ATTRIBUTE = "com.coverity.pie.plugin.springsecurity.CONTEXT"; private SpringSecurityPolicy policy; private PolicyConfig policyConfig; @Override public SpringSecurityPolicy getPolicy() { return policy; } @Override public PolicyConfig getPolicyConfig() { return policyConfig; } @Override
public void init(PieConfig pieConfig) {
coverity/pie
examples/spring-security/src/main/java/com/coverity/security/pie/example/service/UserDao.java
// Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/model/User.java // @Entity // public class User { // @Id @GeneratedValue // private Long id; // // private String username; // // private String passwordHash; // // private Role role; // // // public String getUsername() { // return username; // } // public void setUsername(String username) { // this.username = username; // } // public String getPasswordHash() { // return passwordHash; // } // public void setPasswordHash(String passwordHash) { // this.passwordHash = passwordHash; // } // public Role getRole() { // return role; // } // public void setRole(Role role) { // this.role = role; // } // }
import java.util.List; import com.coverity.security.pie.example.model.User; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional;
package com.coverity.security.pie.example.service; @Service public class UserDao extends AbstractDao {
// Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/model/User.java // @Entity // public class User { // @Id @GeneratedValue // private Long id; // // private String username; // // private String passwordHash; // // private Role role; // // // public String getUsername() { // return username; // } // public void setUsername(String username) { // this.username = username; // } // public String getPasswordHash() { // return passwordHash; // } // public void setPasswordHash(String passwordHash) { // this.passwordHash = passwordHash; // } // public Role getRole() { // return role; // } // public void setRole(Role role) { // this.role = role; // } // } // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/service/UserDao.java import java.util.List; import com.coverity.security.pie.example.model.User; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; package com.coverity.security.pie.example.service; @Service public class UserDao extends AbstractDao {
public List<User> getUsers() {
coverity/pie
examples/spring-security/src/main/java/com/coverity/security/pie/example/controller/HelloWorldController.java
// Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/model/Role.java // public enum Role { // GUEST, USER, ADMIN, SYSTEM; // } // // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/service/AccountDao.java // @Service // public class AccountDao extends AbstractDao { // public Account getAccount(String username) { // List<?> result = getEntityManager() // .createQuery("SELECT A FROM Account A WHERE A.user.username = :username") // .setParameter("username", username) // .getResultList(); // // if (result.size() == 0) { // return null; // } // return (Account)result.get(0); // } // // @Transactional // public void addAccount(Account account) { // getEntityManager().persist(account); // } // } // // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/service/UserDao.java // @Service // public class UserDao extends AbstractDao { // // public List<User> getUsers() { // return castList(getEntityManager().createQuery("SELECT U FROM User U").getResultList(), User.class); // } // // @Transactional // public void addUser(User user) { // getEntityManager().persist(user); // } // // }
import com.coverity.security.pie.example.model.Role; import com.coverity.security.pie.example.service.AccountDao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import com.coverity.security.pie.example.service.UserDao;
// (c) 2014 Coverity, Inc. All rights reserved worldwide. package com.coverity.security.pie.example.controller; @Controller public class HelloWorldController { @Autowired
// Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/model/Role.java // public enum Role { // GUEST, USER, ADMIN, SYSTEM; // } // // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/service/AccountDao.java // @Service // public class AccountDao extends AbstractDao { // public Account getAccount(String username) { // List<?> result = getEntityManager() // .createQuery("SELECT A FROM Account A WHERE A.user.username = :username") // .setParameter("username", username) // .getResultList(); // // if (result.size() == 0) { // return null; // } // return (Account)result.get(0); // } // // @Transactional // public void addAccount(Account account) { // getEntityManager().persist(account); // } // } // // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/service/UserDao.java // @Service // public class UserDao extends AbstractDao { // // public List<User> getUsers() { // return castList(getEntityManager().createQuery("SELECT U FROM User U").getResultList(), User.class); // } // // @Transactional // public void addUser(User user) { // getEntityManager().persist(user); // } // // } // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/controller/HelloWorldController.java import com.coverity.security.pie.example.model.Role; import com.coverity.security.pie.example.service.AccountDao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import com.coverity.security.pie.example.service.UserDao; // (c) 2014 Coverity, Inc. All rights reserved worldwide. package com.coverity.security.pie.example.controller; @Controller public class HelloWorldController { @Autowired
private UserDao userDao;
coverity/pie
examples/spring-security/src/main/java/com/coverity/security/pie/example/controller/HelloWorldController.java
// Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/model/Role.java // public enum Role { // GUEST, USER, ADMIN, SYSTEM; // } // // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/service/AccountDao.java // @Service // public class AccountDao extends AbstractDao { // public Account getAccount(String username) { // List<?> result = getEntityManager() // .createQuery("SELECT A FROM Account A WHERE A.user.username = :username") // .setParameter("username", username) // .getResultList(); // // if (result.size() == 0) { // return null; // } // return (Account)result.get(0); // } // // @Transactional // public void addAccount(Account account) { // getEntityManager().persist(account); // } // } // // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/service/UserDao.java // @Service // public class UserDao extends AbstractDao { // // public List<User> getUsers() { // return castList(getEntityManager().createQuery("SELECT U FROM User U").getResultList(), User.class); // } // // @Transactional // public void addUser(User user) { // getEntityManager().persist(user); // } // // }
import com.coverity.security.pie.example.model.Role; import com.coverity.security.pie.example.service.AccountDao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import com.coverity.security.pie.example.service.UserDao;
// (c) 2014 Coverity, Inc. All rights reserved worldwide. package com.coverity.security.pie.example.controller; @Controller public class HelloWorldController { @Autowired private UserDao userDao; @Autowired
// Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/model/Role.java // public enum Role { // GUEST, USER, ADMIN, SYSTEM; // } // // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/service/AccountDao.java // @Service // public class AccountDao extends AbstractDao { // public Account getAccount(String username) { // List<?> result = getEntityManager() // .createQuery("SELECT A FROM Account A WHERE A.user.username = :username") // .setParameter("username", username) // .getResultList(); // // if (result.size() == 0) { // return null; // } // return (Account)result.get(0); // } // // @Transactional // public void addAccount(Account account) { // getEntityManager().persist(account); // } // } // // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/service/UserDao.java // @Service // public class UserDao extends AbstractDao { // // public List<User> getUsers() { // return castList(getEntityManager().createQuery("SELECT U FROM User U").getResultList(), User.class); // } // // @Transactional // public void addUser(User user) { // getEntityManager().persist(user); // } // // } // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/controller/HelloWorldController.java import com.coverity.security.pie.example.model.Role; import com.coverity.security.pie.example.service.AccountDao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import com.coverity.security.pie.example.service.UserDao; // (c) 2014 Coverity, Inc. All rights reserved worldwide. package com.coverity.security.pie.example.controller; @Controller public class HelloWorldController { @Autowired private UserDao userDao; @Autowired
private AccountDao accountDao;
coverity/pie
examples/spring-security/src/main/java/com/coverity/security/pie/example/controller/HelloWorldController.java
// Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/model/Role.java // public enum Role { // GUEST, USER, ADMIN, SYSTEM; // } // // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/service/AccountDao.java // @Service // public class AccountDao extends AbstractDao { // public Account getAccount(String username) { // List<?> result = getEntityManager() // .createQuery("SELECT A FROM Account A WHERE A.user.username = :username") // .setParameter("username", username) // .getResultList(); // // if (result.size() == 0) { // return null; // } // return (Account)result.get(0); // } // // @Transactional // public void addAccount(Account account) { // getEntityManager().persist(account); // } // } // // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/service/UserDao.java // @Service // public class UserDao extends AbstractDao { // // public List<User> getUsers() { // return castList(getEntityManager().createQuery("SELECT U FROM User U").getResultList(), User.class); // } // // @Transactional // public void addUser(User user) { // getEntityManager().persist(user); // } // // }
import com.coverity.security.pie.example.model.Role; import com.coverity.security.pie.example.service.AccountDao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import com.coverity.security.pie.example.service.UserDao;
// (c) 2014 Coverity, Inc. All rights reserved worldwide. package com.coverity.security.pie.example.controller; @Controller public class HelloWorldController { @Autowired private UserDao userDao; @Autowired private AccountDao accountDao; @RequestMapping("getUsers") public ModelMap getUsers() { if (!SecurityContextHolder.getContext().getAuthentication().getAuthorities()
// Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/model/Role.java // public enum Role { // GUEST, USER, ADMIN, SYSTEM; // } // // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/service/AccountDao.java // @Service // public class AccountDao extends AbstractDao { // public Account getAccount(String username) { // List<?> result = getEntityManager() // .createQuery("SELECT A FROM Account A WHERE A.user.username = :username") // .setParameter("username", username) // .getResultList(); // // if (result.size() == 0) { // return null; // } // return (Account)result.get(0); // } // // @Transactional // public void addAccount(Account account) { // getEntityManager().persist(account); // } // } // // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/service/UserDao.java // @Service // public class UserDao extends AbstractDao { // // public List<User> getUsers() { // return castList(getEntityManager().createQuery("SELECT U FROM User U").getResultList(), User.class); // } // // @Transactional // public void addUser(User user) { // getEntityManager().persist(user); // } // // } // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/controller/HelloWorldController.java import com.coverity.security.pie.example.model.Role; import com.coverity.security.pie.example.service.AccountDao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import com.coverity.security.pie.example.service.UserDao; // (c) 2014 Coverity, Inc. All rights reserved worldwide. package com.coverity.security.pie.example.controller; @Controller public class HelloWorldController { @Autowired private UserDao userDao; @Autowired private AccountDao accountDao; @RequestMapping("getUsers") public ModelMap getUsers() { if (!SecurityContextHolder.getContext().getAuthentication().getAuthorities()
.contains(new SimpleGrantedAuthority(Role.ADMIN.toString()))) {
coverity/pie
pie-sm/src/test/java/com/coverity/security/pie/policy/securitymanager/SocketPermissionsTest.java
// Path: pie-core/src/main/java/com/coverity/security/pie/core/PieConfig.java // public class PieConfig { // // private final Properties properties = new Properties(); // // public PieConfig() { // loadProps(this.getClass().getClassLoader().getResource("pieConfig.default.properties")); // File propFile = new File("pieConfig.properties"); // if (propFile.exists()) { // try { // loadProps(propFile.toURI().toURL()); // } catch (MalformedURLException e) { // throw new RuntimeException(e); // } // } else { // loadProps(this.getClass().getClassLoader().getResource("pieConfig.properties")); // } // } // public PieConfig(URL propertiesUrl) { // loadProps(this.getClass().getClassLoader().getResource("pieConfig.default.properties")); // loadProps(propertiesUrl); // } // private void loadProps(URL propertiesUrl) { // if (propertiesUrl != null) { // InputStream is = null; // try { // is = propertiesUrl.openStream(); // if (is != null) { // properties.load(is); // is.close(); // } // } catch (IOException e) { // IOUtil.closeSilently(is); // throw new RuntimeException(e); // } // } // // } // // public Properties getProperties() { // return properties; // } // // private boolean getBoolean(String prop, boolean defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Boolean.parseBoolean(v); // } // // private String getProperty(String name) { // return properties.getProperty("pie." + name); // } // // public boolean isEnabled() { // return getBoolean("enabled", true); // } // // public boolean isRegenerateOnShutdown() { // return getBoolean("regenerateOnShutdown", true); // } // // public boolean isAdminInterfaceEnabled() { // return getBoolean("admininterface.enabled", false); // } // // public boolean isLoggingEnabled() { return getBoolean("loggingEnabled", false); } // // public String getLogPath() { return getProperty("logPath"); } // } // // Path: pie-core/src/main/java/com/coverity/security/pie/core/PolicyConfig.java // public class PolicyConfig { // private final String name; // private final PieConfig pieConfig; // // public PolicyConfig(String name, PieConfig pieConfig) { // this.name = name; // this.pieConfig = pieConfig; // } // // public boolean isEnabled() { // return getBoolean("isEnabled", true); // } // // public boolean isReportOnlyMode() { // return getBoolean("isReportOnlyMode", true); // } // // public boolean isCollapseEnabled() { // return getBoolean("isCollapseEnabled", true); // } // // public URL getPolicyFile() { // String policyFile = getProperty("policyFile"); // if (policyFile != null) { // try { // return new URL(policyFile); // } catch (MalformedURLException e) { // throw new IllegalStateException("Invalid policy URL: " + policyFile); // } // } // URL resource = this.getClass().getClassLoader().getResource(name + ".policy"); // if (resource != null) { // return resource; // } // String catalinaHome = System.getProperty("catalina.home"); // if (catalinaHome != null) { // try { // return new File(catalinaHome + File.separatorChar + "conf" + File.separatorChar + name + ".policy").toURI().toURL(); // } catch (MalformedURLException e) { // throw new IllegalStateException("Could not build default policy file path."); // } // } // // // Default to file in the CWD // try { // return new File(name + ".policy").toURI().toURL(); // } catch (MalformedURLException e) { // throw new RuntimeException(e); // } // } // // public boolean getBoolean(String prop, boolean defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Boolean.parseBoolean(v); // } // public int getInteger(String prop, int defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Integer.parseInt(v); // } // // // public String getProperty(String name) { // return pieConfig.getProperties().getProperty(this.name + "." + name); // } // }
import com.coverity.security.pie.core.PieConfig; import com.coverity.security.pie.core.PolicyConfig; import org.json.JSONObject; import org.testng.annotations.Test; import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; import java.net.SocketPermission; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue;
package com.coverity.security.pie.policy.securitymanager; public class SocketPermissionsTest { @Test public void testSocketPermissions() throws IOException { /* Test that all 'accept,resolve' permissions get collapsed to a wildcard "*:0" permission, other permissions don't have any collapsing behavior, and that the wildcard is respected when new host names are passed to the policy. */ SecurityManagerPolicy policy = new SecurityManagerPolicy();
// Path: pie-core/src/main/java/com/coverity/security/pie/core/PieConfig.java // public class PieConfig { // // private final Properties properties = new Properties(); // // public PieConfig() { // loadProps(this.getClass().getClassLoader().getResource("pieConfig.default.properties")); // File propFile = new File("pieConfig.properties"); // if (propFile.exists()) { // try { // loadProps(propFile.toURI().toURL()); // } catch (MalformedURLException e) { // throw new RuntimeException(e); // } // } else { // loadProps(this.getClass().getClassLoader().getResource("pieConfig.properties")); // } // } // public PieConfig(URL propertiesUrl) { // loadProps(this.getClass().getClassLoader().getResource("pieConfig.default.properties")); // loadProps(propertiesUrl); // } // private void loadProps(URL propertiesUrl) { // if (propertiesUrl != null) { // InputStream is = null; // try { // is = propertiesUrl.openStream(); // if (is != null) { // properties.load(is); // is.close(); // } // } catch (IOException e) { // IOUtil.closeSilently(is); // throw new RuntimeException(e); // } // } // // } // // public Properties getProperties() { // return properties; // } // // private boolean getBoolean(String prop, boolean defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Boolean.parseBoolean(v); // } // // private String getProperty(String name) { // return properties.getProperty("pie." + name); // } // // public boolean isEnabled() { // return getBoolean("enabled", true); // } // // public boolean isRegenerateOnShutdown() { // return getBoolean("regenerateOnShutdown", true); // } // // public boolean isAdminInterfaceEnabled() { // return getBoolean("admininterface.enabled", false); // } // // public boolean isLoggingEnabled() { return getBoolean("loggingEnabled", false); } // // public String getLogPath() { return getProperty("logPath"); } // } // // Path: pie-core/src/main/java/com/coverity/security/pie/core/PolicyConfig.java // public class PolicyConfig { // private final String name; // private final PieConfig pieConfig; // // public PolicyConfig(String name, PieConfig pieConfig) { // this.name = name; // this.pieConfig = pieConfig; // } // // public boolean isEnabled() { // return getBoolean("isEnabled", true); // } // // public boolean isReportOnlyMode() { // return getBoolean("isReportOnlyMode", true); // } // // public boolean isCollapseEnabled() { // return getBoolean("isCollapseEnabled", true); // } // // public URL getPolicyFile() { // String policyFile = getProperty("policyFile"); // if (policyFile != null) { // try { // return new URL(policyFile); // } catch (MalformedURLException e) { // throw new IllegalStateException("Invalid policy URL: " + policyFile); // } // } // URL resource = this.getClass().getClassLoader().getResource(name + ".policy"); // if (resource != null) { // return resource; // } // String catalinaHome = System.getProperty("catalina.home"); // if (catalinaHome != null) { // try { // return new File(catalinaHome + File.separatorChar + "conf" + File.separatorChar + name + ".policy").toURI().toURL(); // } catch (MalformedURLException e) { // throw new IllegalStateException("Could not build default policy file path."); // } // } // // // Default to file in the CWD // try { // return new File(name + ".policy").toURI().toURL(); // } catch (MalformedURLException e) { // throw new RuntimeException(e); // } // } // // public boolean getBoolean(String prop, boolean defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Boolean.parseBoolean(v); // } // public int getInteger(String prop, int defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Integer.parseInt(v); // } // // // public String getProperty(String name) { // return pieConfig.getProperties().getProperty(this.name + "." + name); // } // } // Path: pie-sm/src/test/java/com/coverity/security/pie/policy/securitymanager/SocketPermissionsTest.java import com.coverity.security.pie.core.PieConfig; import com.coverity.security.pie.core.PolicyConfig; import org.json.JSONObject; import org.testng.annotations.Test; import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; import java.net.SocketPermission; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; package com.coverity.security.pie.policy.securitymanager; public class SocketPermissionsTest { @Test public void testSocketPermissions() throws IOException { /* Test that all 'accept,resolve' permissions get collapsed to a wildcard "*:0" permission, other permissions don't have any collapsing behavior, and that the wildcard is respected when new host names are passed to the policy. */ SecurityManagerPolicy policy = new SecurityManagerPolicy();
policy.setPolicyConfig(new PolicyConfig(policy.getName(), new PieConfig()));
coverity/pie
pie-sm/src/test/java/com/coverity/security/pie/policy/securitymanager/SocketPermissionsTest.java
// Path: pie-core/src/main/java/com/coverity/security/pie/core/PieConfig.java // public class PieConfig { // // private final Properties properties = new Properties(); // // public PieConfig() { // loadProps(this.getClass().getClassLoader().getResource("pieConfig.default.properties")); // File propFile = new File("pieConfig.properties"); // if (propFile.exists()) { // try { // loadProps(propFile.toURI().toURL()); // } catch (MalformedURLException e) { // throw new RuntimeException(e); // } // } else { // loadProps(this.getClass().getClassLoader().getResource("pieConfig.properties")); // } // } // public PieConfig(URL propertiesUrl) { // loadProps(this.getClass().getClassLoader().getResource("pieConfig.default.properties")); // loadProps(propertiesUrl); // } // private void loadProps(URL propertiesUrl) { // if (propertiesUrl != null) { // InputStream is = null; // try { // is = propertiesUrl.openStream(); // if (is != null) { // properties.load(is); // is.close(); // } // } catch (IOException e) { // IOUtil.closeSilently(is); // throw new RuntimeException(e); // } // } // // } // // public Properties getProperties() { // return properties; // } // // private boolean getBoolean(String prop, boolean defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Boolean.parseBoolean(v); // } // // private String getProperty(String name) { // return properties.getProperty("pie." + name); // } // // public boolean isEnabled() { // return getBoolean("enabled", true); // } // // public boolean isRegenerateOnShutdown() { // return getBoolean("regenerateOnShutdown", true); // } // // public boolean isAdminInterfaceEnabled() { // return getBoolean("admininterface.enabled", false); // } // // public boolean isLoggingEnabled() { return getBoolean("loggingEnabled", false); } // // public String getLogPath() { return getProperty("logPath"); } // } // // Path: pie-core/src/main/java/com/coverity/security/pie/core/PolicyConfig.java // public class PolicyConfig { // private final String name; // private final PieConfig pieConfig; // // public PolicyConfig(String name, PieConfig pieConfig) { // this.name = name; // this.pieConfig = pieConfig; // } // // public boolean isEnabled() { // return getBoolean("isEnabled", true); // } // // public boolean isReportOnlyMode() { // return getBoolean("isReportOnlyMode", true); // } // // public boolean isCollapseEnabled() { // return getBoolean("isCollapseEnabled", true); // } // // public URL getPolicyFile() { // String policyFile = getProperty("policyFile"); // if (policyFile != null) { // try { // return new URL(policyFile); // } catch (MalformedURLException e) { // throw new IllegalStateException("Invalid policy URL: " + policyFile); // } // } // URL resource = this.getClass().getClassLoader().getResource(name + ".policy"); // if (resource != null) { // return resource; // } // String catalinaHome = System.getProperty("catalina.home"); // if (catalinaHome != null) { // try { // return new File(catalinaHome + File.separatorChar + "conf" + File.separatorChar + name + ".policy").toURI().toURL(); // } catch (MalformedURLException e) { // throw new IllegalStateException("Could not build default policy file path."); // } // } // // // Default to file in the CWD // try { // return new File(name + ".policy").toURI().toURL(); // } catch (MalformedURLException e) { // throw new RuntimeException(e); // } // } // // public boolean getBoolean(String prop, boolean defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Boolean.parseBoolean(v); // } // public int getInteger(String prop, int defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Integer.parseInt(v); // } // // // public String getProperty(String name) { // return pieConfig.getProperties().getProperty(this.name + "." + name); // } // }
import com.coverity.security.pie.core.PieConfig; import com.coverity.security.pie.core.PolicyConfig; import org.json.JSONObject; import org.testng.annotations.Test; import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; import java.net.SocketPermission; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue;
package com.coverity.security.pie.policy.securitymanager; public class SocketPermissionsTest { @Test public void testSocketPermissions() throws IOException { /* Test that all 'accept,resolve' permissions get collapsed to a wildcard "*:0" permission, other permissions don't have any collapsing behavior, and that the wildcard is respected when new host names are passed to the policy. */ SecurityManagerPolicy policy = new SecurityManagerPolicy();
// Path: pie-core/src/main/java/com/coverity/security/pie/core/PieConfig.java // public class PieConfig { // // private final Properties properties = new Properties(); // // public PieConfig() { // loadProps(this.getClass().getClassLoader().getResource("pieConfig.default.properties")); // File propFile = new File("pieConfig.properties"); // if (propFile.exists()) { // try { // loadProps(propFile.toURI().toURL()); // } catch (MalformedURLException e) { // throw new RuntimeException(e); // } // } else { // loadProps(this.getClass().getClassLoader().getResource("pieConfig.properties")); // } // } // public PieConfig(URL propertiesUrl) { // loadProps(this.getClass().getClassLoader().getResource("pieConfig.default.properties")); // loadProps(propertiesUrl); // } // private void loadProps(URL propertiesUrl) { // if (propertiesUrl != null) { // InputStream is = null; // try { // is = propertiesUrl.openStream(); // if (is != null) { // properties.load(is); // is.close(); // } // } catch (IOException e) { // IOUtil.closeSilently(is); // throw new RuntimeException(e); // } // } // // } // // public Properties getProperties() { // return properties; // } // // private boolean getBoolean(String prop, boolean defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Boolean.parseBoolean(v); // } // // private String getProperty(String name) { // return properties.getProperty("pie." + name); // } // // public boolean isEnabled() { // return getBoolean("enabled", true); // } // // public boolean isRegenerateOnShutdown() { // return getBoolean("regenerateOnShutdown", true); // } // // public boolean isAdminInterfaceEnabled() { // return getBoolean("admininterface.enabled", false); // } // // public boolean isLoggingEnabled() { return getBoolean("loggingEnabled", false); } // // public String getLogPath() { return getProperty("logPath"); } // } // // Path: pie-core/src/main/java/com/coverity/security/pie/core/PolicyConfig.java // public class PolicyConfig { // private final String name; // private final PieConfig pieConfig; // // public PolicyConfig(String name, PieConfig pieConfig) { // this.name = name; // this.pieConfig = pieConfig; // } // // public boolean isEnabled() { // return getBoolean("isEnabled", true); // } // // public boolean isReportOnlyMode() { // return getBoolean("isReportOnlyMode", true); // } // // public boolean isCollapseEnabled() { // return getBoolean("isCollapseEnabled", true); // } // // public URL getPolicyFile() { // String policyFile = getProperty("policyFile"); // if (policyFile != null) { // try { // return new URL(policyFile); // } catch (MalformedURLException e) { // throw new IllegalStateException("Invalid policy URL: " + policyFile); // } // } // URL resource = this.getClass().getClassLoader().getResource(name + ".policy"); // if (resource != null) { // return resource; // } // String catalinaHome = System.getProperty("catalina.home"); // if (catalinaHome != null) { // try { // return new File(catalinaHome + File.separatorChar + "conf" + File.separatorChar + name + ".policy").toURI().toURL(); // } catch (MalformedURLException e) { // throw new IllegalStateException("Could not build default policy file path."); // } // } // // // Default to file in the CWD // try { // return new File(name + ".policy").toURI().toURL(); // } catch (MalformedURLException e) { // throw new RuntimeException(e); // } // } // // public boolean getBoolean(String prop, boolean defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Boolean.parseBoolean(v); // } // public int getInteger(String prop, int defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Integer.parseInt(v); // } // // // public String getProperty(String name) { // return pieConfig.getProperties().getProperty(this.name + "." + name); // } // } // Path: pie-sm/src/test/java/com/coverity/security/pie/policy/securitymanager/SocketPermissionsTest.java import com.coverity.security.pie.core.PieConfig; import com.coverity.security.pie.core.PolicyConfig; import org.json.JSONObject; import org.testng.annotations.Test; import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; import java.net.SocketPermission; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; package com.coverity.security.pie.policy.securitymanager; public class SocketPermissionsTest { @Test public void testSocketPermissions() throws IOException { /* Test that all 'accept,resolve' permissions get collapsed to a wildcard "*:0" permission, other permissions don't have any collapsing behavior, and that the wildcard is respected when new host names are passed to the policy. */ SecurityManagerPolicy policy = new SecurityManagerPolicy();
policy.setPolicyConfig(new PolicyConfig(policy.getName(), new PieConfig()));
coverity/pie
pie-core/src/main/java/com/coverity/security/pie/core/Policy.java
// Path: pie-core/src/main/java/com/coverity/security/pie/util/IOUtil.java // public class IOUtil { // public static void closeSilently(Closeable closeable) { // if (closeable != null) { // try { // closeable.close(); // } catch (IOException e) { // // Do nothing // } // } // } // // public static String readFile(File file) throws IOException { // return toString(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8)); // } // public static String readFile(String file) throws IOException { // return toString(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8)); // } // public static String readFile(URL file) throws IOException { // return toString(file.openStream()); // } // // public static String toString(InputStream is) throws IOException { // try { // return toString(new InputStreamReader(is, StandardCharsets.UTF_8)); // } finally { // closeSilently(is); // } // } // public static String toString(Reader reader) throws IOException { // StringBuilder sb = new StringBuilder(); // try { // char buffer[] = new char[4096]; // int n; // while ((n = reader.read(buffer)) > 0) { // sb.append(buffer, 0, n); // } // reader.close(); // } catch (IOException e) { // closeSilently(reader); // throw e; // } // return sb.toString(); // } // // // public static void writeFile(File file, String content) throws IOException { // writeFile(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8), content); // } // private static void writeFile(Writer fw, String content) throws IOException { // try { // fw.write(content); // fw.close(); // } catch (IOException e) { // closeSilently(fw); // throw e; // } // } // // } // // Path: pie-core/src/main/java/com/coverity/security/pie/util/PieLogger.java // public class PieLogger { // private static PieConfig pieConfig = null; // private static PrintWriter logWriter = null; // // public static void setPieConfig(PieConfig pieConfig) { // PieLogger.pieConfig = pieConfig; // if (logWriter != null) { // IOUtil.closeSilently(logWriter); // logWriter = null; // } // if (pieConfig != null && pieConfig.isLoggingEnabled()) { // try { // logWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(pieConfig.getLogPath(), true), StandardCharsets.UTF_8)); // } catch (FileNotFoundException e) { // throw new RuntimeException(e); // } // } // } // // public static enum LogLevel { // DEBUG, // INFO, // WARN, // ERROR // } // // public static void log(LogLevel logLevel, String msg, Throwable throwable) { // if (logWriter == null) { // return; // } // logWriter.append("[").append(new Date().toString()).append("] ").append(logLevel.toString()).append(": ").append(msg).append("\n"); // if (throwable != null) { // throwable.printStackTrace(logWriter); // } // logWriter.flush(); // } // // public static void log(LogLevel logLevel, String msg) { // log(logLevel, msg, null); // } // // public static void debug(String msg) { // log(LogLevel.DEBUG, msg); // } // public static void debug(String msg, Throwable throwable) { // log(LogLevel.DEBUG, msg, throwable); // } // public static void info(String msg) { // log(LogLevel.INFO, msg); // } // public static void info(String msg, Throwable throwable) { // log(LogLevel.INFO, msg, throwable); // } // public static void warn(String msg) { // log(LogLevel.WARN, msg); // } // public static void warn(String msg, Throwable throwable) { // log(LogLevel.WARN, msg, throwable); // } // public static void error(String msg) { // log(LogLevel.ERROR, msg); // } // public static void error(String msg, Throwable throwable) { // log(LogLevel.ERROR, msg, throwable); // } // // }
import com.coverity.security.pie.util.IOUtil; import com.coverity.security.pie.util.PieLogger; import org.json.JSONObject; import java.io.IOException; import java.io.Reader; import java.io.Writer; import java.util.*; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock;
private FactTreeNode collapseFactTreeNode(String rootValue, Collection<FactTreeNode> children, FactMetaData factMetaData) { if (children.size() == 0) { return new FactTreeNode(rootValue); } Map<String, Collection<FactTreeNode>> childMap = new HashMap<String, Collection<FactTreeNode>>(children.size()); for (FactTreeNode child : children) { if (!childMap.containsKey(child.value)) { childMap.put(child.value, new ArrayList<FactTreeNode>(child.children)); } else { childMap.get(child.value).addAll(child.children); } } childMap = factMetaData.getCollapser(policyConfig).collapse(childMap); FactTreeNode factTreeNode = new FactTreeNode(rootValue); for (Map.Entry<String, Collection<FactTreeNode>> entry : childMap.entrySet()) { factTreeNode.children.add(collapseFactTreeNode( entry.getKey(), entry.getValue(), factMetaData.getChildFactMetaData(entry.getKey()))); } return factTreeNode; } /** * Reads a PIE security policy from the reader argument, replacing any current policy data with what is read in. * * @param reader The reader with the raw policy content. * @throws IOException */ public void parsePolicy(Reader reader) throws IOException {
// Path: pie-core/src/main/java/com/coverity/security/pie/util/IOUtil.java // public class IOUtil { // public static void closeSilently(Closeable closeable) { // if (closeable != null) { // try { // closeable.close(); // } catch (IOException e) { // // Do nothing // } // } // } // // public static String readFile(File file) throws IOException { // return toString(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8)); // } // public static String readFile(String file) throws IOException { // return toString(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8)); // } // public static String readFile(URL file) throws IOException { // return toString(file.openStream()); // } // // public static String toString(InputStream is) throws IOException { // try { // return toString(new InputStreamReader(is, StandardCharsets.UTF_8)); // } finally { // closeSilently(is); // } // } // public static String toString(Reader reader) throws IOException { // StringBuilder sb = new StringBuilder(); // try { // char buffer[] = new char[4096]; // int n; // while ((n = reader.read(buffer)) > 0) { // sb.append(buffer, 0, n); // } // reader.close(); // } catch (IOException e) { // closeSilently(reader); // throw e; // } // return sb.toString(); // } // // // public static void writeFile(File file, String content) throws IOException { // writeFile(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8), content); // } // private static void writeFile(Writer fw, String content) throws IOException { // try { // fw.write(content); // fw.close(); // } catch (IOException e) { // closeSilently(fw); // throw e; // } // } // // } // // Path: pie-core/src/main/java/com/coverity/security/pie/util/PieLogger.java // public class PieLogger { // private static PieConfig pieConfig = null; // private static PrintWriter logWriter = null; // // public static void setPieConfig(PieConfig pieConfig) { // PieLogger.pieConfig = pieConfig; // if (logWriter != null) { // IOUtil.closeSilently(logWriter); // logWriter = null; // } // if (pieConfig != null && pieConfig.isLoggingEnabled()) { // try { // logWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(pieConfig.getLogPath(), true), StandardCharsets.UTF_8)); // } catch (FileNotFoundException e) { // throw new RuntimeException(e); // } // } // } // // public static enum LogLevel { // DEBUG, // INFO, // WARN, // ERROR // } // // public static void log(LogLevel logLevel, String msg, Throwable throwable) { // if (logWriter == null) { // return; // } // logWriter.append("[").append(new Date().toString()).append("] ").append(logLevel.toString()).append(": ").append(msg).append("\n"); // if (throwable != null) { // throwable.printStackTrace(logWriter); // } // logWriter.flush(); // } // // public static void log(LogLevel logLevel, String msg) { // log(logLevel, msg, null); // } // // public static void debug(String msg) { // log(LogLevel.DEBUG, msg); // } // public static void debug(String msg, Throwable throwable) { // log(LogLevel.DEBUG, msg, throwable); // } // public static void info(String msg) { // log(LogLevel.INFO, msg); // } // public static void info(String msg, Throwable throwable) { // log(LogLevel.INFO, msg, throwable); // } // public static void warn(String msg) { // log(LogLevel.WARN, msg); // } // public static void warn(String msg, Throwable throwable) { // log(LogLevel.WARN, msg, throwable); // } // public static void error(String msg) { // log(LogLevel.ERROR, msg); // } // public static void error(String msg, Throwable throwable) { // log(LogLevel.ERROR, msg, throwable); // } // // } // Path: pie-core/src/main/java/com/coverity/security/pie/core/Policy.java import com.coverity.security.pie.util.IOUtil; import com.coverity.security.pie.util.PieLogger; import org.json.JSONObject; import java.io.IOException; import java.io.Reader; import java.io.Writer; import java.util.*; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; private FactTreeNode collapseFactTreeNode(String rootValue, Collection<FactTreeNode> children, FactMetaData factMetaData) { if (children.size() == 0) { return new FactTreeNode(rootValue); } Map<String, Collection<FactTreeNode>> childMap = new HashMap<String, Collection<FactTreeNode>>(children.size()); for (FactTreeNode child : children) { if (!childMap.containsKey(child.value)) { childMap.put(child.value, new ArrayList<FactTreeNode>(child.children)); } else { childMap.get(child.value).addAll(child.children); } } childMap = factMetaData.getCollapser(policyConfig).collapse(childMap); FactTreeNode factTreeNode = new FactTreeNode(rootValue); for (Map.Entry<String, Collection<FactTreeNode>> entry : childMap.entrySet()) { factTreeNode.children.add(collapseFactTreeNode( entry.getKey(), entry.getValue(), factMetaData.getChildFactMetaData(entry.getKey()))); } return factTreeNode; } /** * Reads a PIE security policy from the reader argument, replacing any current policy data with what is read in. * * @param reader The reader with the raw policy content. * @throws IOException */ public void parsePolicy(Reader reader) throws IOException {
policyRoot = asFactTreeNode(null, new JSONObject(IOUtil.toString(reader)));
coverity/pie
pie-core/src/main/java/com/coverity/security/pie/core/Policy.java
// Path: pie-core/src/main/java/com/coverity/security/pie/util/IOUtil.java // public class IOUtil { // public static void closeSilently(Closeable closeable) { // if (closeable != null) { // try { // closeable.close(); // } catch (IOException e) { // // Do nothing // } // } // } // // public static String readFile(File file) throws IOException { // return toString(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8)); // } // public static String readFile(String file) throws IOException { // return toString(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8)); // } // public static String readFile(URL file) throws IOException { // return toString(file.openStream()); // } // // public static String toString(InputStream is) throws IOException { // try { // return toString(new InputStreamReader(is, StandardCharsets.UTF_8)); // } finally { // closeSilently(is); // } // } // public static String toString(Reader reader) throws IOException { // StringBuilder sb = new StringBuilder(); // try { // char buffer[] = new char[4096]; // int n; // while ((n = reader.read(buffer)) > 0) { // sb.append(buffer, 0, n); // } // reader.close(); // } catch (IOException e) { // closeSilently(reader); // throw e; // } // return sb.toString(); // } // // // public static void writeFile(File file, String content) throws IOException { // writeFile(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8), content); // } // private static void writeFile(Writer fw, String content) throws IOException { // try { // fw.write(content); // fw.close(); // } catch (IOException e) { // closeSilently(fw); // throw e; // } // } // // } // // Path: pie-core/src/main/java/com/coverity/security/pie/util/PieLogger.java // public class PieLogger { // private static PieConfig pieConfig = null; // private static PrintWriter logWriter = null; // // public static void setPieConfig(PieConfig pieConfig) { // PieLogger.pieConfig = pieConfig; // if (logWriter != null) { // IOUtil.closeSilently(logWriter); // logWriter = null; // } // if (pieConfig != null && pieConfig.isLoggingEnabled()) { // try { // logWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(pieConfig.getLogPath(), true), StandardCharsets.UTF_8)); // } catch (FileNotFoundException e) { // throw new RuntimeException(e); // } // } // } // // public static enum LogLevel { // DEBUG, // INFO, // WARN, // ERROR // } // // public static void log(LogLevel logLevel, String msg, Throwable throwable) { // if (logWriter == null) { // return; // } // logWriter.append("[").append(new Date().toString()).append("] ").append(logLevel.toString()).append(": ").append(msg).append("\n"); // if (throwable != null) { // throwable.printStackTrace(logWriter); // } // logWriter.flush(); // } // // public static void log(LogLevel logLevel, String msg) { // log(logLevel, msg, null); // } // // public static void debug(String msg) { // log(LogLevel.DEBUG, msg); // } // public static void debug(String msg, Throwable throwable) { // log(LogLevel.DEBUG, msg, throwable); // } // public static void info(String msg) { // log(LogLevel.INFO, msg); // } // public static void info(String msg, Throwable throwable) { // log(LogLevel.INFO, msg, throwable); // } // public static void warn(String msg) { // log(LogLevel.WARN, msg); // } // public static void warn(String msg, Throwable throwable) { // log(LogLevel.WARN, msg, throwable); // } // public static void error(String msg) { // log(LogLevel.ERROR, msg); // } // public static void error(String msg, Throwable throwable) { // log(LogLevel.ERROR, msg, throwable); // } // // }
import com.coverity.security.pie.util.IOUtil; import com.coverity.security.pie.util.PieLogger; import org.json.JSONObject; import java.io.IOException; import java.io.Reader; import java.io.Writer; import java.util.*; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock;
FactTreeNode child = children.get(i); for (int j = 0; j < indent; j++) { writer.write(" "); } writer.write("\""); writer.write(child.value.replaceAll("\\\\", "\\\\\\\\").replaceAll("\"", "\\\\\\\"")); writer.write("\": {"); if (child.children.size() == 0) { writer.write ("}"); } else { writer.write("\n"); writePolicy(writer, child, indent+1); for (int j = 0; j < indent; j++) { writer.write(" "); } writer.write ("}"); } if (i < children.size()-1) { writer.write(","); } writer.write("\n"); } } /** * Appends the observed policy violation to this policy's list of violations. * @param facts */ protected final void logViolation(String ... facts) {
// Path: pie-core/src/main/java/com/coverity/security/pie/util/IOUtil.java // public class IOUtil { // public static void closeSilently(Closeable closeable) { // if (closeable != null) { // try { // closeable.close(); // } catch (IOException e) { // // Do nothing // } // } // } // // public static String readFile(File file) throws IOException { // return toString(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8)); // } // public static String readFile(String file) throws IOException { // return toString(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8)); // } // public static String readFile(URL file) throws IOException { // return toString(file.openStream()); // } // // public static String toString(InputStream is) throws IOException { // try { // return toString(new InputStreamReader(is, StandardCharsets.UTF_8)); // } finally { // closeSilently(is); // } // } // public static String toString(Reader reader) throws IOException { // StringBuilder sb = new StringBuilder(); // try { // char buffer[] = new char[4096]; // int n; // while ((n = reader.read(buffer)) > 0) { // sb.append(buffer, 0, n); // } // reader.close(); // } catch (IOException e) { // closeSilently(reader); // throw e; // } // return sb.toString(); // } // // // public static void writeFile(File file, String content) throws IOException { // writeFile(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8), content); // } // private static void writeFile(Writer fw, String content) throws IOException { // try { // fw.write(content); // fw.close(); // } catch (IOException e) { // closeSilently(fw); // throw e; // } // } // // } // // Path: pie-core/src/main/java/com/coverity/security/pie/util/PieLogger.java // public class PieLogger { // private static PieConfig pieConfig = null; // private static PrintWriter logWriter = null; // // public static void setPieConfig(PieConfig pieConfig) { // PieLogger.pieConfig = pieConfig; // if (logWriter != null) { // IOUtil.closeSilently(logWriter); // logWriter = null; // } // if (pieConfig != null && pieConfig.isLoggingEnabled()) { // try { // logWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(pieConfig.getLogPath(), true), StandardCharsets.UTF_8)); // } catch (FileNotFoundException e) { // throw new RuntimeException(e); // } // } // } // // public static enum LogLevel { // DEBUG, // INFO, // WARN, // ERROR // } // // public static void log(LogLevel logLevel, String msg, Throwable throwable) { // if (logWriter == null) { // return; // } // logWriter.append("[").append(new Date().toString()).append("] ").append(logLevel.toString()).append(": ").append(msg).append("\n"); // if (throwable != null) { // throwable.printStackTrace(logWriter); // } // logWriter.flush(); // } // // public static void log(LogLevel logLevel, String msg) { // log(logLevel, msg, null); // } // // public static void debug(String msg) { // log(LogLevel.DEBUG, msg); // } // public static void debug(String msg, Throwable throwable) { // log(LogLevel.DEBUG, msg, throwable); // } // public static void info(String msg) { // log(LogLevel.INFO, msg); // } // public static void info(String msg, Throwable throwable) { // log(LogLevel.INFO, msg, throwable); // } // public static void warn(String msg) { // log(LogLevel.WARN, msg); // } // public static void warn(String msg, Throwable throwable) { // log(LogLevel.WARN, msg, throwable); // } // public static void error(String msg) { // log(LogLevel.ERROR, msg); // } // public static void error(String msg, Throwable throwable) { // log(LogLevel.ERROR, msg, throwable); // } // // } // Path: pie-core/src/main/java/com/coverity/security/pie/core/Policy.java import com.coverity.security.pie.util.IOUtil; import com.coverity.security.pie.util.PieLogger; import org.json.JSONObject; import java.io.IOException; import java.io.Reader; import java.io.Writer; import java.util.*; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; FactTreeNode child = children.get(i); for (int j = 0; j < indent; j++) { writer.write(" "); } writer.write("\""); writer.write(child.value.replaceAll("\\\\", "\\\\\\\\").replaceAll("\"", "\\\\\\\"")); writer.write("\": {"); if (child.children.size() == 0) { writer.write ("}"); } else { writer.write("\n"); writePolicy(writer, child, indent+1); for (int j = 0; j < indent; j++) { writer.write(" "); } writer.write ("}"); } if (i < children.size()-1) { writer.write(","); } writer.write("\n"); } } /** * Appends the observed policy violation to this policy's list of violations. * @param facts */ protected final void logViolation(String ... facts) {
PieLogger.info("Observed policy violation: " + Arrays.toString(facts));
coverity/pie
examples/spring-security/src/main/java/com/coverity/security/pie/example/config/SampleDataLoader.java
// Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/model/Account.java // @Entity // public class Account { // // @Id @GeneratedValue // private Long id; // // @ManyToOne(optional = false) // private User user; // // @Column(nullable = false) // private BigDecimal balance; // // public User getUser() { // return user; // } // public void setUser(User user) { // this.user = user; // } // public BigDecimal getBalance() { // return balance; // } // public void setBalance(BigDecimal balance) { // this.balance = balance; // } // // // } // // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/service/AccountDao.java // @Service // public class AccountDao extends AbstractDao { // public Account getAccount(String username) { // List<?> result = getEntityManager() // .createQuery("SELECT A FROM Account A WHERE A.user.username = :username") // .setParameter("username", username) // .getResultList(); // // if (result.size() == 0) { // return null; // } // return (Account)result.get(0); // } // // @Transactional // public void addAccount(Account account) { // getEntityManager().persist(account); // } // } // // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/util/DoPrivileged.java // public class DoPrivileged { // public static <T> T asSystem(Callable<T> callable) throws Exception { // final SecurityContext priorContext = SecurityContextHolder.getContext(); // try { // SecurityContextHolder.setContext(SecurityContextHolder.createEmptyContext()); // PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken( // "system", null, Arrays.asList(new SimpleGrantedAuthority(Role.SYSTEM.toString()))); // SecurityContextHolder.getContext().setAuthentication(token); // // return callable.call(); // } finally { // SecurityContextHolder.setContext(priorContext); // } // // } // } // // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/model/Role.java // public enum Role { // GUEST, USER, ADMIN, SYSTEM; // } // // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/model/User.java // @Entity // public class User { // @Id @GeneratedValue // private Long id; // // private String username; // // private String passwordHash; // // private Role role; // // // public String getUsername() { // return username; // } // public void setUsername(String username) { // this.username = username; // } // public String getPasswordHash() { // return passwordHash; // } // public void setPasswordHash(String passwordHash) { // this.passwordHash = passwordHash; // } // public Role getRole() { // return role; // } // public void setRole(Role role) { // this.role = role; // } // } // // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/service/UserDao.java // @Service // public class UserDao extends AbstractDao { // // public List<User> getUsers() { // return castList(getEntityManager().createQuery("SELECT U FROM User U").getResultList(), User.class); // } // // @Transactional // public void addUser(User user) { // getEntityManager().persist(user); // } // // }
import java.math.BigDecimal; import java.util.concurrent.Callable; import com.coverity.security.pie.example.model.Account; import com.coverity.security.pie.example.service.AccountDao; import com.coverity.security.pie.example.util.DoPrivileged; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.security.crypto.password.PasswordEncoder; import com.coverity.security.pie.example.model.Role; import com.coverity.security.pie.example.model.User; import com.coverity.security.pie.example.service.UserDao;
package com.coverity.security.pie.example.config; public class SampleDataLoader implements ApplicationListener<ContextRefreshedEvent> { @Autowired
// Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/model/Account.java // @Entity // public class Account { // // @Id @GeneratedValue // private Long id; // // @ManyToOne(optional = false) // private User user; // // @Column(nullable = false) // private BigDecimal balance; // // public User getUser() { // return user; // } // public void setUser(User user) { // this.user = user; // } // public BigDecimal getBalance() { // return balance; // } // public void setBalance(BigDecimal balance) { // this.balance = balance; // } // // // } // // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/service/AccountDao.java // @Service // public class AccountDao extends AbstractDao { // public Account getAccount(String username) { // List<?> result = getEntityManager() // .createQuery("SELECT A FROM Account A WHERE A.user.username = :username") // .setParameter("username", username) // .getResultList(); // // if (result.size() == 0) { // return null; // } // return (Account)result.get(0); // } // // @Transactional // public void addAccount(Account account) { // getEntityManager().persist(account); // } // } // // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/util/DoPrivileged.java // public class DoPrivileged { // public static <T> T asSystem(Callable<T> callable) throws Exception { // final SecurityContext priorContext = SecurityContextHolder.getContext(); // try { // SecurityContextHolder.setContext(SecurityContextHolder.createEmptyContext()); // PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken( // "system", null, Arrays.asList(new SimpleGrantedAuthority(Role.SYSTEM.toString()))); // SecurityContextHolder.getContext().setAuthentication(token); // // return callable.call(); // } finally { // SecurityContextHolder.setContext(priorContext); // } // // } // } // // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/model/Role.java // public enum Role { // GUEST, USER, ADMIN, SYSTEM; // } // // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/model/User.java // @Entity // public class User { // @Id @GeneratedValue // private Long id; // // private String username; // // private String passwordHash; // // private Role role; // // // public String getUsername() { // return username; // } // public void setUsername(String username) { // this.username = username; // } // public String getPasswordHash() { // return passwordHash; // } // public void setPasswordHash(String passwordHash) { // this.passwordHash = passwordHash; // } // public Role getRole() { // return role; // } // public void setRole(Role role) { // this.role = role; // } // } // // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/service/UserDao.java // @Service // public class UserDao extends AbstractDao { // // public List<User> getUsers() { // return castList(getEntityManager().createQuery("SELECT U FROM User U").getResultList(), User.class); // } // // @Transactional // public void addUser(User user) { // getEntityManager().persist(user); // } // // } // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/config/SampleDataLoader.java import java.math.BigDecimal; import java.util.concurrent.Callable; import com.coverity.security.pie.example.model.Account; import com.coverity.security.pie.example.service.AccountDao; import com.coverity.security.pie.example.util.DoPrivileged; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.security.crypto.password.PasswordEncoder; import com.coverity.security.pie.example.model.Role; import com.coverity.security.pie.example.model.User; import com.coverity.security.pie.example.service.UserDao; package com.coverity.security.pie.example.config; public class SampleDataLoader implements ApplicationListener<ContextRefreshedEvent> { @Autowired
private UserDao userDao;
coverity/pie
examples/spring-security/src/main/java/com/coverity/security/pie/example/config/SampleDataLoader.java
// Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/model/Account.java // @Entity // public class Account { // // @Id @GeneratedValue // private Long id; // // @ManyToOne(optional = false) // private User user; // // @Column(nullable = false) // private BigDecimal balance; // // public User getUser() { // return user; // } // public void setUser(User user) { // this.user = user; // } // public BigDecimal getBalance() { // return balance; // } // public void setBalance(BigDecimal balance) { // this.balance = balance; // } // // // } // // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/service/AccountDao.java // @Service // public class AccountDao extends AbstractDao { // public Account getAccount(String username) { // List<?> result = getEntityManager() // .createQuery("SELECT A FROM Account A WHERE A.user.username = :username") // .setParameter("username", username) // .getResultList(); // // if (result.size() == 0) { // return null; // } // return (Account)result.get(0); // } // // @Transactional // public void addAccount(Account account) { // getEntityManager().persist(account); // } // } // // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/util/DoPrivileged.java // public class DoPrivileged { // public static <T> T asSystem(Callable<T> callable) throws Exception { // final SecurityContext priorContext = SecurityContextHolder.getContext(); // try { // SecurityContextHolder.setContext(SecurityContextHolder.createEmptyContext()); // PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken( // "system", null, Arrays.asList(new SimpleGrantedAuthority(Role.SYSTEM.toString()))); // SecurityContextHolder.getContext().setAuthentication(token); // // return callable.call(); // } finally { // SecurityContextHolder.setContext(priorContext); // } // // } // } // // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/model/Role.java // public enum Role { // GUEST, USER, ADMIN, SYSTEM; // } // // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/model/User.java // @Entity // public class User { // @Id @GeneratedValue // private Long id; // // private String username; // // private String passwordHash; // // private Role role; // // // public String getUsername() { // return username; // } // public void setUsername(String username) { // this.username = username; // } // public String getPasswordHash() { // return passwordHash; // } // public void setPasswordHash(String passwordHash) { // this.passwordHash = passwordHash; // } // public Role getRole() { // return role; // } // public void setRole(Role role) { // this.role = role; // } // } // // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/service/UserDao.java // @Service // public class UserDao extends AbstractDao { // // public List<User> getUsers() { // return castList(getEntityManager().createQuery("SELECT U FROM User U").getResultList(), User.class); // } // // @Transactional // public void addUser(User user) { // getEntityManager().persist(user); // } // // }
import java.math.BigDecimal; import java.util.concurrent.Callable; import com.coverity.security.pie.example.model.Account; import com.coverity.security.pie.example.service.AccountDao; import com.coverity.security.pie.example.util.DoPrivileged; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.security.crypto.password.PasswordEncoder; import com.coverity.security.pie.example.model.Role; import com.coverity.security.pie.example.model.User; import com.coverity.security.pie.example.service.UserDao;
package com.coverity.security.pie.example.config; public class SampleDataLoader implements ApplicationListener<ContextRefreshedEvent> { @Autowired private UserDao userDao; @Autowired
// Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/model/Account.java // @Entity // public class Account { // // @Id @GeneratedValue // private Long id; // // @ManyToOne(optional = false) // private User user; // // @Column(nullable = false) // private BigDecimal balance; // // public User getUser() { // return user; // } // public void setUser(User user) { // this.user = user; // } // public BigDecimal getBalance() { // return balance; // } // public void setBalance(BigDecimal balance) { // this.balance = balance; // } // // // } // // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/service/AccountDao.java // @Service // public class AccountDao extends AbstractDao { // public Account getAccount(String username) { // List<?> result = getEntityManager() // .createQuery("SELECT A FROM Account A WHERE A.user.username = :username") // .setParameter("username", username) // .getResultList(); // // if (result.size() == 0) { // return null; // } // return (Account)result.get(0); // } // // @Transactional // public void addAccount(Account account) { // getEntityManager().persist(account); // } // } // // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/util/DoPrivileged.java // public class DoPrivileged { // public static <T> T asSystem(Callable<T> callable) throws Exception { // final SecurityContext priorContext = SecurityContextHolder.getContext(); // try { // SecurityContextHolder.setContext(SecurityContextHolder.createEmptyContext()); // PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken( // "system", null, Arrays.asList(new SimpleGrantedAuthority(Role.SYSTEM.toString()))); // SecurityContextHolder.getContext().setAuthentication(token); // // return callable.call(); // } finally { // SecurityContextHolder.setContext(priorContext); // } // // } // } // // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/model/Role.java // public enum Role { // GUEST, USER, ADMIN, SYSTEM; // } // // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/model/User.java // @Entity // public class User { // @Id @GeneratedValue // private Long id; // // private String username; // // private String passwordHash; // // private Role role; // // // public String getUsername() { // return username; // } // public void setUsername(String username) { // this.username = username; // } // public String getPasswordHash() { // return passwordHash; // } // public void setPasswordHash(String passwordHash) { // this.passwordHash = passwordHash; // } // public Role getRole() { // return role; // } // public void setRole(Role role) { // this.role = role; // } // } // // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/service/UserDao.java // @Service // public class UserDao extends AbstractDao { // // public List<User> getUsers() { // return castList(getEntityManager().createQuery("SELECT U FROM User U").getResultList(), User.class); // } // // @Transactional // public void addUser(User user) { // getEntityManager().persist(user); // } // // } // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/config/SampleDataLoader.java import java.math.BigDecimal; import java.util.concurrent.Callable; import com.coverity.security.pie.example.model.Account; import com.coverity.security.pie.example.service.AccountDao; import com.coverity.security.pie.example.util.DoPrivileged; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.security.crypto.password.PasswordEncoder; import com.coverity.security.pie.example.model.Role; import com.coverity.security.pie.example.model.User; import com.coverity.security.pie.example.service.UserDao; package com.coverity.security.pie.example.config; public class SampleDataLoader implements ApplicationListener<ContextRefreshedEvent> { @Autowired private UserDao userDao; @Autowired
private AccountDao accountDao;
coverity/pie
examples/spring-security/src/main/java/com/coverity/security/pie/example/config/SampleDataLoader.java
// Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/model/Account.java // @Entity // public class Account { // // @Id @GeneratedValue // private Long id; // // @ManyToOne(optional = false) // private User user; // // @Column(nullable = false) // private BigDecimal balance; // // public User getUser() { // return user; // } // public void setUser(User user) { // this.user = user; // } // public BigDecimal getBalance() { // return balance; // } // public void setBalance(BigDecimal balance) { // this.balance = balance; // } // // // } // // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/service/AccountDao.java // @Service // public class AccountDao extends AbstractDao { // public Account getAccount(String username) { // List<?> result = getEntityManager() // .createQuery("SELECT A FROM Account A WHERE A.user.username = :username") // .setParameter("username", username) // .getResultList(); // // if (result.size() == 0) { // return null; // } // return (Account)result.get(0); // } // // @Transactional // public void addAccount(Account account) { // getEntityManager().persist(account); // } // } // // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/util/DoPrivileged.java // public class DoPrivileged { // public static <T> T asSystem(Callable<T> callable) throws Exception { // final SecurityContext priorContext = SecurityContextHolder.getContext(); // try { // SecurityContextHolder.setContext(SecurityContextHolder.createEmptyContext()); // PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken( // "system", null, Arrays.asList(new SimpleGrantedAuthority(Role.SYSTEM.toString()))); // SecurityContextHolder.getContext().setAuthentication(token); // // return callable.call(); // } finally { // SecurityContextHolder.setContext(priorContext); // } // // } // } // // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/model/Role.java // public enum Role { // GUEST, USER, ADMIN, SYSTEM; // } // // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/model/User.java // @Entity // public class User { // @Id @GeneratedValue // private Long id; // // private String username; // // private String passwordHash; // // private Role role; // // // public String getUsername() { // return username; // } // public void setUsername(String username) { // this.username = username; // } // public String getPasswordHash() { // return passwordHash; // } // public void setPasswordHash(String passwordHash) { // this.passwordHash = passwordHash; // } // public Role getRole() { // return role; // } // public void setRole(Role role) { // this.role = role; // } // } // // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/service/UserDao.java // @Service // public class UserDao extends AbstractDao { // // public List<User> getUsers() { // return castList(getEntityManager().createQuery("SELECT U FROM User U").getResultList(), User.class); // } // // @Transactional // public void addUser(User user) { // getEntityManager().persist(user); // } // // }
import java.math.BigDecimal; import java.util.concurrent.Callable; import com.coverity.security.pie.example.model.Account; import com.coverity.security.pie.example.service.AccountDao; import com.coverity.security.pie.example.util.DoPrivileged; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.security.crypto.password.PasswordEncoder; import com.coverity.security.pie.example.model.Role; import com.coverity.security.pie.example.model.User; import com.coverity.security.pie.example.service.UserDao;
package com.coverity.security.pie.example.config; public class SampleDataLoader implements ApplicationListener<ContextRefreshedEvent> { @Autowired private UserDao userDao; @Autowired private AccountDao accountDao; @Autowired private PasswordEncoder passwordEncoder; @Override public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) { try {
// Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/model/Account.java // @Entity // public class Account { // // @Id @GeneratedValue // private Long id; // // @ManyToOne(optional = false) // private User user; // // @Column(nullable = false) // private BigDecimal balance; // // public User getUser() { // return user; // } // public void setUser(User user) { // this.user = user; // } // public BigDecimal getBalance() { // return balance; // } // public void setBalance(BigDecimal balance) { // this.balance = balance; // } // // // } // // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/service/AccountDao.java // @Service // public class AccountDao extends AbstractDao { // public Account getAccount(String username) { // List<?> result = getEntityManager() // .createQuery("SELECT A FROM Account A WHERE A.user.username = :username") // .setParameter("username", username) // .getResultList(); // // if (result.size() == 0) { // return null; // } // return (Account)result.get(0); // } // // @Transactional // public void addAccount(Account account) { // getEntityManager().persist(account); // } // } // // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/util/DoPrivileged.java // public class DoPrivileged { // public static <T> T asSystem(Callable<T> callable) throws Exception { // final SecurityContext priorContext = SecurityContextHolder.getContext(); // try { // SecurityContextHolder.setContext(SecurityContextHolder.createEmptyContext()); // PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken( // "system", null, Arrays.asList(new SimpleGrantedAuthority(Role.SYSTEM.toString()))); // SecurityContextHolder.getContext().setAuthentication(token); // // return callable.call(); // } finally { // SecurityContextHolder.setContext(priorContext); // } // // } // } // // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/model/Role.java // public enum Role { // GUEST, USER, ADMIN, SYSTEM; // } // // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/model/User.java // @Entity // public class User { // @Id @GeneratedValue // private Long id; // // private String username; // // private String passwordHash; // // private Role role; // // // public String getUsername() { // return username; // } // public void setUsername(String username) { // this.username = username; // } // public String getPasswordHash() { // return passwordHash; // } // public void setPasswordHash(String passwordHash) { // this.passwordHash = passwordHash; // } // public Role getRole() { // return role; // } // public void setRole(Role role) { // this.role = role; // } // } // // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/service/UserDao.java // @Service // public class UserDao extends AbstractDao { // // public List<User> getUsers() { // return castList(getEntityManager().createQuery("SELECT U FROM User U").getResultList(), User.class); // } // // @Transactional // public void addUser(User user) { // getEntityManager().persist(user); // } // // } // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/config/SampleDataLoader.java import java.math.BigDecimal; import java.util.concurrent.Callable; import com.coverity.security.pie.example.model.Account; import com.coverity.security.pie.example.service.AccountDao; import com.coverity.security.pie.example.util.DoPrivileged; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.security.crypto.password.PasswordEncoder; import com.coverity.security.pie.example.model.Role; import com.coverity.security.pie.example.model.User; import com.coverity.security.pie.example.service.UserDao; package com.coverity.security.pie.example.config; public class SampleDataLoader implements ApplicationListener<ContextRefreshedEvent> { @Autowired private UserDao userDao; @Autowired private AccountDao accountDao; @Autowired private PasswordEncoder passwordEncoder; @Override public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) { try {
DoPrivileged.asSystem(new Callable<Void>() {
coverity/pie
examples/spring-security/src/main/java/com/coverity/security/pie/example/config/SampleDataLoader.java
// Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/model/Account.java // @Entity // public class Account { // // @Id @GeneratedValue // private Long id; // // @ManyToOne(optional = false) // private User user; // // @Column(nullable = false) // private BigDecimal balance; // // public User getUser() { // return user; // } // public void setUser(User user) { // this.user = user; // } // public BigDecimal getBalance() { // return balance; // } // public void setBalance(BigDecimal balance) { // this.balance = balance; // } // // // } // // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/service/AccountDao.java // @Service // public class AccountDao extends AbstractDao { // public Account getAccount(String username) { // List<?> result = getEntityManager() // .createQuery("SELECT A FROM Account A WHERE A.user.username = :username") // .setParameter("username", username) // .getResultList(); // // if (result.size() == 0) { // return null; // } // return (Account)result.get(0); // } // // @Transactional // public void addAccount(Account account) { // getEntityManager().persist(account); // } // } // // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/util/DoPrivileged.java // public class DoPrivileged { // public static <T> T asSystem(Callable<T> callable) throws Exception { // final SecurityContext priorContext = SecurityContextHolder.getContext(); // try { // SecurityContextHolder.setContext(SecurityContextHolder.createEmptyContext()); // PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken( // "system", null, Arrays.asList(new SimpleGrantedAuthority(Role.SYSTEM.toString()))); // SecurityContextHolder.getContext().setAuthentication(token); // // return callable.call(); // } finally { // SecurityContextHolder.setContext(priorContext); // } // // } // } // // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/model/Role.java // public enum Role { // GUEST, USER, ADMIN, SYSTEM; // } // // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/model/User.java // @Entity // public class User { // @Id @GeneratedValue // private Long id; // // private String username; // // private String passwordHash; // // private Role role; // // // public String getUsername() { // return username; // } // public void setUsername(String username) { // this.username = username; // } // public String getPasswordHash() { // return passwordHash; // } // public void setPasswordHash(String passwordHash) { // this.passwordHash = passwordHash; // } // public Role getRole() { // return role; // } // public void setRole(Role role) { // this.role = role; // } // } // // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/service/UserDao.java // @Service // public class UserDao extends AbstractDao { // // public List<User> getUsers() { // return castList(getEntityManager().createQuery("SELECT U FROM User U").getResultList(), User.class); // } // // @Transactional // public void addUser(User user) { // getEntityManager().persist(user); // } // // }
import java.math.BigDecimal; import java.util.concurrent.Callable; import com.coverity.security.pie.example.model.Account; import com.coverity.security.pie.example.service.AccountDao; import com.coverity.security.pie.example.util.DoPrivileged; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.security.crypto.password.PasswordEncoder; import com.coverity.security.pie.example.model.Role; import com.coverity.security.pie.example.model.User; import com.coverity.security.pie.example.service.UserDao;
package com.coverity.security.pie.example.config; public class SampleDataLoader implements ApplicationListener<ContextRefreshedEvent> { @Autowired private UserDao userDao; @Autowired private AccountDao accountDao; @Autowired private PasswordEncoder passwordEncoder; @Override public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) { try { DoPrivileged.asSystem(new Callable<Void>() { @Override public Void call() throws Exception {
// Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/model/Account.java // @Entity // public class Account { // // @Id @GeneratedValue // private Long id; // // @ManyToOne(optional = false) // private User user; // // @Column(nullable = false) // private BigDecimal balance; // // public User getUser() { // return user; // } // public void setUser(User user) { // this.user = user; // } // public BigDecimal getBalance() { // return balance; // } // public void setBalance(BigDecimal balance) { // this.balance = balance; // } // // // } // // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/service/AccountDao.java // @Service // public class AccountDao extends AbstractDao { // public Account getAccount(String username) { // List<?> result = getEntityManager() // .createQuery("SELECT A FROM Account A WHERE A.user.username = :username") // .setParameter("username", username) // .getResultList(); // // if (result.size() == 0) { // return null; // } // return (Account)result.get(0); // } // // @Transactional // public void addAccount(Account account) { // getEntityManager().persist(account); // } // } // // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/util/DoPrivileged.java // public class DoPrivileged { // public static <T> T asSystem(Callable<T> callable) throws Exception { // final SecurityContext priorContext = SecurityContextHolder.getContext(); // try { // SecurityContextHolder.setContext(SecurityContextHolder.createEmptyContext()); // PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken( // "system", null, Arrays.asList(new SimpleGrantedAuthority(Role.SYSTEM.toString()))); // SecurityContextHolder.getContext().setAuthentication(token); // // return callable.call(); // } finally { // SecurityContextHolder.setContext(priorContext); // } // // } // } // // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/model/Role.java // public enum Role { // GUEST, USER, ADMIN, SYSTEM; // } // // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/model/User.java // @Entity // public class User { // @Id @GeneratedValue // private Long id; // // private String username; // // private String passwordHash; // // private Role role; // // // public String getUsername() { // return username; // } // public void setUsername(String username) { // this.username = username; // } // public String getPasswordHash() { // return passwordHash; // } // public void setPasswordHash(String passwordHash) { // this.passwordHash = passwordHash; // } // public Role getRole() { // return role; // } // public void setRole(Role role) { // this.role = role; // } // } // // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/service/UserDao.java // @Service // public class UserDao extends AbstractDao { // // public List<User> getUsers() { // return castList(getEntityManager().createQuery("SELECT U FROM User U").getResultList(), User.class); // } // // @Transactional // public void addUser(User user) { // getEntityManager().persist(user); // } // // } // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/config/SampleDataLoader.java import java.math.BigDecimal; import java.util.concurrent.Callable; import com.coverity.security.pie.example.model.Account; import com.coverity.security.pie.example.service.AccountDao; import com.coverity.security.pie.example.util.DoPrivileged; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.security.crypto.password.PasswordEncoder; import com.coverity.security.pie.example.model.Role; import com.coverity.security.pie.example.model.User; import com.coverity.security.pie.example.service.UserDao; package com.coverity.security.pie.example.config; public class SampleDataLoader implements ApplicationListener<ContextRefreshedEvent> { @Autowired private UserDao userDao; @Autowired private AccountDao accountDao; @Autowired private PasswordEncoder passwordEncoder; @Override public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) { try { DoPrivileged.asSystem(new Callable<Void>() { @Override public Void call() throws Exception {
User user = new User();
coverity/pie
examples/spring-security/src/main/java/com/coverity/security/pie/example/config/SampleDataLoader.java
// Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/model/Account.java // @Entity // public class Account { // // @Id @GeneratedValue // private Long id; // // @ManyToOne(optional = false) // private User user; // // @Column(nullable = false) // private BigDecimal balance; // // public User getUser() { // return user; // } // public void setUser(User user) { // this.user = user; // } // public BigDecimal getBalance() { // return balance; // } // public void setBalance(BigDecimal balance) { // this.balance = balance; // } // // // } // // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/service/AccountDao.java // @Service // public class AccountDao extends AbstractDao { // public Account getAccount(String username) { // List<?> result = getEntityManager() // .createQuery("SELECT A FROM Account A WHERE A.user.username = :username") // .setParameter("username", username) // .getResultList(); // // if (result.size() == 0) { // return null; // } // return (Account)result.get(0); // } // // @Transactional // public void addAccount(Account account) { // getEntityManager().persist(account); // } // } // // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/util/DoPrivileged.java // public class DoPrivileged { // public static <T> T asSystem(Callable<T> callable) throws Exception { // final SecurityContext priorContext = SecurityContextHolder.getContext(); // try { // SecurityContextHolder.setContext(SecurityContextHolder.createEmptyContext()); // PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken( // "system", null, Arrays.asList(new SimpleGrantedAuthority(Role.SYSTEM.toString()))); // SecurityContextHolder.getContext().setAuthentication(token); // // return callable.call(); // } finally { // SecurityContextHolder.setContext(priorContext); // } // // } // } // // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/model/Role.java // public enum Role { // GUEST, USER, ADMIN, SYSTEM; // } // // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/model/User.java // @Entity // public class User { // @Id @GeneratedValue // private Long id; // // private String username; // // private String passwordHash; // // private Role role; // // // public String getUsername() { // return username; // } // public void setUsername(String username) { // this.username = username; // } // public String getPasswordHash() { // return passwordHash; // } // public void setPasswordHash(String passwordHash) { // this.passwordHash = passwordHash; // } // public Role getRole() { // return role; // } // public void setRole(Role role) { // this.role = role; // } // } // // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/service/UserDao.java // @Service // public class UserDao extends AbstractDao { // // public List<User> getUsers() { // return castList(getEntityManager().createQuery("SELECT U FROM User U").getResultList(), User.class); // } // // @Transactional // public void addUser(User user) { // getEntityManager().persist(user); // } // // }
import java.math.BigDecimal; import java.util.concurrent.Callable; import com.coverity.security.pie.example.model.Account; import com.coverity.security.pie.example.service.AccountDao; import com.coverity.security.pie.example.util.DoPrivileged; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.security.crypto.password.PasswordEncoder; import com.coverity.security.pie.example.model.Role; import com.coverity.security.pie.example.model.User; import com.coverity.security.pie.example.service.UserDao;
package com.coverity.security.pie.example.config; public class SampleDataLoader implements ApplicationListener<ContextRefreshedEvent> { @Autowired private UserDao userDao; @Autowired private AccountDao accountDao; @Autowired private PasswordEncoder passwordEncoder; @Override public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) { try { DoPrivileged.asSystem(new Callable<Void>() { @Override public Void call() throws Exception { User user = new User(); user.setUsername("Alice"); user.setPasswordHash(passwordEncoder.encode("alice"));
// Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/model/Account.java // @Entity // public class Account { // // @Id @GeneratedValue // private Long id; // // @ManyToOne(optional = false) // private User user; // // @Column(nullable = false) // private BigDecimal balance; // // public User getUser() { // return user; // } // public void setUser(User user) { // this.user = user; // } // public BigDecimal getBalance() { // return balance; // } // public void setBalance(BigDecimal balance) { // this.balance = balance; // } // // // } // // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/service/AccountDao.java // @Service // public class AccountDao extends AbstractDao { // public Account getAccount(String username) { // List<?> result = getEntityManager() // .createQuery("SELECT A FROM Account A WHERE A.user.username = :username") // .setParameter("username", username) // .getResultList(); // // if (result.size() == 0) { // return null; // } // return (Account)result.get(0); // } // // @Transactional // public void addAccount(Account account) { // getEntityManager().persist(account); // } // } // // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/util/DoPrivileged.java // public class DoPrivileged { // public static <T> T asSystem(Callable<T> callable) throws Exception { // final SecurityContext priorContext = SecurityContextHolder.getContext(); // try { // SecurityContextHolder.setContext(SecurityContextHolder.createEmptyContext()); // PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken( // "system", null, Arrays.asList(new SimpleGrantedAuthority(Role.SYSTEM.toString()))); // SecurityContextHolder.getContext().setAuthentication(token); // // return callable.call(); // } finally { // SecurityContextHolder.setContext(priorContext); // } // // } // } // // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/model/Role.java // public enum Role { // GUEST, USER, ADMIN, SYSTEM; // } // // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/model/User.java // @Entity // public class User { // @Id @GeneratedValue // private Long id; // // private String username; // // private String passwordHash; // // private Role role; // // // public String getUsername() { // return username; // } // public void setUsername(String username) { // this.username = username; // } // public String getPasswordHash() { // return passwordHash; // } // public void setPasswordHash(String passwordHash) { // this.passwordHash = passwordHash; // } // public Role getRole() { // return role; // } // public void setRole(Role role) { // this.role = role; // } // } // // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/service/UserDao.java // @Service // public class UserDao extends AbstractDao { // // public List<User> getUsers() { // return castList(getEntityManager().createQuery("SELECT U FROM User U").getResultList(), User.class); // } // // @Transactional // public void addUser(User user) { // getEntityManager().persist(user); // } // // } // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/config/SampleDataLoader.java import java.math.BigDecimal; import java.util.concurrent.Callable; import com.coverity.security.pie.example.model.Account; import com.coverity.security.pie.example.service.AccountDao; import com.coverity.security.pie.example.util.DoPrivileged; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.security.crypto.password.PasswordEncoder; import com.coverity.security.pie.example.model.Role; import com.coverity.security.pie.example.model.User; import com.coverity.security.pie.example.service.UserDao; package com.coverity.security.pie.example.config; public class SampleDataLoader implements ApplicationListener<ContextRefreshedEvent> { @Autowired private UserDao userDao; @Autowired private AccountDao accountDao; @Autowired private PasswordEncoder passwordEncoder; @Override public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) { try { DoPrivileged.asSystem(new Callable<Void>() { @Override public Void call() throws Exception { User user = new User(); user.setUsername("Alice"); user.setPasswordHash(passwordEncoder.encode("alice"));
user.setRole(Role.GUEST);
coverity/pie
examples/spring-security/src/main/java/com/coverity/security/pie/example/config/SampleDataLoader.java
// Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/model/Account.java // @Entity // public class Account { // // @Id @GeneratedValue // private Long id; // // @ManyToOne(optional = false) // private User user; // // @Column(nullable = false) // private BigDecimal balance; // // public User getUser() { // return user; // } // public void setUser(User user) { // this.user = user; // } // public BigDecimal getBalance() { // return balance; // } // public void setBalance(BigDecimal balance) { // this.balance = balance; // } // // // } // // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/service/AccountDao.java // @Service // public class AccountDao extends AbstractDao { // public Account getAccount(String username) { // List<?> result = getEntityManager() // .createQuery("SELECT A FROM Account A WHERE A.user.username = :username") // .setParameter("username", username) // .getResultList(); // // if (result.size() == 0) { // return null; // } // return (Account)result.get(0); // } // // @Transactional // public void addAccount(Account account) { // getEntityManager().persist(account); // } // } // // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/util/DoPrivileged.java // public class DoPrivileged { // public static <T> T asSystem(Callable<T> callable) throws Exception { // final SecurityContext priorContext = SecurityContextHolder.getContext(); // try { // SecurityContextHolder.setContext(SecurityContextHolder.createEmptyContext()); // PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken( // "system", null, Arrays.asList(new SimpleGrantedAuthority(Role.SYSTEM.toString()))); // SecurityContextHolder.getContext().setAuthentication(token); // // return callable.call(); // } finally { // SecurityContextHolder.setContext(priorContext); // } // // } // } // // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/model/Role.java // public enum Role { // GUEST, USER, ADMIN, SYSTEM; // } // // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/model/User.java // @Entity // public class User { // @Id @GeneratedValue // private Long id; // // private String username; // // private String passwordHash; // // private Role role; // // // public String getUsername() { // return username; // } // public void setUsername(String username) { // this.username = username; // } // public String getPasswordHash() { // return passwordHash; // } // public void setPasswordHash(String passwordHash) { // this.passwordHash = passwordHash; // } // public Role getRole() { // return role; // } // public void setRole(Role role) { // this.role = role; // } // } // // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/service/UserDao.java // @Service // public class UserDao extends AbstractDao { // // public List<User> getUsers() { // return castList(getEntityManager().createQuery("SELECT U FROM User U").getResultList(), User.class); // } // // @Transactional // public void addUser(User user) { // getEntityManager().persist(user); // } // // }
import java.math.BigDecimal; import java.util.concurrent.Callable; import com.coverity.security.pie.example.model.Account; import com.coverity.security.pie.example.service.AccountDao; import com.coverity.security.pie.example.util.DoPrivileged; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.security.crypto.password.PasswordEncoder; import com.coverity.security.pie.example.model.Role; import com.coverity.security.pie.example.model.User; import com.coverity.security.pie.example.service.UserDao;
package com.coverity.security.pie.example.config; public class SampleDataLoader implements ApplicationListener<ContextRefreshedEvent> { @Autowired private UserDao userDao; @Autowired private AccountDao accountDao; @Autowired private PasswordEncoder passwordEncoder; @Override public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) { try { DoPrivileged.asSystem(new Callable<Void>() { @Override public Void call() throws Exception { User user = new User(); user.setUsername("Alice"); user.setPasswordHash(passwordEncoder.encode("alice")); user.setRole(Role.GUEST); userDao.addUser(user); user = new User(); user.setUsername("Bob"); user.setPasswordHash(passwordEncoder.encode("bob")); user.setRole(Role.USER); userDao.addUser(user);
// Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/model/Account.java // @Entity // public class Account { // // @Id @GeneratedValue // private Long id; // // @ManyToOne(optional = false) // private User user; // // @Column(nullable = false) // private BigDecimal balance; // // public User getUser() { // return user; // } // public void setUser(User user) { // this.user = user; // } // public BigDecimal getBalance() { // return balance; // } // public void setBalance(BigDecimal balance) { // this.balance = balance; // } // // // } // // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/service/AccountDao.java // @Service // public class AccountDao extends AbstractDao { // public Account getAccount(String username) { // List<?> result = getEntityManager() // .createQuery("SELECT A FROM Account A WHERE A.user.username = :username") // .setParameter("username", username) // .getResultList(); // // if (result.size() == 0) { // return null; // } // return (Account)result.get(0); // } // // @Transactional // public void addAccount(Account account) { // getEntityManager().persist(account); // } // } // // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/util/DoPrivileged.java // public class DoPrivileged { // public static <T> T asSystem(Callable<T> callable) throws Exception { // final SecurityContext priorContext = SecurityContextHolder.getContext(); // try { // SecurityContextHolder.setContext(SecurityContextHolder.createEmptyContext()); // PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken( // "system", null, Arrays.asList(new SimpleGrantedAuthority(Role.SYSTEM.toString()))); // SecurityContextHolder.getContext().setAuthentication(token); // // return callable.call(); // } finally { // SecurityContextHolder.setContext(priorContext); // } // // } // } // // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/model/Role.java // public enum Role { // GUEST, USER, ADMIN, SYSTEM; // } // // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/model/User.java // @Entity // public class User { // @Id @GeneratedValue // private Long id; // // private String username; // // private String passwordHash; // // private Role role; // // // public String getUsername() { // return username; // } // public void setUsername(String username) { // this.username = username; // } // public String getPasswordHash() { // return passwordHash; // } // public void setPasswordHash(String passwordHash) { // this.passwordHash = passwordHash; // } // public Role getRole() { // return role; // } // public void setRole(Role role) { // this.role = role; // } // } // // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/service/UserDao.java // @Service // public class UserDao extends AbstractDao { // // public List<User> getUsers() { // return castList(getEntityManager().createQuery("SELECT U FROM User U").getResultList(), User.class); // } // // @Transactional // public void addUser(User user) { // getEntityManager().persist(user); // } // // } // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/config/SampleDataLoader.java import java.math.BigDecimal; import java.util.concurrent.Callable; import com.coverity.security.pie.example.model.Account; import com.coverity.security.pie.example.service.AccountDao; import com.coverity.security.pie.example.util.DoPrivileged; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.security.crypto.password.PasswordEncoder; import com.coverity.security.pie.example.model.Role; import com.coverity.security.pie.example.model.User; import com.coverity.security.pie.example.service.UserDao; package com.coverity.security.pie.example.config; public class SampleDataLoader implements ApplicationListener<ContextRefreshedEvent> { @Autowired private UserDao userDao; @Autowired private AccountDao accountDao; @Autowired private PasswordEncoder passwordEncoder; @Override public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) { try { DoPrivileged.asSystem(new Callable<Void>() { @Override public Void call() throws Exception { User user = new User(); user.setUsername("Alice"); user.setPasswordHash(passwordEncoder.encode("alice")); user.setRole(Role.GUEST); userDao.addUser(user); user = new User(); user.setUsername("Bob"); user.setPasswordHash(passwordEncoder.encode("bob")); user.setRole(Role.USER); userDao.addUser(user);
Account account = new Account();
coverity/pie
pie-csp/src/main/java/com/coverity/security/pie/policy/csp/CspEnforcementFilter.java
// Path: pie-core/src/main/java/com/coverity/security/pie/core/PolicyConfig.java // public class PolicyConfig { // private final String name; // private final PieConfig pieConfig; // // public PolicyConfig(String name, PieConfig pieConfig) { // this.name = name; // this.pieConfig = pieConfig; // } // // public boolean isEnabled() { // return getBoolean("isEnabled", true); // } // // public boolean isReportOnlyMode() { // return getBoolean("isReportOnlyMode", true); // } // // public boolean isCollapseEnabled() { // return getBoolean("isCollapseEnabled", true); // } // // public URL getPolicyFile() { // String policyFile = getProperty("policyFile"); // if (policyFile != null) { // try { // return new URL(policyFile); // } catch (MalformedURLException e) { // throw new IllegalStateException("Invalid policy URL: " + policyFile); // } // } // URL resource = this.getClass().getClassLoader().getResource(name + ".policy"); // if (resource != null) { // return resource; // } // String catalinaHome = System.getProperty("catalina.home"); // if (catalinaHome != null) { // try { // return new File(catalinaHome + File.separatorChar + "conf" + File.separatorChar + name + ".policy").toURI().toURL(); // } catch (MalformedURLException e) { // throw new IllegalStateException("Could not build default policy file path."); // } // } // // // Default to file in the CWD // try { // return new File(name + ".policy").toURI().toURL(); // } catch (MalformedURLException e) { // throw new RuntimeException(e); // } // } // // public boolean getBoolean(String prop, boolean defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Boolean.parseBoolean(v); // } // public int getInteger(String prop, int defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Integer.parseInt(v); // } // // // public String getProperty(String name) { // return pieConfig.getProperties().getProperty(this.name + "." + name); // } // } // // Path: pie-core/src/main/java/com/coverity/security/pie/util/IOUtil.java // public class IOUtil { // public static void closeSilently(Closeable closeable) { // if (closeable != null) { // try { // closeable.close(); // } catch (IOException e) { // // Do nothing // } // } // } // // public static String readFile(File file) throws IOException { // return toString(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8)); // } // public static String readFile(String file) throws IOException { // return toString(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8)); // } // public static String readFile(URL file) throws IOException { // return toString(file.openStream()); // } // // public static String toString(InputStream is) throws IOException { // try { // return toString(new InputStreamReader(is, StandardCharsets.UTF_8)); // } finally { // closeSilently(is); // } // } // public static String toString(Reader reader) throws IOException { // StringBuilder sb = new StringBuilder(); // try { // char buffer[] = new char[4096]; // int n; // while ((n = reader.read(buffer)) > 0) { // sb.append(buffer, 0, n); // } // reader.close(); // } catch (IOException e) { // closeSilently(reader); // throw e; // } // return sb.toString(); // } // // // public static void writeFile(File file, String content) throws IOException { // writeFile(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8), content); // } // private static void writeFile(Writer fw, String content) throws IOException { // try { // fw.write(content); // fw.close(); // } catch (IOException e) { // closeSilently(fw); // throw e; // } // } // // }
import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.json.JSONException; import org.json.JSONObject; import com.coverity.security.pie.core.PolicyConfig; import com.coverity.security.pie.util.IOUtil;
package com.coverity.security.pie.policy.csp; /** * A servlet filter which adds the CSP directive to the response and which handles violation reports send by the agent. */ public class CspEnforcementFilter implements Filter { public static final String REPORT_URI = "/a379568856ef23aPIE19bc95ce4e2f7fd2b"; private final CspPolicy policy;
// Path: pie-core/src/main/java/com/coverity/security/pie/core/PolicyConfig.java // public class PolicyConfig { // private final String name; // private final PieConfig pieConfig; // // public PolicyConfig(String name, PieConfig pieConfig) { // this.name = name; // this.pieConfig = pieConfig; // } // // public boolean isEnabled() { // return getBoolean("isEnabled", true); // } // // public boolean isReportOnlyMode() { // return getBoolean("isReportOnlyMode", true); // } // // public boolean isCollapseEnabled() { // return getBoolean("isCollapseEnabled", true); // } // // public URL getPolicyFile() { // String policyFile = getProperty("policyFile"); // if (policyFile != null) { // try { // return new URL(policyFile); // } catch (MalformedURLException e) { // throw new IllegalStateException("Invalid policy URL: " + policyFile); // } // } // URL resource = this.getClass().getClassLoader().getResource(name + ".policy"); // if (resource != null) { // return resource; // } // String catalinaHome = System.getProperty("catalina.home"); // if (catalinaHome != null) { // try { // return new File(catalinaHome + File.separatorChar + "conf" + File.separatorChar + name + ".policy").toURI().toURL(); // } catch (MalformedURLException e) { // throw new IllegalStateException("Could not build default policy file path."); // } // } // // // Default to file in the CWD // try { // return new File(name + ".policy").toURI().toURL(); // } catch (MalformedURLException e) { // throw new RuntimeException(e); // } // } // // public boolean getBoolean(String prop, boolean defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Boolean.parseBoolean(v); // } // public int getInteger(String prop, int defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Integer.parseInt(v); // } // // // public String getProperty(String name) { // return pieConfig.getProperties().getProperty(this.name + "." + name); // } // } // // Path: pie-core/src/main/java/com/coverity/security/pie/util/IOUtil.java // public class IOUtil { // public static void closeSilently(Closeable closeable) { // if (closeable != null) { // try { // closeable.close(); // } catch (IOException e) { // // Do nothing // } // } // } // // public static String readFile(File file) throws IOException { // return toString(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8)); // } // public static String readFile(String file) throws IOException { // return toString(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8)); // } // public static String readFile(URL file) throws IOException { // return toString(file.openStream()); // } // // public static String toString(InputStream is) throws IOException { // try { // return toString(new InputStreamReader(is, StandardCharsets.UTF_8)); // } finally { // closeSilently(is); // } // } // public static String toString(Reader reader) throws IOException { // StringBuilder sb = new StringBuilder(); // try { // char buffer[] = new char[4096]; // int n; // while ((n = reader.read(buffer)) > 0) { // sb.append(buffer, 0, n); // } // reader.close(); // } catch (IOException e) { // closeSilently(reader); // throw e; // } // return sb.toString(); // } // // // public static void writeFile(File file, String content) throws IOException { // writeFile(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8), content); // } // private static void writeFile(Writer fw, String content) throws IOException { // try { // fw.write(content); // fw.close(); // } catch (IOException e) { // closeSilently(fw); // throw e; // } // } // // } // Path: pie-csp/src/main/java/com/coverity/security/pie/policy/csp/CspEnforcementFilter.java import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.json.JSONException; import org.json.JSONObject; import com.coverity.security.pie.core.PolicyConfig; import com.coverity.security.pie.util.IOUtil; package com.coverity.security.pie.policy.csp; /** * A servlet filter which adds the CSP directive to the response and which handles violation reports send by the agent. */ public class CspEnforcementFilter implements Filter { public static final String REPORT_URI = "/a379568856ef23aPIE19bc95ce4e2f7fd2b"; private final CspPolicy policy;
private final PolicyConfig policyConfig;
coverity/pie
pie-csp/src/main/java/com/coverity/security/pie/policy/csp/CspEnforcementFilter.java
// Path: pie-core/src/main/java/com/coverity/security/pie/core/PolicyConfig.java // public class PolicyConfig { // private final String name; // private final PieConfig pieConfig; // // public PolicyConfig(String name, PieConfig pieConfig) { // this.name = name; // this.pieConfig = pieConfig; // } // // public boolean isEnabled() { // return getBoolean("isEnabled", true); // } // // public boolean isReportOnlyMode() { // return getBoolean("isReportOnlyMode", true); // } // // public boolean isCollapseEnabled() { // return getBoolean("isCollapseEnabled", true); // } // // public URL getPolicyFile() { // String policyFile = getProperty("policyFile"); // if (policyFile != null) { // try { // return new URL(policyFile); // } catch (MalformedURLException e) { // throw new IllegalStateException("Invalid policy URL: " + policyFile); // } // } // URL resource = this.getClass().getClassLoader().getResource(name + ".policy"); // if (resource != null) { // return resource; // } // String catalinaHome = System.getProperty("catalina.home"); // if (catalinaHome != null) { // try { // return new File(catalinaHome + File.separatorChar + "conf" + File.separatorChar + name + ".policy").toURI().toURL(); // } catch (MalformedURLException e) { // throw new IllegalStateException("Could not build default policy file path."); // } // } // // // Default to file in the CWD // try { // return new File(name + ".policy").toURI().toURL(); // } catch (MalformedURLException e) { // throw new RuntimeException(e); // } // } // // public boolean getBoolean(String prop, boolean defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Boolean.parseBoolean(v); // } // public int getInteger(String prop, int defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Integer.parseInt(v); // } // // // public String getProperty(String name) { // return pieConfig.getProperties().getProperty(this.name + "." + name); // } // } // // Path: pie-core/src/main/java/com/coverity/security/pie/util/IOUtil.java // public class IOUtil { // public static void closeSilently(Closeable closeable) { // if (closeable != null) { // try { // closeable.close(); // } catch (IOException e) { // // Do nothing // } // } // } // // public static String readFile(File file) throws IOException { // return toString(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8)); // } // public static String readFile(String file) throws IOException { // return toString(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8)); // } // public static String readFile(URL file) throws IOException { // return toString(file.openStream()); // } // // public static String toString(InputStream is) throws IOException { // try { // return toString(new InputStreamReader(is, StandardCharsets.UTF_8)); // } finally { // closeSilently(is); // } // } // public static String toString(Reader reader) throws IOException { // StringBuilder sb = new StringBuilder(); // try { // char buffer[] = new char[4096]; // int n; // while ((n = reader.read(buffer)) > 0) { // sb.append(buffer, 0, n); // } // reader.close(); // } catch (IOException e) { // closeSilently(reader); // throw e; // } // return sb.toString(); // } // // // public static void writeFile(File file, String content) throws IOException { // writeFile(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8), content); // } // private static void writeFile(Writer fw, String content) throws IOException { // try { // fw.write(content); // fw.close(); // } catch (IOException e) { // closeSilently(fw); // throw e; // } // } // // }
import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.json.JSONException; import org.json.JSONObject; import com.coverity.security.pie.core.PolicyConfig; import com.coverity.security.pie.util.IOUtil;
package com.coverity.security.pie.policy.csp; /** * A servlet filter which adds the CSP directive to the response and which handles violation reports send by the agent. */ public class CspEnforcementFilter implements Filter { public static final String REPORT_URI = "/a379568856ef23aPIE19bc95ce4e2f7fd2b"; private final CspPolicy policy; private final PolicyConfig policyConfig; public CspEnforcementFilter(CspPolicy policy, PolicyConfig policyConfig) { this.policy = policy; this.policyConfig = policyConfig; } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (request == null || response == null || !(request instanceof HttpServletRequest) || !(response instanceof HttpServletResponse)) { chain.doFilter(request, response); return; } HttpServletRequest httpServletRequest = (HttpServletRequest)request; HttpServletResponse httpServletResponse = (HttpServletResponse)response; if (REPORT_URI.equals(httpServletRequest.getRequestURI())) {
// Path: pie-core/src/main/java/com/coverity/security/pie/core/PolicyConfig.java // public class PolicyConfig { // private final String name; // private final PieConfig pieConfig; // // public PolicyConfig(String name, PieConfig pieConfig) { // this.name = name; // this.pieConfig = pieConfig; // } // // public boolean isEnabled() { // return getBoolean("isEnabled", true); // } // // public boolean isReportOnlyMode() { // return getBoolean("isReportOnlyMode", true); // } // // public boolean isCollapseEnabled() { // return getBoolean("isCollapseEnabled", true); // } // // public URL getPolicyFile() { // String policyFile = getProperty("policyFile"); // if (policyFile != null) { // try { // return new URL(policyFile); // } catch (MalformedURLException e) { // throw new IllegalStateException("Invalid policy URL: " + policyFile); // } // } // URL resource = this.getClass().getClassLoader().getResource(name + ".policy"); // if (resource != null) { // return resource; // } // String catalinaHome = System.getProperty("catalina.home"); // if (catalinaHome != null) { // try { // return new File(catalinaHome + File.separatorChar + "conf" + File.separatorChar + name + ".policy").toURI().toURL(); // } catch (MalformedURLException e) { // throw new IllegalStateException("Could not build default policy file path."); // } // } // // // Default to file in the CWD // try { // return new File(name + ".policy").toURI().toURL(); // } catch (MalformedURLException e) { // throw new RuntimeException(e); // } // } // // public boolean getBoolean(String prop, boolean defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Boolean.parseBoolean(v); // } // public int getInteger(String prop, int defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Integer.parseInt(v); // } // // // public String getProperty(String name) { // return pieConfig.getProperties().getProperty(this.name + "." + name); // } // } // // Path: pie-core/src/main/java/com/coverity/security/pie/util/IOUtil.java // public class IOUtil { // public static void closeSilently(Closeable closeable) { // if (closeable != null) { // try { // closeable.close(); // } catch (IOException e) { // // Do nothing // } // } // } // // public static String readFile(File file) throws IOException { // return toString(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8)); // } // public static String readFile(String file) throws IOException { // return toString(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8)); // } // public static String readFile(URL file) throws IOException { // return toString(file.openStream()); // } // // public static String toString(InputStream is) throws IOException { // try { // return toString(new InputStreamReader(is, StandardCharsets.UTF_8)); // } finally { // closeSilently(is); // } // } // public static String toString(Reader reader) throws IOException { // StringBuilder sb = new StringBuilder(); // try { // char buffer[] = new char[4096]; // int n; // while ((n = reader.read(buffer)) > 0) { // sb.append(buffer, 0, n); // } // reader.close(); // } catch (IOException e) { // closeSilently(reader); // throw e; // } // return sb.toString(); // } // // // public static void writeFile(File file, String content) throws IOException { // writeFile(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8), content); // } // private static void writeFile(Writer fw, String content) throws IOException { // try { // fw.write(content); // fw.close(); // } catch (IOException e) { // closeSilently(fw); // throw e; // } // } // // } // Path: pie-csp/src/main/java/com/coverity/security/pie/policy/csp/CspEnforcementFilter.java import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.json.JSONException; import org.json.JSONObject; import com.coverity.security.pie.core.PolicyConfig; import com.coverity.security.pie.util.IOUtil; package com.coverity.security.pie.policy.csp; /** * A servlet filter which adds the CSP directive to the response and which handles violation reports send by the agent. */ public class CspEnforcementFilter implements Filter { public static final String REPORT_URI = "/a379568856ef23aPIE19bc95ce4e2f7fd2b"; private final CspPolicy policy; private final PolicyConfig policyConfig; public CspEnforcementFilter(CspPolicy policy, PolicyConfig policyConfig) { this.policy = policy; this.policyConfig = policyConfig; } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (request == null || response == null || !(request instanceof HttpServletRequest) || !(response instanceof HttpServletResponse)) { chain.doFilter(request, response); return; } HttpServletRequest httpServletRequest = (HttpServletRequest)request; HttpServletResponse httpServletResponse = (HttpServletResponse)response; if (REPORT_URI.equals(httpServletRequest.getRequestURI())) {
JSONObject json = new JSONObject(IOUtil.toString(httpServletRequest.getInputStream()));
coverity/pie
pie-core/src/test/java/com/coverity/security/pie/web/PieAdminFilterTest.java
// Path: pie-core/src/main/java/com/coverity/security/pie/core/PieConfig.java // public class PieConfig { // // private final Properties properties = new Properties(); // // public PieConfig() { // loadProps(this.getClass().getClassLoader().getResource("pieConfig.default.properties")); // File propFile = new File("pieConfig.properties"); // if (propFile.exists()) { // try { // loadProps(propFile.toURI().toURL()); // } catch (MalformedURLException e) { // throw new RuntimeException(e); // } // } else { // loadProps(this.getClass().getClassLoader().getResource("pieConfig.properties")); // } // } // public PieConfig(URL propertiesUrl) { // loadProps(this.getClass().getClassLoader().getResource("pieConfig.default.properties")); // loadProps(propertiesUrl); // } // private void loadProps(URL propertiesUrl) { // if (propertiesUrl != null) { // InputStream is = null; // try { // is = propertiesUrl.openStream(); // if (is != null) { // properties.load(is); // is.close(); // } // } catch (IOException e) { // IOUtil.closeSilently(is); // throw new RuntimeException(e); // } // } // // } // // public Properties getProperties() { // return properties; // } // // private boolean getBoolean(String prop, boolean defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Boolean.parseBoolean(v); // } // // private String getProperty(String name) { // return properties.getProperty("pie." + name); // } // // public boolean isEnabled() { // return getBoolean("enabled", true); // } // // public boolean isRegenerateOnShutdown() { // return getBoolean("regenerateOnShutdown", true); // } // // public boolean isAdminInterfaceEnabled() { // return getBoolean("admininterface.enabled", false); // } // // public boolean isLoggingEnabled() { return getBoolean("loggingEnabled", false); } // // public String getLogPath() { return getProperty("logPath"); } // } // // Path: pie-core/src/test/java/com/coverity/security/pie/core/test/TestPolicyEnforcer.java // public class TestPolicyEnforcer implements PolicyEnforcer { // // private static TestPolicyEnforcer instance = null; // // public static TestPolicyEnforcer getInstance() { // return instance; // } // // private SimplePolicy policy; // private PolicyConfig policyConfig; // private boolean isApplied = false; // // public TestPolicyEnforcer() { // if (instance != null) { // throw new IllegalStateException("Cannot instantiate more than one TestPolicyEnforcer at a time."); // } // instance = this; // } // // @Override // public void init(PieConfig pieConfig) { // this.policy = new SimplePolicy(); // this.policyConfig = new PolicyConfig(policy.getName(), pieConfig); // } // // @Override // public SimplePolicy getPolicy() { // return policy; // } // // @Override // public PolicyConfig getPolicyConfig() { // return policyConfig; // } // // @Override // public void applyPolicy(ServletContext cx) { // isApplied = true; // } // // @Override // public void shutdown() { // instance = null; // } // // public boolean isApplied() { // return isApplied; // } // }
import com.coverity.security.pie.core.PieConfig; import com.coverity.security.pie.core.test.TestPolicyEnforcer; import org.testng.annotations.Test; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import static org.easymock.EasyMock.*; import static org.testng.Assert.assertEquals;
package com.coverity.security.pie.web; public class PieAdminFilterTest { @Test public void testPieAdminFilter() throws IOException, ServletException, InterruptedException {
// Path: pie-core/src/main/java/com/coverity/security/pie/core/PieConfig.java // public class PieConfig { // // private final Properties properties = new Properties(); // // public PieConfig() { // loadProps(this.getClass().getClassLoader().getResource("pieConfig.default.properties")); // File propFile = new File("pieConfig.properties"); // if (propFile.exists()) { // try { // loadProps(propFile.toURI().toURL()); // } catch (MalformedURLException e) { // throw new RuntimeException(e); // } // } else { // loadProps(this.getClass().getClassLoader().getResource("pieConfig.properties")); // } // } // public PieConfig(URL propertiesUrl) { // loadProps(this.getClass().getClassLoader().getResource("pieConfig.default.properties")); // loadProps(propertiesUrl); // } // private void loadProps(URL propertiesUrl) { // if (propertiesUrl != null) { // InputStream is = null; // try { // is = propertiesUrl.openStream(); // if (is != null) { // properties.load(is); // is.close(); // } // } catch (IOException e) { // IOUtil.closeSilently(is); // throw new RuntimeException(e); // } // } // // } // // public Properties getProperties() { // return properties; // } // // private boolean getBoolean(String prop, boolean defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Boolean.parseBoolean(v); // } // // private String getProperty(String name) { // return properties.getProperty("pie." + name); // } // // public boolean isEnabled() { // return getBoolean("enabled", true); // } // // public boolean isRegenerateOnShutdown() { // return getBoolean("regenerateOnShutdown", true); // } // // public boolean isAdminInterfaceEnabled() { // return getBoolean("admininterface.enabled", false); // } // // public boolean isLoggingEnabled() { return getBoolean("loggingEnabled", false); } // // public String getLogPath() { return getProperty("logPath"); } // } // // Path: pie-core/src/test/java/com/coverity/security/pie/core/test/TestPolicyEnforcer.java // public class TestPolicyEnforcer implements PolicyEnforcer { // // private static TestPolicyEnforcer instance = null; // // public static TestPolicyEnforcer getInstance() { // return instance; // } // // private SimplePolicy policy; // private PolicyConfig policyConfig; // private boolean isApplied = false; // // public TestPolicyEnforcer() { // if (instance != null) { // throw new IllegalStateException("Cannot instantiate more than one TestPolicyEnforcer at a time."); // } // instance = this; // } // // @Override // public void init(PieConfig pieConfig) { // this.policy = new SimplePolicy(); // this.policyConfig = new PolicyConfig(policy.getName(), pieConfig); // } // // @Override // public SimplePolicy getPolicy() { // return policy; // } // // @Override // public PolicyConfig getPolicyConfig() { // return policyConfig; // } // // @Override // public void applyPolicy(ServletContext cx) { // isApplied = true; // } // // @Override // public void shutdown() { // instance = null; // } // // public boolean isApplied() { // return isApplied; // } // } // Path: pie-core/src/test/java/com/coverity/security/pie/web/PieAdminFilterTest.java import com.coverity.security.pie.core.PieConfig; import com.coverity.security.pie.core.test.TestPolicyEnforcer; import org.testng.annotations.Test; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import static org.easymock.EasyMock.*; import static org.testng.Assert.assertEquals; package com.coverity.security.pie.web; public class PieAdminFilterTest { @Test public void testPieAdminFilter() throws IOException, ServletException, InterruptedException {
TestPolicyEnforcer testPolicyEnforcer = new TestPolicyEnforcer();
coverity/pie
pie-core/src/test/java/com/coverity/security/pie/web/PieAdminFilterTest.java
// Path: pie-core/src/main/java/com/coverity/security/pie/core/PieConfig.java // public class PieConfig { // // private final Properties properties = new Properties(); // // public PieConfig() { // loadProps(this.getClass().getClassLoader().getResource("pieConfig.default.properties")); // File propFile = new File("pieConfig.properties"); // if (propFile.exists()) { // try { // loadProps(propFile.toURI().toURL()); // } catch (MalformedURLException e) { // throw new RuntimeException(e); // } // } else { // loadProps(this.getClass().getClassLoader().getResource("pieConfig.properties")); // } // } // public PieConfig(URL propertiesUrl) { // loadProps(this.getClass().getClassLoader().getResource("pieConfig.default.properties")); // loadProps(propertiesUrl); // } // private void loadProps(URL propertiesUrl) { // if (propertiesUrl != null) { // InputStream is = null; // try { // is = propertiesUrl.openStream(); // if (is != null) { // properties.load(is); // is.close(); // } // } catch (IOException e) { // IOUtil.closeSilently(is); // throw new RuntimeException(e); // } // } // // } // // public Properties getProperties() { // return properties; // } // // private boolean getBoolean(String prop, boolean defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Boolean.parseBoolean(v); // } // // private String getProperty(String name) { // return properties.getProperty("pie." + name); // } // // public boolean isEnabled() { // return getBoolean("enabled", true); // } // // public boolean isRegenerateOnShutdown() { // return getBoolean("regenerateOnShutdown", true); // } // // public boolean isAdminInterfaceEnabled() { // return getBoolean("admininterface.enabled", false); // } // // public boolean isLoggingEnabled() { return getBoolean("loggingEnabled", false); } // // public String getLogPath() { return getProperty("logPath"); } // } // // Path: pie-core/src/test/java/com/coverity/security/pie/core/test/TestPolicyEnforcer.java // public class TestPolicyEnforcer implements PolicyEnforcer { // // private static TestPolicyEnforcer instance = null; // // public static TestPolicyEnforcer getInstance() { // return instance; // } // // private SimplePolicy policy; // private PolicyConfig policyConfig; // private boolean isApplied = false; // // public TestPolicyEnforcer() { // if (instance != null) { // throw new IllegalStateException("Cannot instantiate more than one TestPolicyEnforcer at a time."); // } // instance = this; // } // // @Override // public void init(PieConfig pieConfig) { // this.policy = new SimplePolicy(); // this.policyConfig = new PolicyConfig(policy.getName(), pieConfig); // } // // @Override // public SimplePolicy getPolicy() { // return policy; // } // // @Override // public PolicyConfig getPolicyConfig() { // return policyConfig; // } // // @Override // public void applyPolicy(ServletContext cx) { // isApplied = true; // } // // @Override // public void shutdown() { // instance = null; // } // // public boolean isApplied() { // return isApplied; // } // }
import com.coverity.security.pie.core.PieConfig; import com.coverity.security.pie.core.test.TestPolicyEnforcer; import org.testng.annotations.Test; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import static org.easymock.EasyMock.*; import static org.testng.Assert.assertEquals;
package com.coverity.security.pie.web; public class PieAdminFilterTest { @Test public void testPieAdminFilter() throws IOException, ServletException, InterruptedException { TestPolicyEnforcer testPolicyEnforcer = new TestPolicyEnforcer(); try {
// Path: pie-core/src/main/java/com/coverity/security/pie/core/PieConfig.java // public class PieConfig { // // private final Properties properties = new Properties(); // // public PieConfig() { // loadProps(this.getClass().getClassLoader().getResource("pieConfig.default.properties")); // File propFile = new File("pieConfig.properties"); // if (propFile.exists()) { // try { // loadProps(propFile.toURI().toURL()); // } catch (MalformedURLException e) { // throw new RuntimeException(e); // } // } else { // loadProps(this.getClass().getClassLoader().getResource("pieConfig.properties")); // } // } // public PieConfig(URL propertiesUrl) { // loadProps(this.getClass().getClassLoader().getResource("pieConfig.default.properties")); // loadProps(propertiesUrl); // } // private void loadProps(URL propertiesUrl) { // if (propertiesUrl != null) { // InputStream is = null; // try { // is = propertiesUrl.openStream(); // if (is != null) { // properties.load(is); // is.close(); // } // } catch (IOException e) { // IOUtil.closeSilently(is); // throw new RuntimeException(e); // } // } // // } // // public Properties getProperties() { // return properties; // } // // private boolean getBoolean(String prop, boolean defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Boolean.parseBoolean(v); // } // // private String getProperty(String name) { // return properties.getProperty("pie." + name); // } // // public boolean isEnabled() { // return getBoolean("enabled", true); // } // // public boolean isRegenerateOnShutdown() { // return getBoolean("regenerateOnShutdown", true); // } // // public boolean isAdminInterfaceEnabled() { // return getBoolean("admininterface.enabled", false); // } // // public boolean isLoggingEnabled() { return getBoolean("loggingEnabled", false); } // // public String getLogPath() { return getProperty("logPath"); } // } // // Path: pie-core/src/test/java/com/coverity/security/pie/core/test/TestPolicyEnforcer.java // public class TestPolicyEnforcer implements PolicyEnforcer { // // private static TestPolicyEnforcer instance = null; // // public static TestPolicyEnforcer getInstance() { // return instance; // } // // private SimplePolicy policy; // private PolicyConfig policyConfig; // private boolean isApplied = false; // // public TestPolicyEnforcer() { // if (instance != null) { // throw new IllegalStateException("Cannot instantiate more than one TestPolicyEnforcer at a time."); // } // instance = this; // } // // @Override // public void init(PieConfig pieConfig) { // this.policy = new SimplePolicy(); // this.policyConfig = new PolicyConfig(policy.getName(), pieConfig); // } // // @Override // public SimplePolicy getPolicy() { // return policy; // } // // @Override // public PolicyConfig getPolicyConfig() { // return policyConfig; // } // // @Override // public void applyPolicy(ServletContext cx) { // isApplied = true; // } // // @Override // public void shutdown() { // instance = null; // } // // public boolean isApplied() { // return isApplied; // } // } // Path: pie-core/src/test/java/com/coverity/security/pie/web/PieAdminFilterTest.java import com.coverity.security.pie.core.PieConfig; import com.coverity.security.pie.core.test.TestPolicyEnforcer; import org.testng.annotations.Test; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import static org.easymock.EasyMock.*; import static org.testng.Assert.assertEquals; package com.coverity.security.pie.web; public class PieAdminFilterTest { @Test public void testPieAdminFilter() throws IOException, ServletException, InterruptedException { TestPolicyEnforcer testPolicyEnforcer = new TestPolicyEnforcer(); try {
testPolicyEnforcer.init(new PieConfig());
coverity/pie
pie-sm/src/main/java/com/coverity/security/pie/policy/securitymanager/fact/JmxMBeanObjectNameFactMetaData.java
// Path: pie-core/src/main/java/com/coverity/security/pie/core/FactMetaData.java // public interface FactMetaData { // /** // * Returns a StringCollapser appropriate for this fact's semantics. The behavior of the StringCollapser may behave // * according to particulars of the policyConfig argument. // * // * @param policyConfig The policy's configuration, which may have directives relevant to this type of fact. // * @return The StringCollapser instance appropriate for this fact. // */ // public StringCollapser getCollapser(PolicyConfig policyConfig); // // /** // * This decides if a concrete instance of a fact matches a fact definition from the security policy. // * @param matcher The security policy's fact. // * @param matchee The concrete instance of a fact. // * @return Whether or not the security policy's fact applies to the instance of a fact. // */ // public boolean matches(String matcher, String matchee); // // /** // * Gets the metadata object associated with the child fact. The particular semantics of the child may depend on the // * concrete instance of the fact being handled. For instance, with the Java SecurityManager, the semantics of child // * facts of a java.io.FilePermission (which represent file paths) are distinct from the child facts of a // * java.net.SocketPermission (which represent hosts). // * @param fact The concrete value of the fact for which child metadata is desired. // * @return The child metadata. // */ // public FactMetaData getChildFactMetaData(String fact); // } // // Path: pie-core/src/main/java/com/coverity/security/pie/core/NullStringCollapser.java // public class NullStringCollapser implements StringCollapser { // // private static final NullStringCollapser instance = new NullStringCollapser(); // // private NullStringCollapser() { // } // // public static NullStringCollapser getInstance() { // return instance; // } // // @Override // public <T> Map<String, Collection<T>> collapse(Map<String, Collection<T>> input) { // return input; // } // // } // // Path: pie-core/src/main/java/com/coverity/security/pie/core/PolicyConfig.java // public class PolicyConfig { // private final String name; // private final PieConfig pieConfig; // // public PolicyConfig(String name, PieConfig pieConfig) { // this.name = name; // this.pieConfig = pieConfig; // } // // public boolean isEnabled() { // return getBoolean("isEnabled", true); // } // // public boolean isReportOnlyMode() { // return getBoolean("isReportOnlyMode", true); // } // // public boolean isCollapseEnabled() { // return getBoolean("isCollapseEnabled", true); // } // // public URL getPolicyFile() { // String policyFile = getProperty("policyFile"); // if (policyFile != null) { // try { // return new URL(policyFile); // } catch (MalformedURLException e) { // throw new IllegalStateException("Invalid policy URL: " + policyFile); // } // } // URL resource = this.getClass().getClassLoader().getResource(name + ".policy"); // if (resource != null) { // return resource; // } // String catalinaHome = System.getProperty("catalina.home"); // if (catalinaHome != null) { // try { // return new File(catalinaHome + File.separatorChar + "conf" + File.separatorChar + name + ".policy").toURI().toURL(); // } catch (MalformedURLException e) { // throw new IllegalStateException("Could not build default policy file path."); // } // } // // // Default to file in the CWD // try { // return new File(name + ".policy").toURI().toURL(); // } catch (MalformedURLException e) { // throw new RuntimeException(e); // } // } // // public boolean getBoolean(String prop, boolean defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Boolean.parseBoolean(v); // } // public int getInteger(String prop, int defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Integer.parseInt(v); // } // // // public String getProperty(String name) { // return pieConfig.getProperties().getProperty(this.name + "." + name); // } // } // // Path: pie-core/src/main/java/com/coverity/security/pie/core/StringCollapser.java // public interface StringCollapser { // /** // * Collapses a security policy according to the concrete implementation's rules. It takes a map from facts to their // * children, and returns a collapsed version of that map. For example, given the map: // * { // * A => {'X', 'Y'}, // * B => {'Z'} // * } // * // * If the implementation determines that the facts A and B should be collapsed to fact C, then this would return // * { // * C => {'X', 'Y', 'Z'} // * } // * // * @param input A map from facts to a collection of child facts. // * @param <T> The type of the child facts; irrelevant to the internal procedure of collapsing. // * @return The collapsed map of facts to their children. // */ // public <T> Map<String, Collection<T>> collapse(Map<String, Collection<T>> input); // }
import javax.management.MalformedObjectNameException; import javax.management.ObjectName; import com.coverity.security.pie.core.FactMetaData; import com.coverity.security.pie.core.NullStringCollapser; import com.coverity.security.pie.core.PolicyConfig; import com.coverity.security.pie.core.StringCollapser;
package com.coverity.security.pie.policy.securitymanager.fact; public class JmxMBeanObjectNameFactMetaData implements FactMetaData { private static final JmxMBeanObjectNameFactMetaData instance = new JmxMBeanObjectNameFactMetaData(); private JmxMBeanObjectNameFactMetaData() { } public static JmxMBeanObjectNameFactMetaData getInstance() { return instance; } @Override
// Path: pie-core/src/main/java/com/coverity/security/pie/core/FactMetaData.java // public interface FactMetaData { // /** // * Returns a StringCollapser appropriate for this fact's semantics. The behavior of the StringCollapser may behave // * according to particulars of the policyConfig argument. // * // * @param policyConfig The policy's configuration, which may have directives relevant to this type of fact. // * @return The StringCollapser instance appropriate for this fact. // */ // public StringCollapser getCollapser(PolicyConfig policyConfig); // // /** // * This decides if a concrete instance of a fact matches a fact definition from the security policy. // * @param matcher The security policy's fact. // * @param matchee The concrete instance of a fact. // * @return Whether or not the security policy's fact applies to the instance of a fact. // */ // public boolean matches(String matcher, String matchee); // // /** // * Gets the metadata object associated with the child fact. The particular semantics of the child may depend on the // * concrete instance of the fact being handled. For instance, with the Java SecurityManager, the semantics of child // * facts of a java.io.FilePermission (which represent file paths) are distinct from the child facts of a // * java.net.SocketPermission (which represent hosts). // * @param fact The concrete value of the fact for which child metadata is desired. // * @return The child metadata. // */ // public FactMetaData getChildFactMetaData(String fact); // } // // Path: pie-core/src/main/java/com/coverity/security/pie/core/NullStringCollapser.java // public class NullStringCollapser implements StringCollapser { // // private static final NullStringCollapser instance = new NullStringCollapser(); // // private NullStringCollapser() { // } // // public static NullStringCollapser getInstance() { // return instance; // } // // @Override // public <T> Map<String, Collection<T>> collapse(Map<String, Collection<T>> input) { // return input; // } // // } // // Path: pie-core/src/main/java/com/coverity/security/pie/core/PolicyConfig.java // public class PolicyConfig { // private final String name; // private final PieConfig pieConfig; // // public PolicyConfig(String name, PieConfig pieConfig) { // this.name = name; // this.pieConfig = pieConfig; // } // // public boolean isEnabled() { // return getBoolean("isEnabled", true); // } // // public boolean isReportOnlyMode() { // return getBoolean("isReportOnlyMode", true); // } // // public boolean isCollapseEnabled() { // return getBoolean("isCollapseEnabled", true); // } // // public URL getPolicyFile() { // String policyFile = getProperty("policyFile"); // if (policyFile != null) { // try { // return new URL(policyFile); // } catch (MalformedURLException e) { // throw new IllegalStateException("Invalid policy URL: " + policyFile); // } // } // URL resource = this.getClass().getClassLoader().getResource(name + ".policy"); // if (resource != null) { // return resource; // } // String catalinaHome = System.getProperty("catalina.home"); // if (catalinaHome != null) { // try { // return new File(catalinaHome + File.separatorChar + "conf" + File.separatorChar + name + ".policy").toURI().toURL(); // } catch (MalformedURLException e) { // throw new IllegalStateException("Could not build default policy file path."); // } // } // // // Default to file in the CWD // try { // return new File(name + ".policy").toURI().toURL(); // } catch (MalformedURLException e) { // throw new RuntimeException(e); // } // } // // public boolean getBoolean(String prop, boolean defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Boolean.parseBoolean(v); // } // public int getInteger(String prop, int defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Integer.parseInt(v); // } // // // public String getProperty(String name) { // return pieConfig.getProperties().getProperty(this.name + "." + name); // } // } // // Path: pie-core/src/main/java/com/coverity/security/pie/core/StringCollapser.java // public interface StringCollapser { // /** // * Collapses a security policy according to the concrete implementation's rules. It takes a map from facts to their // * children, and returns a collapsed version of that map. For example, given the map: // * { // * A => {'X', 'Y'}, // * B => {'Z'} // * } // * // * If the implementation determines that the facts A and B should be collapsed to fact C, then this would return // * { // * C => {'X', 'Y', 'Z'} // * } // * // * @param input A map from facts to a collection of child facts. // * @param <T> The type of the child facts; irrelevant to the internal procedure of collapsing. // * @return The collapsed map of facts to their children. // */ // public <T> Map<String, Collection<T>> collapse(Map<String, Collection<T>> input); // } // Path: pie-sm/src/main/java/com/coverity/security/pie/policy/securitymanager/fact/JmxMBeanObjectNameFactMetaData.java import javax.management.MalformedObjectNameException; import javax.management.ObjectName; import com.coverity.security.pie.core.FactMetaData; import com.coverity.security.pie.core.NullStringCollapser; import com.coverity.security.pie.core.PolicyConfig; import com.coverity.security.pie.core.StringCollapser; package com.coverity.security.pie.policy.securitymanager.fact; public class JmxMBeanObjectNameFactMetaData implements FactMetaData { private static final JmxMBeanObjectNameFactMetaData instance = new JmxMBeanObjectNameFactMetaData(); private JmxMBeanObjectNameFactMetaData() { } public static JmxMBeanObjectNameFactMetaData getInstance() { return instance; } @Override
public StringCollapser getCollapser(PolicyConfig policyConfig) {
coverity/pie
pie-sm/src/main/java/com/coverity/security/pie/policy/securitymanager/fact/JmxMBeanObjectNameFactMetaData.java
// Path: pie-core/src/main/java/com/coverity/security/pie/core/FactMetaData.java // public interface FactMetaData { // /** // * Returns a StringCollapser appropriate for this fact's semantics. The behavior of the StringCollapser may behave // * according to particulars of the policyConfig argument. // * // * @param policyConfig The policy's configuration, which may have directives relevant to this type of fact. // * @return The StringCollapser instance appropriate for this fact. // */ // public StringCollapser getCollapser(PolicyConfig policyConfig); // // /** // * This decides if a concrete instance of a fact matches a fact definition from the security policy. // * @param matcher The security policy's fact. // * @param matchee The concrete instance of a fact. // * @return Whether or not the security policy's fact applies to the instance of a fact. // */ // public boolean matches(String matcher, String matchee); // // /** // * Gets the metadata object associated with the child fact. The particular semantics of the child may depend on the // * concrete instance of the fact being handled. For instance, with the Java SecurityManager, the semantics of child // * facts of a java.io.FilePermission (which represent file paths) are distinct from the child facts of a // * java.net.SocketPermission (which represent hosts). // * @param fact The concrete value of the fact for which child metadata is desired. // * @return The child metadata. // */ // public FactMetaData getChildFactMetaData(String fact); // } // // Path: pie-core/src/main/java/com/coverity/security/pie/core/NullStringCollapser.java // public class NullStringCollapser implements StringCollapser { // // private static final NullStringCollapser instance = new NullStringCollapser(); // // private NullStringCollapser() { // } // // public static NullStringCollapser getInstance() { // return instance; // } // // @Override // public <T> Map<String, Collection<T>> collapse(Map<String, Collection<T>> input) { // return input; // } // // } // // Path: pie-core/src/main/java/com/coverity/security/pie/core/PolicyConfig.java // public class PolicyConfig { // private final String name; // private final PieConfig pieConfig; // // public PolicyConfig(String name, PieConfig pieConfig) { // this.name = name; // this.pieConfig = pieConfig; // } // // public boolean isEnabled() { // return getBoolean("isEnabled", true); // } // // public boolean isReportOnlyMode() { // return getBoolean("isReportOnlyMode", true); // } // // public boolean isCollapseEnabled() { // return getBoolean("isCollapseEnabled", true); // } // // public URL getPolicyFile() { // String policyFile = getProperty("policyFile"); // if (policyFile != null) { // try { // return new URL(policyFile); // } catch (MalformedURLException e) { // throw new IllegalStateException("Invalid policy URL: " + policyFile); // } // } // URL resource = this.getClass().getClassLoader().getResource(name + ".policy"); // if (resource != null) { // return resource; // } // String catalinaHome = System.getProperty("catalina.home"); // if (catalinaHome != null) { // try { // return new File(catalinaHome + File.separatorChar + "conf" + File.separatorChar + name + ".policy").toURI().toURL(); // } catch (MalformedURLException e) { // throw new IllegalStateException("Could not build default policy file path."); // } // } // // // Default to file in the CWD // try { // return new File(name + ".policy").toURI().toURL(); // } catch (MalformedURLException e) { // throw new RuntimeException(e); // } // } // // public boolean getBoolean(String prop, boolean defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Boolean.parseBoolean(v); // } // public int getInteger(String prop, int defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Integer.parseInt(v); // } // // // public String getProperty(String name) { // return pieConfig.getProperties().getProperty(this.name + "." + name); // } // } // // Path: pie-core/src/main/java/com/coverity/security/pie/core/StringCollapser.java // public interface StringCollapser { // /** // * Collapses a security policy according to the concrete implementation's rules. It takes a map from facts to their // * children, and returns a collapsed version of that map. For example, given the map: // * { // * A => {'X', 'Y'}, // * B => {'Z'} // * } // * // * If the implementation determines that the facts A and B should be collapsed to fact C, then this would return // * { // * C => {'X', 'Y', 'Z'} // * } // * // * @param input A map from facts to a collection of child facts. // * @param <T> The type of the child facts; irrelevant to the internal procedure of collapsing. // * @return The collapsed map of facts to their children. // */ // public <T> Map<String, Collection<T>> collapse(Map<String, Collection<T>> input); // }
import javax.management.MalformedObjectNameException; import javax.management.ObjectName; import com.coverity.security.pie.core.FactMetaData; import com.coverity.security.pie.core.NullStringCollapser; import com.coverity.security.pie.core.PolicyConfig; import com.coverity.security.pie.core.StringCollapser;
package com.coverity.security.pie.policy.securitymanager.fact; public class JmxMBeanObjectNameFactMetaData implements FactMetaData { private static final JmxMBeanObjectNameFactMetaData instance = new JmxMBeanObjectNameFactMetaData(); private JmxMBeanObjectNameFactMetaData() { } public static JmxMBeanObjectNameFactMetaData getInstance() { return instance; } @Override
// Path: pie-core/src/main/java/com/coverity/security/pie/core/FactMetaData.java // public interface FactMetaData { // /** // * Returns a StringCollapser appropriate for this fact's semantics. The behavior of the StringCollapser may behave // * according to particulars of the policyConfig argument. // * // * @param policyConfig The policy's configuration, which may have directives relevant to this type of fact. // * @return The StringCollapser instance appropriate for this fact. // */ // public StringCollapser getCollapser(PolicyConfig policyConfig); // // /** // * This decides if a concrete instance of a fact matches a fact definition from the security policy. // * @param matcher The security policy's fact. // * @param matchee The concrete instance of a fact. // * @return Whether or not the security policy's fact applies to the instance of a fact. // */ // public boolean matches(String matcher, String matchee); // // /** // * Gets the metadata object associated with the child fact. The particular semantics of the child may depend on the // * concrete instance of the fact being handled. For instance, with the Java SecurityManager, the semantics of child // * facts of a java.io.FilePermission (which represent file paths) are distinct from the child facts of a // * java.net.SocketPermission (which represent hosts). // * @param fact The concrete value of the fact for which child metadata is desired. // * @return The child metadata. // */ // public FactMetaData getChildFactMetaData(String fact); // } // // Path: pie-core/src/main/java/com/coverity/security/pie/core/NullStringCollapser.java // public class NullStringCollapser implements StringCollapser { // // private static final NullStringCollapser instance = new NullStringCollapser(); // // private NullStringCollapser() { // } // // public static NullStringCollapser getInstance() { // return instance; // } // // @Override // public <T> Map<String, Collection<T>> collapse(Map<String, Collection<T>> input) { // return input; // } // // } // // Path: pie-core/src/main/java/com/coverity/security/pie/core/PolicyConfig.java // public class PolicyConfig { // private final String name; // private final PieConfig pieConfig; // // public PolicyConfig(String name, PieConfig pieConfig) { // this.name = name; // this.pieConfig = pieConfig; // } // // public boolean isEnabled() { // return getBoolean("isEnabled", true); // } // // public boolean isReportOnlyMode() { // return getBoolean("isReportOnlyMode", true); // } // // public boolean isCollapseEnabled() { // return getBoolean("isCollapseEnabled", true); // } // // public URL getPolicyFile() { // String policyFile = getProperty("policyFile"); // if (policyFile != null) { // try { // return new URL(policyFile); // } catch (MalformedURLException e) { // throw new IllegalStateException("Invalid policy URL: " + policyFile); // } // } // URL resource = this.getClass().getClassLoader().getResource(name + ".policy"); // if (resource != null) { // return resource; // } // String catalinaHome = System.getProperty("catalina.home"); // if (catalinaHome != null) { // try { // return new File(catalinaHome + File.separatorChar + "conf" + File.separatorChar + name + ".policy").toURI().toURL(); // } catch (MalformedURLException e) { // throw new IllegalStateException("Could not build default policy file path."); // } // } // // // Default to file in the CWD // try { // return new File(name + ".policy").toURI().toURL(); // } catch (MalformedURLException e) { // throw new RuntimeException(e); // } // } // // public boolean getBoolean(String prop, boolean defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Boolean.parseBoolean(v); // } // public int getInteger(String prop, int defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Integer.parseInt(v); // } // // // public String getProperty(String name) { // return pieConfig.getProperties().getProperty(this.name + "." + name); // } // } // // Path: pie-core/src/main/java/com/coverity/security/pie/core/StringCollapser.java // public interface StringCollapser { // /** // * Collapses a security policy according to the concrete implementation's rules. It takes a map from facts to their // * children, and returns a collapsed version of that map. For example, given the map: // * { // * A => {'X', 'Y'}, // * B => {'Z'} // * } // * // * If the implementation determines that the facts A and B should be collapsed to fact C, then this would return // * { // * C => {'X', 'Y', 'Z'} // * } // * // * @param input A map from facts to a collection of child facts. // * @param <T> The type of the child facts; irrelevant to the internal procedure of collapsing. // * @return The collapsed map of facts to their children. // */ // public <T> Map<String, Collection<T>> collapse(Map<String, Collection<T>> input); // } // Path: pie-sm/src/main/java/com/coverity/security/pie/policy/securitymanager/fact/JmxMBeanObjectNameFactMetaData.java import javax.management.MalformedObjectNameException; import javax.management.ObjectName; import com.coverity.security.pie.core.FactMetaData; import com.coverity.security.pie.core.NullStringCollapser; import com.coverity.security.pie.core.PolicyConfig; import com.coverity.security.pie.core.StringCollapser; package com.coverity.security.pie.policy.securitymanager.fact; public class JmxMBeanObjectNameFactMetaData implements FactMetaData { private static final JmxMBeanObjectNameFactMetaData instance = new JmxMBeanObjectNameFactMetaData(); private JmxMBeanObjectNameFactMetaData() { } public static JmxMBeanObjectNameFactMetaData getInstance() { return instance; } @Override
public StringCollapser getCollapser(PolicyConfig policyConfig) {
coverity/pie
pie-sm/src/main/java/com/coverity/security/pie/policy/securitymanager/fact/JmxMBeanObjectNameFactMetaData.java
// Path: pie-core/src/main/java/com/coverity/security/pie/core/FactMetaData.java // public interface FactMetaData { // /** // * Returns a StringCollapser appropriate for this fact's semantics. The behavior of the StringCollapser may behave // * according to particulars of the policyConfig argument. // * // * @param policyConfig The policy's configuration, which may have directives relevant to this type of fact. // * @return The StringCollapser instance appropriate for this fact. // */ // public StringCollapser getCollapser(PolicyConfig policyConfig); // // /** // * This decides if a concrete instance of a fact matches a fact definition from the security policy. // * @param matcher The security policy's fact. // * @param matchee The concrete instance of a fact. // * @return Whether or not the security policy's fact applies to the instance of a fact. // */ // public boolean matches(String matcher, String matchee); // // /** // * Gets the metadata object associated with the child fact. The particular semantics of the child may depend on the // * concrete instance of the fact being handled. For instance, with the Java SecurityManager, the semantics of child // * facts of a java.io.FilePermission (which represent file paths) are distinct from the child facts of a // * java.net.SocketPermission (which represent hosts). // * @param fact The concrete value of the fact for which child metadata is desired. // * @return The child metadata. // */ // public FactMetaData getChildFactMetaData(String fact); // } // // Path: pie-core/src/main/java/com/coverity/security/pie/core/NullStringCollapser.java // public class NullStringCollapser implements StringCollapser { // // private static final NullStringCollapser instance = new NullStringCollapser(); // // private NullStringCollapser() { // } // // public static NullStringCollapser getInstance() { // return instance; // } // // @Override // public <T> Map<String, Collection<T>> collapse(Map<String, Collection<T>> input) { // return input; // } // // } // // Path: pie-core/src/main/java/com/coverity/security/pie/core/PolicyConfig.java // public class PolicyConfig { // private final String name; // private final PieConfig pieConfig; // // public PolicyConfig(String name, PieConfig pieConfig) { // this.name = name; // this.pieConfig = pieConfig; // } // // public boolean isEnabled() { // return getBoolean("isEnabled", true); // } // // public boolean isReportOnlyMode() { // return getBoolean("isReportOnlyMode", true); // } // // public boolean isCollapseEnabled() { // return getBoolean("isCollapseEnabled", true); // } // // public URL getPolicyFile() { // String policyFile = getProperty("policyFile"); // if (policyFile != null) { // try { // return new URL(policyFile); // } catch (MalformedURLException e) { // throw new IllegalStateException("Invalid policy URL: " + policyFile); // } // } // URL resource = this.getClass().getClassLoader().getResource(name + ".policy"); // if (resource != null) { // return resource; // } // String catalinaHome = System.getProperty("catalina.home"); // if (catalinaHome != null) { // try { // return new File(catalinaHome + File.separatorChar + "conf" + File.separatorChar + name + ".policy").toURI().toURL(); // } catch (MalformedURLException e) { // throw new IllegalStateException("Could not build default policy file path."); // } // } // // // Default to file in the CWD // try { // return new File(name + ".policy").toURI().toURL(); // } catch (MalformedURLException e) { // throw new RuntimeException(e); // } // } // // public boolean getBoolean(String prop, boolean defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Boolean.parseBoolean(v); // } // public int getInteger(String prop, int defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Integer.parseInt(v); // } // // // public String getProperty(String name) { // return pieConfig.getProperties().getProperty(this.name + "." + name); // } // } // // Path: pie-core/src/main/java/com/coverity/security/pie/core/StringCollapser.java // public interface StringCollapser { // /** // * Collapses a security policy according to the concrete implementation's rules. It takes a map from facts to their // * children, and returns a collapsed version of that map. For example, given the map: // * { // * A => {'X', 'Y'}, // * B => {'Z'} // * } // * // * If the implementation determines that the facts A and B should be collapsed to fact C, then this would return // * { // * C => {'X', 'Y', 'Z'} // * } // * // * @param input A map from facts to a collection of child facts. // * @param <T> The type of the child facts; irrelevant to the internal procedure of collapsing. // * @return The collapsed map of facts to their children. // */ // public <T> Map<String, Collection<T>> collapse(Map<String, Collection<T>> input); // }
import javax.management.MalformedObjectNameException; import javax.management.ObjectName; import com.coverity.security.pie.core.FactMetaData; import com.coverity.security.pie.core.NullStringCollapser; import com.coverity.security.pie.core.PolicyConfig; import com.coverity.security.pie.core.StringCollapser;
package com.coverity.security.pie.policy.securitymanager.fact; public class JmxMBeanObjectNameFactMetaData implements FactMetaData { private static final JmxMBeanObjectNameFactMetaData instance = new JmxMBeanObjectNameFactMetaData(); private JmxMBeanObjectNameFactMetaData() { } public static JmxMBeanObjectNameFactMetaData getInstance() { return instance; } @Override public StringCollapser getCollapser(PolicyConfig policyConfig) { // FIXME: ObjectName spec is quite general, so deciding how to collapse is non-trivial
// Path: pie-core/src/main/java/com/coverity/security/pie/core/FactMetaData.java // public interface FactMetaData { // /** // * Returns a StringCollapser appropriate for this fact's semantics. The behavior of the StringCollapser may behave // * according to particulars of the policyConfig argument. // * // * @param policyConfig The policy's configuration, which may have directives relevant to this type of fact. // * @return The StringCollapser instance appropriate for this fact. // */ // public StringCollapser getCollapser(PolicyConfig policyConfig); // // /** // * This decides if a concrete instance of a fact matches a fact definition from the security policy. // * @param matcher The security policy's fact. // * @param matchee The concrete instance of a fact. // * @return Whether or not the security policy's fact applies to the instance of a fact. // */ // public boolean matches(String matcher, String matchee); // // /** // * Gets the metadata object associated with the child fact. The particular semantics of the child may depend on the // * concrete instance of the fact being handled. For instance, with the Java SecurityManager, the semantics of child // * facts of a java.io.FilePermission (which represent file paths) are distinct from the child facts of a // * java.net.SocketPermission (which represent hosts). // * @param fact The concrete value of the fact for which child metadata is desired. // * @return The child metadata. // */ // public FactMetaData getChildFactMetaData(String fact); // } // // Path: pie-core/src/main/java/com/coverity/security/pie/core/NullStringCollapser.java // public class NullStringCollapser implements StringCollapser { // // private static final NullStringCollapser instance = new NullStringCollapser(); // // private NullStringCollapser() { // } // // public static NullStringCollapser getInstance() { // return instance; // } // // @Override // public <T> Map<String, Collection<T>> collapse(Map<String, Collection<T>> input) { // return input; // } // // } // // Path: pie-core/src/main/java/com/coverity/security/pie/core/PolicyConfig.java // public class PolicyConfig { // private final String name; // private final PieConfig pieConfig; // // public PolicyConfig(String name, PieConfig pieConfig) { // this.name = name; // this.pieConfig = pieConfig; // } // // public boolean isEnabled() { // return getBoolean("isEnabled", true); // } // // public boolean isReportOnlyMode() { // return getBoolean("isReportOnlyMode", true); // } // // public boolean isCollapseEnabled() { // return getBoolean("isCollapseEnabled", true); // } // // public URL getPolicyFile() { // String policyFile = getProperty("policyFile"); // if (policyFile != null) { // try { // return new URL(policyFile); // } catch (MalformedURLException e) { // throw new IllegalStateException("Invalid policy URL: " + policyFile); // } // } // URL resource = this.getClass().getClassLoader().getResource(name + ".policy"); // if (resource != null) { // return resource; // } // String catalinaHome = System.getProperty("catalina.home"); // if (catalinaHome != null) { // try { // return new File(catalinaHome + File.separatorChar + "conf" + File.separatorChar + name + ".policy").toURI().toURL(); // } catch (MalformedURLException e) { // throw new IllegalStateException("Could not build default policy file path."); // } // } // // // Default to file in the CWD // try { // return new File(name + ".policy").toURI().toURL(); // } catch (MalformedURLException e) { // throw new RuntimeException(e); // } // } // // public boolean getBoolean(String prop, boolean defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Boolean.parseBoolean(v); // } // public int getInteger(String prop, int defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Integer.parseInt(v); // } // // // public String getProperty(String name) { // return pieConfig.getProperties().getProperty(this.name + "." + name); // } // } // // Path: pie-core/src/main/java/com/coverity/security/pie/core/StringCollapser.java // public interface StringCollapser { // /** // * Collapses a security policy according to the concrete implementation's rules. It takes a map from facts to their // * children, and returns a collapsed version of that map. For example, given the map: // * { // * A => {'X', 'Y'}, // * B => {'Z'} // * } // * // * If the implementation determines that the facts A and B should be collapsed to fact C, then this would return // * { // * C => {'X', 'Y', 'Z'} // * } // * // * @param input A map from facts to a collection of child facts. // * @param <T> The type of the child facts; irrelevant to the internal procedure of collapsing. // * @return The collapsed map of facts to their children. // */ // public <T> Map<String, Collection<T>> collapse(Map<String, Collection<T>> input); // } // Path: pie-sm/src/main/java/com/coverity/security/pie/policy/securitymanager/fact/JmxMBeanObjectNameFactMetaData.java import javax.management.MalformedObjectNameException; import javax.management.ObjectName; import com.coverity.security.pie.core.FactMetaData; import com.coverity.security.pie.core.NullStringCollapser; import com.coverity.security.pie.core.PolicyConfig; import com.coverity.security.pie.core.StringCollapser; package com.coverity.security.pie.policy.securitymanager.fact; public class JmxMBeanObjectNameFactMetaData implements FactMetaData { private static final JmxMBeanObjectNameFactMetaData instance = new JmxMBeanObjectNameFactMetaData(); private JmxMBeanObjectNameFactMetaData() { } public static JmxMBeanObjectNameFactMetaData getInstance() { return instance; } @Override public StringCollapser getCollapser(PolicyConfig policyConfig) { // FIXME: ObjectName spec is quite general, so deciding how to collapse is non-trivial
return NullStringCollapser.getInstance();
coverity/pie
pie-core/src/main/java/com/coverity/security/pie/util/collapser/UriCspDirectiveCollapser.java
// Path: pie-core/src/main/java/com/coverity/security/pie/core/StringCollapser.java // public interface StringCollapser { // /** // * Collapses a security policy according to the concrete implementation's rules. It takes a map from facts to their // * children, and returns a collapsed version of that map. For example, given the map: // * { // * A => {'X', 'Y'}, // * B => {'Z'} // * } // * // * If the implementation determines that the facts A and B should be collapsed to fact C, then this would return // * { // * C => {'X', 'Y', 'Z'} // * } // * // * @param input A map from facts to a collection of child facts. // * @param <T> The type of the child facts; irrelevant to the internal procedure of collapsing. // * @return The collapsed map of facts to their children. // */ // public <T> Map<String, Collection<T>> collapse(Map<String, Collection<T>> input); // } // // Path: pie-core/src/main/java/com/coverity/security/pie/util/StringUtil.java // public class StringUtil { // public static String join(String s, String[] arr, int off, int end) { // if (off < 0 || end > arr.length) { // throw new IllegalArgumentException("Invalid indices"); // } // if (end <= off) { // return ""; // } // // StringBuilder sb = new StringBuilder(); // for (int i = off; i < end-1; i++) { // sb.append(arr[i]).append(s); // } // sb.append(arr[end-1]); // return sb.toString(); // } // // public static String join(String s, List<String> strings) { // if (strings.size() == 0) { // return ""; // } // StringBuilder sb = new StringBuilder(); // for (int i = 0; i < strings.size()-1; i++) { // sb.append(strings.get(i)).append(s); // } // sb.append(strings.get(strings.size()-1)); // return sb.toString(); // } // // // public static String join(String s, String ... strings) { // if (strings.length == 0) { // return ""; // } // StringBuilder sb = new StringBuilder(); // for (int i = 0; i < strings.length-1; i++) { // sb.append(strings[i]).append(s); // } // sb.append(strings[strings.length-1]); // return sb.toString(); // } // }
import java.util.Collection; import java.util.HashMap; import java.util.Map; import com.coverity.security.pie.core.StringCollapser; import com.coverity.security.pie.util.StringUtil;
package com.coverity.security.pie.util.collapser; /** * An implementation of the AbstractPathCollapser which collapses URLs for CSP policies. */ public class UriCspDirectiveCollapser extends AbstractPathCollapser implements StringCollapser { public UriCspDirectiveCollapser(int collapseThreshold) { super("*", "**", collapseThreshold, 1); } @Override protected boolean pathNameMatches(PathName matcher, PathName matchee) { // Do not collapse URI paths down to the root. if (matcher.getPathComponents().length == 1 && (matcher.getPathComponents()[0].equals("*") || matcher.getPathComponents()[0].equals("**"))) { return false; } return super.pathNameMatches(matcher, matchee); } @Override public <T> Map<String, Collection<T>> collapse(Map<String, Collection<T>> input) { Map<PathName, Collection<T>> inputMap = new HashMap<PathName, Collection<T>>(input.size()); for (Map.Entry<String, Collection<T>> entry : input.entrySet()) { String uri = entry.getKey(); if (!uri.startsWith("/")) { throw new IllegalArgumentException("Expected URI to start with leading slash."); } inputMap.put(new PathName(uri.substring(1).split("/", -1), null), entry.getValue()); } Map<PathName, Collection<T>> outputMap = collapsePaths(inputMap); Map<String, Collection<T>> output = new HashMap<String, Collection<T>>(outputMap.size()); for (Map.Entry<PathName, Collection<T>> pathNameEntry : outputMap.entrySet()) {
// Path: pie-core/src/main/java/com/coverity/security/pie/core/StringCollapser.java // public interface StringCollapser { // /** // * Collapses a security policy according to the concrete implementation's rules. It takes a map from facts to their // * children, and returns a collapsed version of that map. For example, given the map: // * { // * A => {'X', 'Y'}, // * B => {'Z'} // * } // * // * If the implementation determines that the facts A and B should be collapsed to fact C, then this would return // * { // * C => {'X', 'Y', 'Z'} // * } // * // * @param input A map from facts to a collection of child facts. // * @param <T> The type of the child facts; irrelevant to the internal procedure of collapsing. // * @return The collapsed map of facts to their children. // */ // public <T> Map<String, Collection<T>> collapse(Map<String, Collection<T>> input); // } // // Path: pie-core/src/main/java/com/coverity/security/pie/util/StringUtil.java // public class StringUtil { // public static String join(String s, String[] arr, int off, int end) { // if (off < 0 || end > arr.length) { // throw new IllegalArgumentException("Invalid indices"); // } // if (end <= off) { // return ""; // } // // StringBuilder sb = new StringBuilder(); // for (int i = off; i < end-1; i++) { // sb.append(arr[i]).append(s); // } // sb.append(arr[end-1]); // return sb.toString(); // } // // public static String join(String s, List<String> strings) { // if (strings.size() == 0) { // return ""; // } // StringBuilder sb = new StringBuilder(); // for (int i = 0; i < strings.size()-1; i++) { // sb.append(strings.get(i)).append(s); // } // sb.append(strings.get(strings.size()-1)); // return sb.toString(); // } // // // public static String join(String s, String ... strings) { // if (strings.length == 0) { // return ""; // } // StringBuilder sb = new StringBuilder(); // for (int i = 0; i < strings.length-1; i++) { // sb.append(strings[i]).append(s); // } // sb.append(strings[strings.length-1]); // return sb.toString(); // } // } // Path: pie-core/src/main/java/com/coverity/security/pie/util/collapser/UriCspDirectiveCollapser.java import java.util.Collection; import java.util.HashMap; import java.util.Map; import com.coverity.security.pie.core.StringCollapser; import com.coverity.security.pie.util.StringUtil; package com.coverity.security.pie.util.collapser; /** * An implementation of the AbstractPathCollapser which collapses URLs for CSP policies. */ public class UriCspDirectiveCollapser extends AbstractPathCollapser implements StringCollapser { public UriCspDirectiveCollapser(int collapseThreshold) { super("*", "**", collapseThreshold, 1); } @Override protected boolean pathNameMatches(PathName matcher, PathName matchee) { // Do not collapse URI paths down to the root. if (matcher.getPathComponents().length == 1 && (matcher.getPathComponents()[0].equals("*") || matcher.getPathComponents()[0].equals("**"))) { return false; } return super.pathNameMatches(matcher, matchee); } @Override public <T> Map<String, Collection<T>> collapse(Map<String, Collection<T>> input) { Map<PathName, Collection<T>> inputMap = new HashMap<PathName, Collection<T>>(input.size()); for (Map.Entry<String, Collection<T>> entry : input.entrySet()) { String uri = entry.getKey(); if (!uri.startsWith("/")) { throw new IllegalArgumentException("Expected URI to start with leading slash."); } inputMap.put(new PathName(uri.substring(1).split("/", -1), null), entry.getValue()); } Map<PathName, Collection<T>> outputMap = collapsePaths(inputMap); Map<String, Collection<T>> output = new HashMap<String, Collection<T>>(outputMap.size()); for (Map.Entry<PathName, Collection<T>> pathNameEntry : outputMap.entrySet()) {
output.put("/" + StringUtil.join("/", pathNameEntry.getKey().getPathComponents()), pathNameEntry.getValue());
coverity/pie
pie-csp/src/test/java/com/coverity/security/pie/policy/csp/CspPolicyEnforcerTest.java
// Path: pie-core/src/main/java/com/coverity/security/pie/core/PieConfig.java // public class PieConfig { // // private final Properties properties = new Properties(); // // public PieConfig() { // loadProps(this.getClass().getClassLoader().getResource("pieConfig.default.properties")); // File propFile = new File("pieConfig.properties"); // if (propFile.exists()) { // try { // loadProps(propFile.toURI().toURL()); // } catch (MalformedURLException e) { // throw new RuntimeException(e); // } // } else { // loadProps(this.getClass().getClassLoader().getResource("pieConfig.properties")); // } // } // public PieConfig(URL propertiesUrl) { // loadProps(this.getClass().getClassLoader().getResource("pieConfig.default.properties")); // loadProps(propertiesUrl); // } // private void loadProps(URL propertiesUrl) { // if (propertiesUrl != null) { // InputStream is = null; // try { // is = propertiesUrl.openStream(); // if (is != null) { // properties.load(is); // is.close(); // } // } catch (IOException e) { // IOUtil.closeSilently(is); // throw new RuntimeException(e); // } // } // // } // // public Properties getProperties() { // return properties; // } // // private boolean getBoolean(String prop, boolean defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Boolean.parseBoolean(v); // } // // private String getProperty(String name) { // return properties.getProperty("pie." + name); // } // // public boolean isEnabled() { // return getBoolean("enabled", true); // } // // public boolean isRegenerateOnShutdown() { // return getBoolean("regenerateOnShutdown", true); // } // // public boolean isAdminInterfaceEnabled() { // return getBoolean("admininterface.enabled", false); // } // // public boolean isLoggingEnabled() { return getBoolean("loggingEnabled", false); } // // public String getLogPath() { return getProperty("logPath"); } // }
import com.coverity.security.pie.core.PieConfig; import org.testng.annotations.Test; import javax.servlet.FilterRegistration; import javax.servlet.ServletContext; import static org.easymock.EasyMock.*;
package com.coverity.security.pie.policy.csp; public class CspPolicyEnforcerTest { @Test public void testApplyPolicy() { CspPolicyEnforcer cspPolicyEnforcer = new CspPolicyEnforcer();
// Path: pie-core/src/main/java/com/coverity/security/pie/core/PieConfig.java // public class PieConfig { // // private final Properties properties = new Properties(); // // public PieConfig() { // loadProps(this.getClass().getClassLoader().getResource("pieConfig.default.properties")); // File propFile = new File("pieConfig.properties"); // if (propFile.exists()) { // try { // loadProps(propFile.toURI().toURL()); // } catch (MalformedURLException e) { // throw new RuntimeException(e); // } // } else { // loadProps(this.getClass().getClassLoader().getResource("pieConfig.properties")); // } // } // public PieConfig(URL propertiesUrl) { // loadProps(this.getClass().getClassLoader().getResource("pieConfig.default.properties")); // loadProps(propertiesUrl); // } // private void loadProps(URL propertiesUrl) { // if (propertiesUrl != null) { // InputStream is = null; // try { // is = propertiesUrl.openStream(); // if (is != null) { // properties.load(is); // is.close(); // } // } catch (IOException e) { // IOUtil.closeSilently(is); // throw new RuntimeException(e); // } // } // // } // // public Properties getProperties() { // return properties; // } // // private boolean getBoolean(String prop, boolean defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Boolean.parseBoolean(v); // } // // private String getProperty(String name) { // return properties.getProperty("pie." + name); // } // // public boolean isEnabled() { // return getBoolean("enabled", true); // } // // public boolean isRegenerateOnShutdown() { // return getBoolean("regenerateOnShutdown", true); // } // // public boolean isAdminInterfaceEnabled() { // return getBoolean("admininterface.enabled", false); // } // // public boolean isLoggingEnabled() { return getBoolean("loggingEnabled", false); } // // public String getLogPath() { return getProperty("logPath"); } // } // Path: pie-csp/src/test/java/com/coverity/security/pie/policy/csp/CspPolicyEnforcerTest.java import com.coverity.security.pie.core.PieConfig; import org.testng.annotations.Test; import javax.servlet.FilterRegistration; import javax.servlet.ServletContext; import static org.easymock.EasyMock.*; package com.coverity.security.pie.policy.csp; public class CspPolicyEnforcerTest { @Test public void testApplyPolicy() { CspPolicyEnforcer cspPolicyEnforcer = new CspPolicyEnforcer();
cspPolicyEnforcer.init(new PieConfig());
coverity/pie
pie-sm/src/test/java/com/coverity/security/pie/policy/securitymanager/PropertyPermissionsTest.java
// Path: pie-core/src/main/java/com/coverity/security/pie/core/PieConfig.java // public class PieConfig { // // private final Properties properties = new Properties(); // // public PieConfig() { // loadProps(this.getClass().getClassLoader().getResource("pieConfig.default.properties")); // File propFile = new File("pieConfig.properties"); // if (propFile.exists()) { // try { // loadProps(propFile.toURI().toURL()); // } catch (MalformedURLException e) { // throw new RuntimeException(e); // } // } else { // loadProps(this.getClass().getClassLoader().getResource("pieConfig.properties")); // } // } // public PieConfig(URL propertiesUrl) { // loadProps(this.getClass().getClassLoader().getResource("pieConfig.default.properties")); // loadProps(propertiesUrl); // } // private void loadProps(URL propertiesUrl) { // if (propertiesUrl != null) { // InputStream is = null; // try { // is = propertiesUrl.openStream(); // if (is != null) { // properties.load(is); // is.close(); // } // } catch (IOException e) { // IOUtil.closeSilently(is); // throw new RuntimeException(e); // } // } // // } // // public Properties getProperties() { // return properties; // } // // private boolean getBoolean(String prop, boolean defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Boolean.parseBoolean(v); // } // // private String getProperty(String name) { // return properties.getProperty("pie." + name); // } // // public boolean isEnabled() { // return getBoolean("enabled", true); // } // // public boolean isRegenerateOnShutdown() { // return getBoolean("regenerateOnShutdown", true); // } // // public boolean isAdminInterfaceEnabled() { // return getBoolean("admininterface.enabled", false); // } // // public boolean isLoggingEnabled() { return getBoolean("loggingEnabled", false); } // // public String getLogPath() { return getProperty("logPath"); } // } // // Path: pie-core/src/main/java/com/coverity/security/pie/core/PolicyConfig.java // public class PolicyConfig { // private final String name; // private final PieConfig pieConfig; // // public PolicyConfig(String name, PieConfig pieConfig) { // this.name = name; // this.pieConfig = pieConfig; // } // // public boolean isEnabled() { // return getBoolean("isEnabled", true); // } // // public boolean isReportOnlyMode() { // return getBoolean("isReportOnlyMode", true); // } // // public boolean isCollapseEnabled() { // return getBoolean("isCollapseEnabled", true); // } // // public URL getPolicyFile() { // String policyFile = getProperty("policyFile"); // if (policyFile != null) { // try { // return new URL(policyFile); // } catch (MalformedURLException e) { // throw new IllegalStateException("Invalid policy URL: " + policyFile); // } // } // URL resource = this.getClass().getClassLoader().getResource(name + ".policy"); // if (resource != null) { // return resource; // } // String catalinaHome = System.getProperty("catalina.home"); // if (catalinaHome != null) { // try { // return new File(catalinaHome + File.separatorChar + "conf" + File.separatorChar + name + ".policy").toURI().toURL(); // } catch (MalformedURLException e) { // throw new IllegalStateException("Could not build default policy file path."); // } // } // // // Default to file in the CWD // try { // return new File(name + ".policy").toURI().toURL(); // } catch (MalformedURLException e) { // throw new RuntimeException(e); // } // } // // public boolean getBoolean(String prop, boolean defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Boolean.parseBoolean(v); // } // public int getInteger(String prop, int defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Integer.parseInt(v); // } // // // public String getProperty(String name) { // return pieConfig.getProperties().getProperty(this.name + "." + name); // } // }
import com.coverity.security.pie.core.PieConfig; import com.coverity.security.pie.core.PolicyConfig; import org.json.JSONObject; import org.testng.annotations.Test; import java.io.IOException; import java.io.StringWriter; import java.util.PropertyPermission; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue;
package com.coverity.security.pie.policy.securitymanager; public class PropertyPermissionsTest { @Test public void testPropertyPermissions() throws IOException { SecurityManagerPolicy policy = new SecurityManagerPolicy();
// Path: pie-core/src/main/java/com/coverity/security/pie/core/PieConfig.java // public class PieConfig { // // private final Properties properties = new Properties(); // // public PieConfig() { // loadProps(this.getClass().getClassLoader().getResource("pieConfig.default.properties")); // File propFile = new File("pieConfig.properties"); // if (propFile.exists()) { // try { // loadProps(propFile.toURI().toURL()); // } catch (MalformedURLException e) { // throw new RuntimeException(e); // } // } else { // loadProps(this.getClass().getClassLoader().getResource("pieConfig.properties")); // } // } // public PieConfig(URL propertiesUrl) { // loadProps(this.getClass().getClassLoader().getResource("pieConfig.default.properties")); // loadProps(propertiesUrl); // } // private void loadProps(URL propertiesUrl) { // if (propertiesUrl != null) { // InputStream is = null; // try { // is = propertiesUrl.openStream(); // if (is != null) { // properties.load(is); // is.close(); // } // } catch (IOException e) { // IOUtil.closeSilently(is); // throw new RuntimeException(e); // } // } // // } // // public Properties getProperties() { // return properties; // } // // private boolean getBoolean(String prop, boolean defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Boolean.parseBoolean(v); // } // // private String getProperty(String name) { // return properties.getProperty("pie." + name); // } // // public boolean isEnabled() { // return getBoolean("enabled", true); // } // // public boolean isRegenerateOnShutdown() { // return getBoolean("regenerateOnShutdown", true); // } // // public boolean isAdminInterfaceEnabled() { // return getBoolean("admininterface.enabled", false); // } // // public boolean isLoggingEnabled() { return getBoolean("loggingEnabled", false); } // // public String getLogPath() { return getProperty("logPath"); } // } // // Path: pie-core/src/main/java/com/coverity/security/pie/core/PolicyConfig.java // public class PolicyConfig { // private final String name; // private final PieConfig pieConfig; // // public PolicyConfig(String name, PieConfig pieConfig) { // this.name = name; // this.pieConfig = pieConfig; // } // // public boolean isEnabled() { // return getBoolean("isEnabled", true); // } // // public boolean isReportOnlyMode() { // return getBoolean("isReportOnlyMode", true); // } // // public boolean isCollapseEnabled() { // return getBoolean("isCollapseEnabled", true); // } // // public URL getPolicyFile() { // String policyFile = getProperty("policyFile"); // if (policyFile != null) { // try { // return new URL(policyFile); // } catch (MalformedURLException e) { // throw new IllegalStateException("Invalid policy URL: " + policyFile); // } // } // URL resource = this.getClass().getClassLoader().getResource(name + ".policy"); // if (resource != null) { // return resource; // } // String catalinaHome = System.getProperty("catalina.home"); // if (catalinaHome != null) { // try { // return new File(catalinaHome + File.separatorChar + "conf" + File.separatorChar + name + ".policy").toURI().toURL(); // } catch (MalformedURLException e) { // throw new IllegalStateException("Could not build default policy file path."); // } // } // // // Default to file in the CWD // try { // return new File(name + ".policy").toURI().toURL(); // } catch (MalformedURLException e) { // throw new RuntimeException(e); // } // } // // public boolean getBoolean(String prop, boolean defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Boolean.parseBoolean(v); // } // public int getInteger(String prop, int defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Integer.parseInt(v); // } // // // public String getProperty(String name) { // return pieConfig.getProperties().getProperty(this.name + "." + name); // } // } // Path: pie-sm/src/test/java/com/coverity/security/pie/policy/securitymanager/PropertyPermissionsTest.java import com.coverity.security.pie.core.PieConfig; import com.coverity.security.pie.core.PolicyConfig; import org.json.JSONObject; import org.testng.annotations.Test; import java.io.IOException; import java.io.StringWriter; import java.util.PropertyPermission; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; package com.coverity.security.pie.policy.securitymanager; public class PropertyPermissionsTest { @Test public void testPropertyPermissions() throws IOException { SecurityManagerPolicy policy = new SecurityManagerPolicy();
policy.setPolicyConfig(new PolicyConfig(policy.getName(), new PieConfig()));
coverity/pie
pie-sm/src/test/java/com/coverity/security/pie/policy/securitymanager/PropertyPermissionsTest.java
// Path: pie-core/src/main/java/com/coverity/security/pie/core/PieConfig.java // public class PieConfig { // // private final Properties properties = new Properties(); // // public PieConfig() { // loadProps(this.getClass().getClassLoader().getResource("pieConfig.default.properties")); // File propFile = new File("pieConfig.properties"); // if (propFile.exists()) { // try { // loadProps(propFile.toURI().toURL()); // } catch (MalformedURLException e) { // throw new RuntimeException(e); // } // } else { // loadProps(this.getClass().getClassLoader().getResource("pieConfig.properties")); // } // } // public PieConfig(URL propertiesUrl) { // loadProps(this.getClass().getClassLoader().getResource("pieConfig.default.properties")); // loadProps(propertiesUrl); // } // private void loadProps(URL propertiesUrl) { // if (propertiesUrl != null) { // InputStream is = null; // try { // is = propertiesUrl.openStream(); // if (is != null) { // properties.load(is); // is.close(); // } // } catch (IOException e) { // IOUtil.closeSilently(is); // throw new RuntimeException(e); // } // } // // } // // public Properties getProperties() { // return properties; // } // // private boolean getBoolean(String prop, boolean defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Boolean.parseBoolean(v); // } // // private String getProperty(String name) { // return properties.getProperty("pie." + name); // } // // public boolean isEnabled() { // return getBoolean("enabled", true); // } // // public boolean isRegenerateOnShutdown() { // return getBoolean("regenerateOnShutdown", true); // } // // public boolean isAdminInterfaceEnabled() { // return getBoolean("admininterface.enabled", false); // } // // public boolean isLoggingEnabled() { return getBoolean("loggingEnabled", false); } // // public String getLogPath() { return getProperty("logPath"); } // } // // Path: pie-core/src/main/java/com/coverity/security/pie/core/PolicyConfig.java // public class PolicyConfig { // private final String name; // private final PieConfig pieConfig; // // public PolicyConfig(String name, PieConfig pieConfig) { // this.name = name; // this.pieConfig = pieConfig; // } // // public boolean isEnabled() { // return getBoolean("isEnabled", true); // } // // public boolean isReportOnlyMode() { // return getBoolean("isReportOnlyMode", true); // } // // public boolean isCollapseEnabled() { // return getBoolean("isCollapseEnabled", true); // } // // public URL getPolicyFile() { // String policyFile = getProperty("policyFile"); // if (policyFile != null) { // try { // return new URL(policyFile); // } catch (MalformedURLException e) { // throw new IllegalStateException("Invalid policy URL: " + policyFile); // } // } // URL resource = this.getClass().getClassLoader().getResource(name + ".policy"); // if (resource != null) { // return resource; // } // String catalinaHome = System.getProperty("catalina.home"); // if (catalinaHome != null) { // try { // return new File(catalinaHome + File.separatorChar + "conf" + File.separatorChar + name + ".policy").toURI().toURL(); // } catch (MalformedURLException e) { // throw new IllegalStateException("Could not build default policy file path."); // } // } // // // Default to file in the CWD // try { // return new File(name + ".policy").toURI().toURL(); // } catch (MalformedURLException e) { // throw new RuntimeException(e); // } // } // // public boolean getBoolean(String prop, boolean defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Boolean.parseBoolean(v); // } // public int getInteger(String prop, int defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Integer.parseInt(v); // } // // // public String getProperty(String name) { // return pieConfig.getProperties().getProperty(this.name + "." + name); // } // }
import com.coverity.security.pie.core.PieConfig; import com.coverity.security.pie.core.PolicyConfig; import org.json.JSONObject; import org.testng.annotations.Test; import java.io.IOException; import java.io.StringWriter; import java.util.PropertyPermission; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue;
package com.coverity.security.pie.policy.securitymanager; public class PropertyPermissionsTest { @Test public void testPropertyPermissions() throws IOException { SecurityManagerPolicy policy = new SecurityManagerPolicy();
// Path: pie-core/src/main/java/com/coverity/security/pie/core/PieConfig.java // public class PieConfig { // // private final Properties properties = new Properties(); // // public PieConfig() { // loadProps(this.getClass().getClassLoader().getResource("pieConfig.default.properties")); // File propFile = new File("pieConfig.properties"); // if (propFile.exists()) { // try { // loadProps(propFile.toURI().toURL()); // } catch (MalformedURLException e) { // throw new RuntimeException(e); // } // } else { // loadProps(this.getClass().getClassLoader().getResource("pieConfig.properties")); // } // } // public PieConfig(URL propertiesUrl) { // loadProps(this.getClass().getClassLoader().getResource("pieConfig.default.properties")); // loadProps(propertiesUrl); // } // private void loadProps(URL propertiesUrl) { // if (propertiesUrl != null) { // InputStream is = null; // try { // is = propertiesUrl.openStream(); // if (is != null) { // properties.load(is); // is.close(); // } // } catch (IOException e) { // IOUtil.closeSilently(is); // throw new RuntimeException(e); // } // } // // } // // public Properties getProperties() { // return properties; // } // // private boolean getBoolean(String prop, boolean defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Boolean.parseBoolean(v); // } // // private String getProperty(String name) { // return properties.getProperty("pie." + name); // } // // public boolean isEnabled() { // return getBoolean("enabled", true); // } // // public boolean isRegenerateOnShutdown() { // return getBoolean("regenerateOnShutdown", true); // } // // public boolean isAdminInterfaceEnabled() { // return getBoolean("admininterface.enabled", false); // } // // public boolean isLoggingEnabled() { return getBoolean("loggingEnabled", false); } // // public String getLogPath() { return getProperty("logPath"); } // } // // Path: pie-core/src/main/java/com/coverity/security/pie/core/PolicyConfig.java // public class PolicyConfig { // private final String name; // private final PieConfig pieConfig; // // public PolicyConfig(String name, PieConfig pieConfig) { // this.name = name; // this.pieConfig = pieConfig; // } // // public boolean isEnabled() { // return getBoolean("isEnabled", true); // } // // public boolean isReportOnlyMode() { // return getBoolean("isReportOnlyMode", true); // } // // public boolean isCollapseEnabled() { // return getBoolean("isCollapseEnabled", true); // } // // public URL getPolicyFile() { // String policyFile = getProperty("policyFile"); // if (policyFile != null) { // try { // return new URL(policyFile); // } catch (MalformedURLException e) { // throw new IllegalStateException("Invalid policy URL: " + policyFile); // } // } // URL resource = this.getClass().getClassLoader().getResource(name + ".policy"); // if (resource != null) { // return resource; // } // String catalinaHome = System.getProperty("catalina.home"); // if (catalinaHome != null) { // try { // return new File(catalinaHome + File.separatorChar + "conf" + File.separatorChar + name + ".policy").toURI().toURL(); // } catch (MalformedURLException e) { // throw new IllegalStateException("Could not build default policy file path."); // } // } // // // Default to file in the CWD // try { // return new File(name + ".policy").toURI().toURL(); // } catch (MalformedURLException e) { // throw new RuntimeException(e); // } // } // // public boolean getBoolean(String prop, boolean defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Boolean.parseBoolean(v); // } // public int getInteger(String prop, int defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Integer.parseInt(v); // } // // // public String getProperty(String name) { // return pieConfig.getProperties().getProperty(this.name + "." + name); // } // } // Path: pie-sm/src/test/java/com/coverity/security/pie/policy/securitymanager/PropertyPermissionsTest.java import com.coverity.security.pie.core.PieConfig; import com.coverity.security.pie.core.PolicyConfig; import org.json.JSONObject; import org.testng.annotations.Test; import java.io.IOException; import java.io.StringWriter; import java.util.PropertyPermission; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; package com.coverity.security.pie.policy.securitymanager; public class PropertyPermissionsTest { @Test public void testPropertyPermissions() throws IOException { SecurityManagerPolicy policy = new SecurityManagerPolicy();
policy.setPolicyConfig(new PolicyConfig(policy.getName(), new PieConfig()));
coverity/pie
pie-core/src/test/java/com/coverity/security/pie/web/PieInitializerTest.java
// Path: pie-core/src/test/java/com/coverity/security/pie/core/test/TestPolicyEnforcer.java // public class TestPolicyEnforcer implements PolicyEnforcer { // // private static TestPolicyEnforcer instance = null; // // public static TestPolicyEnforcer getInstance() { // return instance; // } // // private SimplePolicy policy; // private PolicyConfig policyConfig; // private boolean isApplied = false; // // public TestPolicyEnforcer() { // if (instance != null) { // throw new IllegalStateException("Cannot instantiate more than one TestPolicyEnforcer at a time."); // } // instance = this; // } // // @Override // public void init(PieConfig pieConfig) { // this.policy = new SimplePolicy(); // this.policyConfig = new PolicyConfig(policy.getName(), pieConfig); // } // // @Override // public SimplePolicy getPolicy() { // return policy; // } // // @Override // public PolicyConfig getPolicyConfig() { // return policyConfig; // } // // @Override // public void applyPolicy(ServletContext cx) { // isApplied = true; // } // // @Override // public void shutdown() { // instance = null; // } // // public boolean isApplied() { // return isApplied; // } // } // // Path: pie-core/src/test/java/com/coverity/security/pie/core/test/TomcatContainerWrapper.java // public class TomcatContainerWrapper { // private static class SemaphoreStartupShutdownListener implements ServletContextListener, ServletContainerInitializer { // // private final Semaphore startupSemaphore; // private final Semaphore shutdownSemaphore; // // public SemaphoreStartupShutdownListener() { // this.startupSemaphore = new Semaphore(0); // this.shutdownSemaphore = new Semaphore(0); // } // // @Override // public void onStartup(Set<Class<?>> c, ServletContext ctx) throws ServletException { // ctx.addListener(this); // } // // @Override // public void contextInitialized(ServletContextEvent sce) { // startupSemaphore.release(); // } // // @Override // public void contextDestroyed(ServletContextEvent sce) { // shutdownSemaphore.release(); // } // } // // private final Tomcat tomcat; // private final SemaphoreStartupShutdownListener semaphoreStartupShutdownListener; // // public TomcatContainerWrapper() { // tomcat = new Tomcat(); // tomcat.setPort(18885); // tomcat.setBaseDir("."); // tomcat.getHost().setAppBase("."); // // semaphoreStartupShutdownListener = new SemaphoreStartupShutdownListener(); // } // // public TomcatContainerWrapper start() throws ServletException, LifecycleException, InterruptedException, MalformedURLException { // Context context = tomcat.addWebapp("/myapp", "."); // context.addServletContainerInitializer(semaphoreStartupShutdownListener, null); // tomcat.start(); // semaphoreStartupShutdownListener.startupSemaphore.acquire(); // return this; // } // // public TomcatContainerWrapper stop() throws InterruptedException, LifecycleException { // tomcat.stop(); // tomcat.destroy(); // semaphoreStartupShutdownListener.shutdownSemaphore.acquire(); // return this; // } // } // // Path: pie-core/src/main/java/com/coverity/security/pie/util/IOUtil.java // public class IOUtil { // public static void closeSilently(Closeable closeable) { // if (closeable != null) { // try { // closeable.close(); // } catch (IOException e) { // // Do nothing // } // } // } // // public static String readFile(File file) throws IOException { // return toString(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8)); // } // public static String readFile(String file) throws IOException { // return toString(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8)); // } // public static String readFile(URL file) throws IOException { // return toString(file.openStream()); // } // // public static String toString(InputStream is) throws IOException { // try { // return toString(new InputStreamReader(is, StandardCharsets.UTF_8)); // } finally { // closeSilently(is); // } // } // public static String toString(Reader reader) throws IOException { // StringBuilder sb = new StringBuilder(); // try { // char buffer[] = new char[4096]; // int n; // while ((n = reader.read(buffer)) > 0) { // sb.append(buffer, 0, n); // } // reader.close(); // } catch (IOException e) { // closeSilently(reader); // throw e; // } // return sb.toString(); // } // // // public static void writeFile(File file, String content) throws IOException { // writeFile(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8), content); // } // private static void writeFile(Writer fw, String content) throws IOException { // try { // fw.write(content); // fw.close(); // } catch (IOException e) { // closeSilently(fw); // throw e; // } // } // // }
import com.coverity.security.pie.core.test.TestPolicyEnforcer; import com.coverity.security.pie.core.test.TomcatContainerWrapper; import com.coverity.security.pie.util.IOUtil; import org.apache.catalina.LifecycleException; import org.testng.annotations.Test; import javax.servlet.ServletException; import java.io.File; import java.io.IOException; import java.net.URL; import static org.testng.Assert.*;
package com.coverity.security.pie.web; public class PieInitializerTest { @Test public void testPieDisabled() throws ServletException, LifecycleException, IOException, InterruptedException {
// Path: pie-core/src/test/java/com/coverity/security/pie/core/test/TestPolicyEnforcer.java // public class TestPolicyEnforcer implements PolicyEnforcer { // // private static TestPolicyEnforcer instance = null; // // public static TestPolicyEnforcer getInstance() { // return instance; // } // // private SimplePolicy policy; // private PolicyConfig policyConfig; // private boolean isApplied = false; // // public TestPolicyEnforcer() { // if (instance != null) { // throw new IllegalStateException("Cannot instantiate more than one TestPolicyEnforcer at a time."); // } // instance = this; // } // // @Override // public void init(PieConfig pieConfig) { // this.policy = new SimplePolicy(); // this.policyConfig = new PolicyConfig(policy.getName(), pieConfig); // } // // @Override // public SimplePolicy getPolicy() { // return policy; // } // // @Override // public PolicyConfig getPolicyConfig() { // return policyConfig; // } // // @Override // public void applyPolicy(ServletContext cx) { // isApplied = true; // } // // @Override // public void shutdown() { // instance = null; // } // // public boolean isApplied() { // return isApplied; // } // } // // Path: pie-core/src/test/java/com/coverity/security/pie/core/test/TomcatContainerWrapper.java // public class TomcatContainerWrapper { // private static class SemaphoreStartupShutdownListener implements ServletContextListener, ServletContainerInitializer { // // private final Semaphore startupSemaphore; // private final Semaphore shutdownSemaphore; // // public SemaphoreStartupShutdownListener() { // this.startupSemaphore = new Semaphore(0); // this.shutdownSemaphore = new Semaphore(0); // } // // @Override // public void onStartup(Set<Class<?>> c, ServletContext ctx) throws ServletException { // ctx.addListener(this); // } // // @Override // public void contextInitialized(ServletContextEvent sce) { // startupSemaphore.release(); // } // // @Override // public void contextDestroyed(ServletContextEvent sce) { // shutdownSemaphore.release(); // } // } // // private final Tomcat tomcat; // private final SemaphoreStartupShutdownListener semaphoreStartupShutdownListener; // // public TomcatContainerWrapper() { // tomcat = new Tomcat(); // tomcat.setPort(18885); // tomcat.setBaseDir("."); // tomcat.getHost().setAppBase("."); // // semaphoreStartupShutdownListener = new SemaphoreStartupShutdownListener(); // } // // public TomcatContainerWrapper start() throws ServletException, LifecycleException, InterruptedException, MalformedURLException { // Context context = tomcat.addWebapp("/myapp", "."); // context.addServletContainerInitializer(semaphoreStartupShutdownListener, null); // tomcat.start(); // semaphoreStartupShutdownListener.startupSemaphore.acquire(); // return this; // } // // public TomcatContainerWrapper stop() throws InterruptedException, LifecycleException { // tomcat.stop(); // tomcat.destroy(); // semaphoreStartupShutdownListener.shutdownSemaphore.acquire(); // return this; // } // } // // Path: pie-core/src/main/java/com/coverity/security/pie/util/IOUtil.java // public class IOUtil { // public static void closeSilently(Closeable closeable) { // if (closeable != null) { // try { // closeable.close(); // } catch (IOException e) { // // Do nothing // } // } // } // // public static String readFile(File file) throws IOException { // return toString(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8)); // } // public static String readFile(String file) throws IOException { // return toString(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8)); // } // public static String readFile(URL file) throws IOException { // return toString(file.openStream()); // } // // public static String toString(InputStream is) throws IOException { // try { // return toString(new InputStreamReader(is, StandardCharsets.UTF_8)); // } finally { // closeSilently(is); // } // } // public static String toString(Reader reader) throws IOException { // StringBuilder sb = new StringBuilder(); // try { // char buffer[] = new char[4096]; // int n; // while ((n = reader.read(buffer)) > 0) { // sb.append(buffer, 0, n); // } // reader.close(); // } catch (IOException e) { // closeSilently(reader); // throw e; // } // return sb.toString(); // } // // // public static void writeFile(File file, String content) throws IOException { // writeFile(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8), content); // } // private static void writeFile(Writer fw, String content) throws IOException { // try { // fw.write(content); // fw.close(); // } catch (IOException e) { // closeSilently(fw); // throw e; // } // } // // } // Path: pie-core/src/test/java/com/coverity/security/pie/web/PieInitializerTest.java import com.coverity.security.pie.core.test.TestPolicyEnforcer; import com.coverity.security.pie.core.test.TomcatContainerWrapper; import com.coverity.security.pie.util.IOUtil; import org.apache.catalina.LifecycleException; import org.testng.annotations.Test; import javax.servlet.ServletException; import java.io.File; import java.io.IOException; import java.net.URL; import static org.testng.Assert.*; package com.coverity.security.pie.web; public class PieInitializerTest { @Test public void testPieDisabled() throws ServletException, LifecycleException, IOException, InterruptedException {
IOUtil.writeFile(new File("target/test-classes/pieConfig.properties"), "pie.enabled = false");
coverity/pie
pie-core/src/test/java/com/coverity/security/pie/web/PieInitializerTest.java
// Path: pie-core/src/test/java/com/coverity/security/pie/core/test/TestPolicyEnforcer.java // public class TestPolicyEnforcer implements PolicyEnforcer { // // private static TestPolicyEnforcer instance = null; // // public static TestPolicyEnforcer getInstance() { // return instance; // } // // private SimplePolicy policy; // private PolicyConfig policyConfig; // private boolean isApplied = false; // // public TestPolicyEnforcer() { // if (instance != null) { // throw new IllegalStateException("Cannot instantiate more than one TestPolicyEnforcer at a time."); // } // instance = this; // } // // @Override // public void init(PieConfig pieConfig) { // this.policy = new SimplePolicy(); // this.policyConfig = new PolicyConfig(policy.getName(), pieConfig); // } // // @Override // public SimplePolicy getPolicy() { // return policy; // } // // @Override // public PolicyConfig getPolicyConfig() { // return policyConfig; // } // // @Override // public void applyPolicy(ServletContext cx) { // isApplied = true; // } // // @Override // public void shutdown() { // instance = null; // } // // public boolean isApplied() { // return isApplied; // } // } // // Path: pie-core/src/test/java/com/coverity/security/pie/core/test/TomcatContainerWrapper.java // public class TomcatContainerWrapper { // private static class SemaphoreStartupShutdownListener implements ServletContextListener, ServletContainerInitializer { // // private final Semaphore startupSemaphore; // private final Semaphore shutdownSemaphore; // // public SemaphoreStartupShutdownListener() { // this.startupSemaphore = new Semaphore(0); // this.shutdownSemaphore = new Semaphore(0); // } // // @Override // public void onStartup(Set<Class<?>> c, ServletContext ctx) throws ServletException { // ctx.addListener(this); // } // // @Override // public void contextInitialized(ServletContextEvent sce) { // startupSemaphore.release(); // } // // @Override // public void contextDestroyed(ServletContextEvent sce) { // shutdownSemaphore.release(); // } // } // // private final Tomcat tomcat; // private final SemaphoreStartupShutdownListener semaphoreStartupShutdownListener; // // public TomcatContainerWrapper() { // tomcat = new Tomcat(); // tomcat.setPort(18885); // tomcat.setBaseDir("."); // tomcat.getHost().setAppBase("."); // // semaphoreStartupShutdownListener = new SemaphoreStartupShutdownListener(); // } // // public TomcatContainerWrapper start() throws ServletException, LifecycleException, InterruptedException, MalformedURLException { // Context context = tomcat.addWebapp("/myapp", "."); // context.addServletContainerInitializer(semaphoreStartupShutdownListener, null); // tomcat.start(); // semaphoreStartupShutdownListener.startupSemaphore.acquire(); // return this; // } // // public TomcatContainerWrapper stop() throws InterruptedException, LifecycleException { // tomcat.stop(); // tomcat.destroy(); // semaphoreStartupShutdownListener.shutdownSemaphore.acquire(); // return this; // } // } // // Path: pie-core/src/main/java/com/coverity/security/pie/util/IOUtil.java // public class IOUtil { // public static void closeSilently(Closeable closeable) { // if (closeable != null) { // try { // closeable.close(); // } catch (IOException e) { // // Do nothing // } // } // } // // public static String readFile(File file) throws IOException { // return toString(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8)); // } // public static String readFile(String file) throws IOException { // return toString(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8)); // } // public static String readFile(URL file) throws IOException { // return toString(file.openStream()); // } // // public static String toString(InputStream is) throws IOException { // try { // return toString(new InputStreamReader(is, StandardCharsets.UTF_8)); // } finally { // closeSilently(is); // } // } // public static String toString(Reader reader) throws IOException { // StringBuilder sb = new StringBuilder(); // try { // char buffer[] = new char[4096]; // int n; // while ((n = reader.read(buffer)) > 0) { // sb.append(buffer, 0, n); // } // reader.close(); // } catch (IOException e) { // closeSilently(reader); // throw e; // } // return sb.toString(); // } // // // public static void writeFile(File file, String content) throws IOException { // writeFile(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8), content); // } // private static void writeFile(Writer fw, String content) throws IOException { // try { // fw.write(content); // fw.close(); // } catch (IOException e) { // closeSilently(fw); // throw e; // } // } // // }
import com.coverity.security.pie.core.test.TestPolicyEnforcer; import com.coverity.security.pie.core.test.TomcatContainerWrapper; import com.coverity.security.pie.util.IOUtil; import org.apache.catalina.LifecycleException; import org.testng.annotations.Test; import javax.servlet.ServletException; import java.io.File; import java.io.IOException; import java.net.URL; import static org.testng.Assert.*;
package com.coverity.security.pie.web; public class PieInitializerTest { @Test public void testPieDisabled() throws ServletException, LifecycleException, IOException, InterruptedException { IOUtil.writeFile(new File("target/test-classes/pieConfig.properties"), "pie.enabled = false");
// Path: pie-core/src/test/java/com/coverity/security/pie/core/test/TestPolicyEnforcer.java // public class TestPolicyEnforcer implements PolicyEnforcer { // // private static TestPolicyEnforcer instance = null; // // public static TestPolicyEnforcer getInstance() { // return instance; // } // // private SimplePolicy policy; // private PolicyConfig policyConfig; // private boolean isApplied = false; // // public TestPolicyEnforcer() { // if (instance != null) { // throw new IllegalStateException("Cannot instantiate more than one TestPolicyEnforcer at a time."); // } // instance = this; // } // // @Override // public void init(PieConfig pieConfig) { // this.policy = new SimplePolicy(); // this.policyConfig = new PolicyConfig(policy.getName(), pieConfig); // } // // @Override // public SimplePolicy getPolicy() { // return policy; // } // // @Override // public PolicyConfig getPolicyConfig() { // return policyConfig; // } // // @Override // public void applyPolicy(ServletContext cx) { // isApplied = true; // } // // @Override // public void shutdown() { // instance = null; // } // // public boolean isApplied() { // return isApplied; // } // } // // Path: pie-core/src/test/java/com/coverity/security/pie/core/test/TomcatContainerWrapper.java // public class TomcatContainerWrapper { // private static class SemaphoreStartupShutdownListener implements ServletContextListener, ServletContainerInitializer { // // private final Semaphore startupSemaphore; // private final Semaphore shutdownSemaphore; // // public SemaphoreStartupShutdownListener() { // this.startupSemaphore = new Semaphore(0); // this.shutdownSemaphore = new Semaphore(0); // } // // @Override // public void onStartup(Set<Class<?>> c, ServletContext ctx) throws ServletException { // ctx.addListener(this); // } // // @Override // public void contextInitialized(ServletContextEvent sce) { // startupSemaphore.release(); // } // // @Override // public void contextDestroyed(ServletContextEvent sce) { // shutdownSemaphore.release(); // } // } // // private final Tomcat tomcat; // private final SemaphoreStartupShutdownListener semaphoreStartupShutdownListener; // // public TomcatContainerWrapper() { // tomcat = new Tomcat(); // tomcat.setPort(18885); // tomcat.setBaseDir("."); // tomcat.getHost().setAppBase("."); // // semaphoreStartupShutdownListener = new SemaphoreStartupShutdownListener(); // } // // public TomcatContainerWrapper start() throws ServletException, LifecycleException, InterruptedException, MalformedURLException { // Context context = tomcat.addWebapp("/myapp", "."); // context.addServletContainerInitializer(semaphoreStartupShutdownListener, null); // tomcat.start(); // semaphoreStartupShutdownListener.startupSemaphore.acquire(); // return this; // } // // public TomcatContainerWrapper stop() throws InterruptedException, LifecycleException { // tomcat.stop(); // tomcat.destroy(); // semaphoreStartupShutdownListener.shutdownSemaphore.acquire(); // return this; // } // } // // Path: pie-core/src/main/java/com/coverity/security/pie/util/IOUtil.java // public class IOUtil { // public static void closeSilently(Closeable closeable) { // if (closeable != null) { // try { // closeable.close(); // } catch (IOException e) { // // Do nothing // } // } // } // // public static String readFile(File file) throws IOException { // return toString(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8)); // } // public static String readFile(String file) throws IOException { // return toString(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8)); // } // public static String readFile(URL file) throws IOException { // return toString(file.openStream()); // } // // public static String toString(InputStream is) throws IOException { // try { // return toString(new InputStreamReader(is, StandardCharsets.UTF_8)); // } finally { // closeSilently(is); // } // } // public static String toString(Reader reader) throws IOException { // StringBuilder sb = new StringBuilder(); // try { // char buffer[] = new char[4096]; // int n; // while ((n = reader.read(buffer)) > 0) { // sb.append(buffer, 0, n); // } // reader.close(); // } catch (IOException e) { // closeSilently(reader); // throw e; // } // return sb.toString(); // } // // // public static void writeFile(File file, String content) throws IOException { // writeFile(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8), content); // } // private static void writeFile(Writer fw, String content) throws IOException { // try { // fw.write(content); // fw.close(); // } catch (IOException e) { // closeSilently(fw); // throw e; // } // } // // } // Path: pie-core/src/test/java/com/coverity/security/pie/web/PieInitializerTest.java import com.coverity.security.pie.core.test.TestPolicyEnforcer; import com.coverity.security.pie.core.test.TomcatContainerWrapper; import com.coverity.security.pie.util.IOUtil; import org.apache.catalina.LifecycleException; import org.testng.annotations.Test; import javax.servlet.ServletException; import java.io.File; import java.io.IOException; import java.net.URL; import static org.testng.Assert.*; package com.coverity.security.pie.web; public class PieInitializerTest { @Test public void testPieDisabled() throws ServletException, LifecycleException, IOException, InterruptedException { IOUtil.writeFile(new File("target/test-classes/pieConfig.properties"), "pie.enabled = false");
TomcatContainerWrapper tomcat = new TomcatContainerWrapper();
coverity/pie
pie-core/src/test/java/com/coverity/security/pie/web/PieInitializerTest.java
// Path: pie-core/src/test/java/com/coverity/security/pie/core/test/TestPolicyEnforcer.java // public class TestPolicyEnforcer implements PolicyEnforcer { // // private static TestPolicyEnforcer instance = null; // // public static TestPolicyEnforcer getInstance() { // return instance; // } // // private SimplePolicy policy; // private PolicyConfig policyConfig; // private boolean isApplied = false; // // public TestPolicyEnforcer() { // if (instance != null) { // throw new IllegalStateException("Cannot instantiate more than one TestPolicyEnforcer at a time."); // } // instance = this; // } // // @Override // public void init(PieConfig pieConfig) { // this.policy = new SimplePolicy(); // this.policyConfig = new PolicyConfig(policy.getName(), pieConfig); // } // // @Override // public SimplePolicy getPolicy() { // return policy; // } // // @Override // public PolicyConfig getPolicyConfig() { // return policyConfig; // } // // @Override // public void applyPolicy(ServletContext cx) { // isApplied = true; // } // // @Override // public void shutdown() { // instance = null; // } // // public boolean isApplied() { // return isApplied; // } // } // // Path: pie-core/src/test/java/com/coverity/security/pie/core/test/TomcatContainerWrapper.java // public class TomcatContainerWrapper { // private static class SemaphoreStartupShutdownListener implements ServletContextListener, ServletContainerInitializer { // // private final Semaphore startupSemaphore; // private final Semaphore shutdownSemaphore; // // public SemaphoreStartupShutdownListener() { // this.startupSemaphore = new Semaphore(0); // this.shutdownSemaphore = new Semaphore(0); // } // // @Override // public void onStartup(Set<Class<?>> c, ServletContext ctx) throws ServletException { // ctx.addListener(this); // } // // @Override // public void contextInitialized(ServletContextEvent sce) { // startupSemaphore.release(); // } // // @Override // public void contextDestroyed(ServletContextEvent sce) { // shutdownSemaphore.release(); // } // } // // private final Tomcat tomcat; // private final SemaphoreStartupShutdownListener semaphoreStartupShutdownListener; // // public TomcatContainerWrapper() { // tomcat = new Tomcat(); // tomcat.setPort(18885); // tomcat.setBaseDir("."); // tomcat.getHost().setAppBase("."); // // semaphoreStartupShutdownListener = new SemaphoreStartupShutdownListener(); // } // // public TomcatContainerWrapper start() throws ServletException, LifecycleException, InterruptedException, MalformedURLException { // Context context = tomcat.addWebapp("/myapp", "."); // context.addServletContainerInitializer(semaphoreStartupShutdownListener, null); // tomcat.start(); // semaphoreStartupShutdownListener.startupSemaphore.acquire(); // return this; // } // // public TomcatContainerWrapper stop() throws InterruptedException, LifecycleException { // tomcat.stop(); // tomcat.destroy(); // semaphoreStartupShutdownListener.shutdownSemaphore.acquire(); // return this; // } // } // // Path: pie-core/src/main/java/com/coverity/security/pie/util/IOUtil.java // public class IOUtil { // public static void closeSilently(Closeable closeable) { // if (closeable != null) { // try { // closeable.close(); // } catch (IOException e) { // // Do nothing // } // } // } // // public static String readFile(File file) throws IOException { // return toString(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8)); // } // public static String readFile(String file) throws IOException { // return toString(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8)); // } // public static String readFile(URL file) throws IOException { // return toString(file.openStream()); // } // // public static String toString(InputStream is) throws IOException { // try { // return toString(new InputStreamReader(is, StandardCharsets.UTF_8)); // } finally { // closeSilently(is); // } // } // public static String toString(Reader reader) throws IOException { // StringBuilder sb = new StringBuilder(); // try { // char buffer[] = new char[4096]; // int n; // while ((n = reader.read(buffer)) > 0) { // sb.append(buffer, 0, n); // } // reader.close(); // } catch (IOException e) { // closeSilently(reader); // throw e; // } // return sb.toString(); // } // // // public static void writeFile(File file, String content) throws IOException { // writeFile(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8), content); // } // private static void writeFile(Writer fw, String content) throws IOException { // try { // fw.write(content); // fw.close(); // } catch (IOException e) { // closeSilently(fw); // throw e; // } // } // // }
import com.coverity.security.pie.core.test.TestPolicyEnforcer; import com.coverity.security.pie.core.test.TomcatContainerWrapper; import com.coverity.security.pie.util.IOUtil; import org.apache.catalina.LifecycleException; import org.testng.annotations.Test; import javax.servlet.ServletException; import java.io.File; import java.io.IOException; import java.net.URL; import static org.testng.Assert.*;
package com.coverity.security.pie.web; public class PieInitializerTest { @Test public void testPieDisabled() throws ServletException, LifecycleException, IOException, InterruptedException { IOUtil.writeFile(new File("target/test-classes/pieConfig.properties"), "pie.enabled = false"); TomcatContainerWrapper tomcat = new TomcatContainerWrapper(); try { tomcat.start();
// Path: pie-core/src/test/java/com/coverity/security/pie/core/test/TestPolicyEnforcer.java // public class TestPolicyEnforcer implements PolicyEnforcer { // // private static TestPolicyEnforcer instance = null; // // public static TestPolicyEnforcer getInstance() { // return instance; // } // // private SimplePolicy policy; // private PolicyConfig policyConfig; // private boolean isApplied = false; // // public TestPolicyEnforcer() { // if (instance != null) { // throw new IllegalStateException("Cannot instantiate more than one TestPolicyEnforcer at a time."); // } // instance = this; // } // // @Override // public void init(PieConfig pieConfig) { // this.policy = new SimplePolicy(); // this.policyConfig = new PolicyConfig(policy.getName(), pieConfig); // } // // @Override // public SimplePolicy getPolicy() { // return policy; // } // // @Override // public PolicyConfig getPolicyConfig() { // return policyConfig; // } // // @Override // public void applyPolicy(ServletContext cx) { // isApplied = true; // } // // @Override // public void shutdown() { // instance = null; // } // // public boolean isApplied() { // return isApplied; // } // } // // Path: pie-core/src/test/java/com/coverity/security/pie/core/test/TomcatContainerWrapper.java // public class TomcatContainerWrapper { // private static class SemaphoreStartupShutdownListener implements ServletContextListener, ServletContainerInitializer { // // private final Semaphore startupSemaphore; // private final Semaphore shutdownSemaphore; // // public SemaphoreStartupShutdownListener() { // this.startupSemaphore = new Semaphore(0); // this.shutdownSemaphore = new Semaphore(0); // } // // @Override // public void onStartup(Set<Class<?>> c, ServletContext ctx) throws ServletException { // ctx.addListener(this); // } // // @Override // public void contextInitialized(ServletContextEvent sce) { // startupSemaphore.release(); // } // // @Override // public void contextDestroyed(ServletContextEvent sce) { // shutdownSemaphore.release(); // } // } // // private final Tomcat tomcat; // private final SemaphoreStartupShutdownListener semaphoreStartupShutdownListener; // // public TomcatContainerWrapper() { // tomcat = new Tomcat(); // tomcat.setPort(18885); // tomcat.setBaseDir("."); // tomcat.getHost().setAppBase("."); // // semaphoreStartupShutdownListener = new SemaphoreStartupShutdownListener(); // } // // public TomcatContainerWrapper start() throws ServletException, LifecycleException, InterruptedException, MalformedURLException { // Context context = tomcat.addWebapp("/myapp", "."); // context.addServletContainerInitializer(semaphoreStartupShutdownListener, null); // tomcat.start(); // semaphoreStartupShutdownListener.startupSemaphore.acquire(); // return this; // } // // public TomcatContainerWrapper stop() throws InterruptedException, LifecycleException { // tomcat.stop(); // tomcat.destroy(); // semaphoreStartupShutdownListener.shutdownSemaphore.acquire(); // return this; // } // } // // Path: pie-core/src/main/java/com/coverity/security/pie/util/IOUtil.java // public class IOUtil { // public static void closeSilently(Closeable closeable) { // if (closeable != null) { // try { // closeable.close(); // } catch (IOException e) { // // Do nothing // } // } // } // // public static String readFile(File file) throws IOException { // return toString(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8)); // } // public static String readFile(String file) throws IOException { // return toString(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8)); // } // public static String readFile(URL file) throws IOException { // return toString(file.openStream()); // } // // public static String toString(InputStream is) throws IOException { // try { // return toString(new InputStreamReader(is, StandardCharsets.UTF_8)); // } finally { // closeSilently(is); // } // } // public static String toString(Reader reader) throws IOException { // StringBuilder sb = new StringBuilder(); // try { // char buffer[] = new char[4096]; // int n; // while ((n = reader.read(buffer)) > 0) { // sb.append(buffer, 0, n); // } // reader.close(); // } catch (IOException e) { // closeSilently(reader); // throw e; // } // return sb.toString(); // } // // // public static void writeFile(File file, String content) throws IOException { // writeFile(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8), content); // } // private static void writeFile(Writer fw, String content) throws IOException { // try { // fw.write(content); // fw.close(); // } catch (IOException e) { // closeSilently(fw); // throw e; // } // } // // } // Path: pie-core/src/test/java/com/coverity/security/pie/web/PieInitializerTest.java import com.coverity.security.pie.core.test.TestPolicyEnforcer; import com.coverity.security.pie.core.test.TomcatContainerWrapper; import com.coverity.security.pie.util.IOUtil; import org.apache.catalina.LifecycleException; import org.testng.annotations.Test; import javax.servlet.ServletException; import java.io.File; import java.io.IOException; import java.net.URL; import static org.testng.Assert.*; package com.coverity.security.pie.web; public class PieInitializerTest { @Test public void testPieDisabled() throws ServletException, LifecycleException, IOException, InterruptedException { IOUtil.writeFile(new File("target/test-classes/pieConfig.properties"), "pie.enabled = false"); TomcatContainerWrapper tomcat = new TomcatContainerWrapper(); try { tomcat.start();
assertNull(TestPolicyEnforcer.getInstance());
coverity/pie
pie-sm/src/test/java/com/coverity/security/pie/policy/securitymanager/DynamicJavaPolicyTest.java
// Path: pie-core/src/main/java/com/coverity/security/pie/core/PieConfig.java // public class PieConfig { // // private final Properties properties = new Properties(); // // public PieConfig() { // loadProps(this.getClass().getClassLoader().getResource("pieConfig.default.properties")); // File propFile = new File("pieConfig.properties"); // if (propFile.exists()) { // try { // loadProps(propFile.toURI().toURL()); // } catch (MalformedURLException e) { // throw new RuntimeException(e); // } // } else { // loadProps(this.getClass().getClassLoader().getResource("pieConfig.properties")); // } // } // public PieConfig(URL propertiesUrl) { // loadProps(this.getClass().getClassLoader().getResource("pieConfig.default.properties")); // loadProps(propertiesUrl); // } // private void loadProps(URL propertiesUrl) { // if (propertiesUrl != null) { // InputStream is = null; // try { // is = propertiesUrl.openStream(); // if (is != null) { // properties.load(is); // is.close(); // } // } catch (IOException e) { // IOUtil.closeSilently(is); // throw new RuntimeException(e); // } // } // // } // // public Properties getProperties() { // return properties; // } // // private boolean getBoolean(String prop, boolean defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Boolean.parseBoolean(v); // } // // private String getProperty(String name) { // return properties.getProperty("pie." + name); // } // // public boolean isEnabled() { // return getBoolean("enabled", true); // } // // public boolean isRegenerateOnShutdown() { // return getBoolean("regenerateOnShutdown", true); // } // // public boolean isAdminInterfaceEnabled() { // return getBoolean("admininterface.enabled", false); // } // // public boolean isLoggingEnabled() { return getBoolean("loggingEnabled", false); } // // public String getLogPath() { return getProperty("logPath"); } // } // // Path: pie-core/src/main/java/com/coverity/security/pie/core/PolicyConfig.java // public class PolicyConfig { // private final String name; // private final PieConfig pieConfig; // // public PolicyConfig(String name, PieConfig pieConfig) { // this.name = name; // this.pieConfig = pieConfig; // } // // public boolean isEnabled() { // return getBoolean("isEnabled", true); // } // // public boolean isReportOnlyMode() { // return getBoolean("isReportOnlyMode", true); // } // // public boolean isCollapseEnabled() { // return getBoolean("isCollapseEnabled", true); // } // // public URL getPolicyFile() { // String policyFile = getProperty("policyFile"); // if (policyFile != null) { // try { // return new URL(policyFile); // } catch (MalformedURLException e) { // throw new IllegalStateException("Invalid policy URL: " + policyFile); // } // } // URL resource = this.getClass().getClassLoader().getResource(name + ".policy"); // if (resource != null) { // return resource; // } // String catalinaHome = System.getProperty("catalina.home"); // if (catalinaHome != null) { // try { // return new File(catalinaHome + File.separatorChar + "conf" + File.separatorChar + name + ".policy").toURI().toURL(); // } catch (MalformedURLException e) { // throw new IllegalStateException("Could not build default policy file path."); // } // } // // // Default to file in the CWD // try { // return new File(name + ".policy").toURI().toURL(); // } catch (MalformedURLException e) { // throw new RuntimeException(e); // } // } // // public boolean getBoolean(String prop, boolean defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Boolean.parseBoolean(v); // } // public int getInteger(String prop, int defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Integer.parseInt(v); // } // // // public String getProperty(String name) { // return pieConfig.getProperties().getProperty(this.name + "." + name); // } // }
import com.coverity.security.pie.core.PieConfig; import com.coverity.security.pie.core.PolicyConfig; import org.testng.annotations.Test; import java.security.Permission; import java.security.ProtectionDomain; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue;
package com.coverity.security.pie.policy.securitymanager; public class DynamicJavaPolicyTest { @Test public void testSetSecurityManagerDenied() {
// Path: pie-core/src/main/java/com/coverity/security/pie/core/PieConfig.java // public class PieConfig { // // private final Properties properties = new Properties(); // // public PieConfig() { // loadProps(this.getClass().getClassLoader().getResource("pieConfig.default.properties")); // File propFile = new File("pieConfig.properties"); // if (propFile.exists()) { // try { // loadProps(propFile.toURI().toURL()); // } catch (MalformedURLException e) { // throw new RuntimeException(e); // } // } else { // loadProps(this.getClass().getClassLoader().getResource("pieConfig.properties")); // } // } // public PieConfig(URL propertiesUrl) { // loadProps(this.getClass().getClassLoader().getResource("pieConfig.default.properties")); // loadProps(propertiesUrl); // } // private void loadProps(URL propertiesUrl) { // if (propertiesUrl != null) { // InputStream is = null; // try { // is = propertiesUrl.openStream(); // if (is != null) { // properties.load(is); // is.close(); // } // } catch (IOException e) { // IOUtil.closeSilently(is); // throw new RuntimeException(e); // } // } // // } // // public Properties getProperties() { // return properties; // } // // private boolean getBoolean(String prop, boolean defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Boolean.parseBoolean(v); // } // // private String getProperty(String name) { // return properties.getProperty("pie." + name); // } // // public boolean isEnabled() { // return getBoolean("enabled", true); // } // // public boolean isRegenerateOnShutdown() { // return getBoolean("regenerateOnShutdown", true); // } // // public boolean isAdminInterfaceEnabled() { // return getBoolean("admininterface.enabled", false); // } // // public boolean isLoggingEnabled() { return getBoolean("loggingEnabled", false); } // // public String getLogPath() { return getProperty("logPath"); } // } // // Path: pie-core/src/main/java/com/coverity/security/pie/core/PolicyConfig.java // public class PolicyConfig { // private final String name; // private final PieConfig pieConfig; // // public PolicyConfig(String name, PieConfig pieConfig) { // this.name = name; // this.pieConfig = pieConfig; // } // // public boolean isEnabled() { // return getBoolean("isEnabled", true); // } // // public boolean isReportOnlyMode() { // return getBoolean("isReportOnlyMode", true); // } // // public boolean isCollapseEnabled() { // return getBoolean("isCollapseEnabled", true); // } // // public URL getPolicyFile() { // String policyFile = getProperty("policyFile"); // if (policyFile != null) { // try { // return new URL(policyFile); // } catch (MalformedURLException e) { // throw new IllegalStateException("Invalid policy URL: " + policyFile); // } // } // URL resource = this.getClass().getClassLoader().getResource(name + ".policy"); // if (resource != null) { // return resource; // } // String catalinaHome = System.getProperty("catalina.home"); // if (catalinaHome != null) { // try { // return new File(catalinaHome + File.separatorChar + "conf" + File.separatorChar + name + ".policy").toURI().toURL(); // } catch (MalformedURLException e) { // throw new IllegalStateException("Could not build default policy file path."); // } // } // // // Default to file in the CWD // try { // return new File(name + ".policy").toURI().toURL(); // } catch (MalformedURLException e) { // throw new RuntimeException(e); // } // } // // public boolean getBoolean(String prop, boolean defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Boolean.parseBoolean(v); // } // public int getInteger(String prop, int defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Integer.parseInt(v); // } // // // public String getProperty(String name) { // return pieConfig.getProperties().getProperty(this.name + "." + name); // } // } // Path: pie-sm/src/test/java/com/coverity/security/pie/policy/securitymanager/DynamicJavaPolicyTest.java import com.coverity.security.pie.core.PieConfig; import com.coverity.security.pie.core.PolicyConfig; import org.testng.annotations.Test; import java.security.Permission; import java.security.ProtectionDomain; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; package com.coverity.security.pie.policy.securitymanager; public class DynamicJavaPolicyTest { @Test public void testSetSecurityManagerDenied() {
PieConfig pieConfig = new PieConfig();
coverity/pie
pie-sm/src/test/java/com/coverity/security/pie/policy/securitymanager/DynamicJavaPolicyTest.java
// Path: pie-core/src/main/java/com/coverity/security/pie/core/PieConfig.java // public class PieConfig { // // private final Properties properties = new Properties(); // // public PieConfig() { // loadProps(this.getClass().getClassLoader().getResource("pieConfig.default.properties")); // File propFile = new File("pieConfig.properties"); // if (propFile.exists()) { // try { // loadProps(propFile.toURI().toURL()); // } catch (MalformedURLException e) { // throw new RuntimeException(e); // } // } else { // loadProps(this.getClass().getClassLoader().getResource("pieConfig.properties")); // } // } // public PieConfig(URL propertiesUrl) { // loadProps(this.getClass().getClassLoader().getResource("pieConfig.default.properties")); // loadProps(propertiesUrl); // } // private void loadProps(URL propertiesUrl) { // if (propertiesUrl != null) { // InputStream is = null; // try { // is = propertiesUrl.openStream(); // if (is != null) { // properties.load(is); // is.close(); // } // } catch (IOException e) { // IOUtil.closeSilently(is); // throw new RuntimeException(e); // } // } // // } // // public Properties getProperties() { // return properties; // } // // private boolean getBoolean(String prop, boolean defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Boolean.parseBoolean(v); // } // // private String getProperty(String name) { // return properties.getProperty("pie." + name); // } // // public boolean isEnabled() { // return getBoolean("enabled", true); // } // // public boolean isRegenerateOnShutdown() { // return getBoolean("regenerateOnShutdown", true); // } // // public boolean isAdminInterfaceEnabled() { // return getBoolean("admininterface.enabled", false); // } // // public boolean isLoggingEnabled() { return getBoolean("loggingEnabled", false); } // // public String getLogPath() { return getProperty("logPath"); } // } // // Path: pie-core/src/main/java/com/coverity/security/pie/core/PolicyConfig.java // public class PolicyConfig { // private final String name; // private final PieConfig pieConfig; // // public PolicyConfig(String name, PieConfig pieConfig) { // this.name = name; // this.pieConfig = pieConfig; // } // // public boolean isEnabled() { // return getBoolean("isEnabled", true); // } // // public boolean isReportOnlyMode() { // return getBoolean("isReportOnlyMode", true); // } // // public boolean isCollapseEnabled() { // return getBoolean("isCollapseEnabled", true); // } // // public URL getPolicyFile() { // String policyFile = getProperty("policyFile"); // if (policyFile != null) { // try { // return new URL(policyFile); // } catch (MalformedURLException e) { // throw new IllegalStateException("Invalid policy URL: " + policyFile); // } // } // URL resource = this.getClass().getClassLoader().getResource(name + ".policy"); // if (resource != null) { // return resource; // } // String catalinaHome = System.getProperty("catalina.home"); // if (catalinaHome != null) { // try { // return new File(catalinaHome + File.separatorChar + "conf" + File.separatorChar + name + ".policy").toURI().toURL(); // } catch (MalformedURLException e) { // throw new IllegalStateException("Could not build default policy file path."); // } // } // // // Default to file in the CWD // try { // return new File(name + ".policy").toURI().toURL(); // } catch (MalformedURLException e) { // throw new RuntimeException(e); // } // } // // public boolean getBoolean(String prop, boolean defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Boolean.parseBoolean(v); // } // public int getInteger(String prop, int defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Integer.parseInt(v); // } // // // public String getProperty(String name) { // return pieConfig.getProperties().getProperty(this.name + "." + name); // } // }
import com.coverity.security.pie.core.PieConfig; import com.coverity.security.pie.core.PolicyConfig; import org.testng.annotations.Test; import java.security.Permission; import java.security.ProtectionDomain; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue;
package com.coverity.security.pie.policy.securitymanager; public class DynamicJavaPolicyTest { @Test public void testSetSecurityManagerDenied() { PieConfig pieConfig = new PieConfig(); SecurityManagerPolicy policy = new SecurityManagerPolicy();
// Path: pie-core/src/main/java/com/coverity/security/pie/core/PieConfig.java // public class PieConfig { // // private final Properties properties = new Properties(); // // public PieConfig() { // loadProps(this.getClass().getClassLoader().getResource("pieConfig.default.properties")); // File propFile = new File("pieConfig.properties"); // if (propFile.exists()) { // try { // loadProps(propFile.toURI().toURL()); // } catch (MalformedURLException e) { // throw new RuntimeException(e); // } // } else { // loadProps(this.getClass().getClassLoader().getResource("pieConfig.properties")); // } // } // public PieConfig(URL propertiesUrl) { // loadProps(this.getClass().getClassLoader().getResource("pieConfig.default.properties")); // loadProps(propertiesUrl); // } // private void loadProps(URL propertiesUrl) { // if (propertiesUrl != null) { // InputStream is = null; // try { // is = propertiesUrl.openStream(); // if (is != null) { // properties.load(is); // is.close(); // } // } catch (IOException e) { // IOUtil.closeSilently(is); // throw new RuntimeException(e); // } // } // // } // // public Properties getProperties() { // return properties; // } // // private boolean getBoolean(String prop, boolean defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Boolean.parseBoolean(v); // } // // private String getProperty(String name) { // return properties.getProperty("pie." + name); // } // // public boolean isEnabled() { // return getBoolean("enabled", true); // } // // public boolean isRegenerateOnShutdown() { // return getBoolean("regenerateOnShutdown", true); // } // // public boolean isAdminInterfaceEnabled() { // return getBoolean("admininterface.enabled", false); // } // // public boolean isLoggingEnabled() { return getBoolean("loggingEnabled", false); } // // public String getLogPath() { return getProperty("logPath"); } // } // // Path: pie-core/src/main/java/com/coverity/security/pie/core/PolicyConfig.java // public class PolicyConfig { // private final String name; // private final PieConfig pieConfig; // // public PolicyConfig(String name, PieConfig pieConfig) { // this.name = name; // this.pieConfig = pieConfig; // } // // public boolean isEnabled() { // return getBoolean("isEnabled", true); // } // // public boolean isReportOnlyMode() { // return getBoolean("isReportOnlyMode", true); // } // // public boolean isCollapseEnabled() { // return getBoolean("isCollapseEnabled", true); // } // // public URL getPolicyFile() { // String policyFile = getProperty("policyFile"); // if (policyFile != null) { // try { // return new URL(policyFile); // } catch (MalformedURLException e) { // throw new IllegalStateException("Invalid policy URL: " + policyFile); // } // } // URL resource = this.getClass().getClassLoader().getResource(name + ".policy"); // if (resource != null) { // return resource; // } // String catalinaHome = System.getProperty("catalina.home"); // if (catalinaHome != null) { // try { // return new File(catalinaHome + File.separatorChar + "conf" + File.separatorChar + name + ".policy").toURI().toURL(); // } catch (MalformedURLException e) { // throw new IllegalStateException("Could not build default policy file path."); // } // } // // // Default to file in the CWD // try { // return new File(name + ".policy").toURI().toURL(); // } catch (MalformedURLException e) { // throw new RuntimeException(e); // } // } // // public boolean getBoolean(String prop, boolean defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Boolean.parseBoolean(v); // } // public int getInteger(String prop, int defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Integer.parseInt(v); // } // // // public String getProperty(String name) { // return pieConfig.getProperties().getProperty(this.name + "." + name); // } // } // Path: pie-sm/src/test/java/com/coverity/security/pie/policy/securitymanager/DynamicJavaPolicyTest.java import com.coverity.security.pie.core.PieConfig; import com.coverity.security.pie.core.PolicyConfig; import org.testng.annotations.Test; import java.security.Permission; import java.security.ProtectionDomain; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; package com.coverity.security.pie.policy.securitymanager; public class DynamicJavaPolicyTest { @Test public void testSetSecurityManagerDenied() { PieConfig pieConfig = new PieConfig(); SecurityManagerPolicy policy = new SecurityManagerPolicy();
PolicyConfig policyConfig = new PolicyConfig(policy.getName(), pieConfig);
coverity/pie
pie-core/src/main/java/com/coverity/security/pie/util/collapser/PropertyCollapser.java
// Path: pie-core/src/main/java/com/coverity/security/pie/core/StringCollapser.java // public interface StringCollapser { // /** // * Collapses a security policy according to the concrete implementation's rules. It takes a map from facts to their // * children, and returns a collapsed version of that map. For example, given the map: // * { // * A => {'X', 'Y'}, // * B => {'Z'} // * } // * // * If the implementation determines that the facts A and B should be collapsed to fact C, then this would return // * { // * C => {'X', 'Y', 'Z'} // * } // * // * @param input A map from facts to a collection of child facts. // * @param <T> The type of the child facts; irrelevant to the internal procedure of collapsing. // * @return The collapsed map of facts to their children. // */ // public <T> Map<String, Collection<T>> collapse(Map<String, Collection<T>> input); // } // // Path: pie-core/src/main/java/com/coverity/security/pie/util/StringUtil.java // public class StringUtil { // public static String join(String s, String[] arr, int off, int end) { // if (off < 0 || end > arr.length) { // throw new IllegalArgumentException("Invalid indices"); // } // if (end <= off) { // return ""; // } // // StringBuilder sb = new StringBuilder(); // for (int i = off; i < end-1; i++) { // sb.append(arr[i]).append(s); // } // sb.append(arr[end-1]); // return sb.toString(); // } // // public static String join(String s, List<String> strings) { // if (strings.size() == 0) { // return ""; // } // StringBuilder sb = new StringBuilder(); // for (int i = 0; i < strings.size()-1; i++) { // sb.append(strings.get(i)).append(s); // } // sb.append(strings.get(strings.size()-1)); // return sb.toString(); // } // // // public static String join(String s, String ... strings) { // if (strings.length == 0) { // return ""; // } // StringBuilder sb = new StringBuilder(); // for (int i = 0; i < strings.length-1; i++) { // sb.append(strings[i]).append(s); // } // sb.append(strings[strings.length-1]); // return sb.toString(); // } // }
import java.util.Collection; import java.util.HashMap; import java.util.Map; import com.coverity.security.pie.core.StringCollapser; import com.coverity.security.pie.util.StringUtil;
package com.coverity.security.pie.util.collapser; /** * An implementation of the AbstractPathCollapser which collapses properties. For example, a.b.c.com would match *.c.com */ public class PropertyCollapser extends AbstractPathCollapser implements StringCollapser { public PropertyCollapser(int collapseThreshold) { super("*", "*", collapseThreshold, 0); } @Override public <T> Map<String, Collection<T>> collapse(Map<String, Collection<T>> input) { Map<PathName, Collection<T>> inputMap = new HashMap<PathName, Collection<T>>(input.size()); for (Map.Entry<String, Collection<T>> entry : input.entrySet()) { inputMap.put(new PathName(entry.getKey().split("\\."), null), entry.getValue()); } Map<PathName, Collection<T>> outputMap = collapsePaths(inputMap); Map<String, Collection<T>> output = new HashMap<String, Collection<T>>(outputMap.size()); for (Map.Entry<PathName, Collection<T>> entry : outputMap.entrySet()) {
// Path: pie-core/src/main/java/com/coverity/security/pie/core/StringCollapser.java // public interface StringCollapser { // /** // * Collapses a security policy according to the concrete implementation's rules. It takes a map from facts to their // * children, and returns a collapsed version of that map. For example, given the map: // * { // * A => {'X', 'Y'}, // * B => {'Z'} // * } // * // * If the implementation determines that the facts A and B should be collapsed to fact C, then this would return // * { // * C => {'X', 'Y', 'Z'} // * } // * // * @param input A map from facts to a collection of child facts. // * @param <T> The type of the child facts; irrelevant to the internal procedure of collapsing. // * @return The collapsed map of facts to their children. // */ // public <T> Map<String, Collection<T>> collapse(Map<String, Collection<T>> input); // } // // Path: pie-core/src/main/java/com/coverity/security/pie/util/StringUtil.java // public class StringUtil { // public static String join(String s, String[] arr, int off, int end) { // if (off < 0 || end > arr.length) { // throw new IllegalArgumentException("Invalid indices"); // } // if (end <= off) { // return ""; // } // // StringBuilder sb = new StringBuilder(); // for (int i = off; i < end-1; i++) { // sb.append(arr[i]).append(s); // } // sb.append(arr[end-1]); // return sb.toString(); // } // // public static String join(String s, List<String> strings) { // if (strings.size() == 0) { // return ""; // } // StringBuilder sb = new StringBuilder(); // for (int i = 0; i < strings.size()-1; i++) { // sb.append(strings.get(i)).append(s); // } // sb.append(strings.get(strings.size()-1)); // return sb.toString(); // } // // // public static String join(String s, String ... strings) { // if (strings.length == 0) { // return ""; // } // StringBuilder sb = new StringBuilder(); // for (int i = 0; i < strings.length-1; i++) { // sb.append(strings[i]).append(s); // } // sb.append(strings[strings.length-1]); // return sb.toString(); // } // } // Path: pie-core/src/main/java/com/coverity/security/pie/util/collapser/PropertyCollapser.java import java.util.Collection; import java.util.HashMap; import java.util.Map; import com.coverity.security.pie.core.StringCollapser; import com.coverity.security.pie.util.StringUtil; package com.coverity.security.pie.util.collapser; /** * An implementation of the AbstractPathCollapser which collapses properties. For example, a.b.c.com would match *.c.com */ public class PropertyCollapser extends AbstractPathCollapser implements StringCollapser { public PropertyCollapser(int collapseThreshold) { super("*", "*", collapseThreshold, 0); } @Override public <T> Map<String, Collection<T>> collapse(Map<String, Collection<T>> input) { Map<PathName, Collection<T>> inputMap = new HashMap<PathName, Collection<T>>(input.size()); for (Map.Entry<String, Collection<T>> entry : input.entrySet()) { inputMap.put(new PathName(entry.getKey().split("\\."), null), entry.getValue()); } Map<PathName, Collection<T>> outputMap = collapsePaths(inputMap); Map<String, Collection<T>> output = new HashMap<String, Collection<T>>(outputMap.size()); for (Map.Entry<PathName, Collection<T>> entry : outputMap.entrySet()) {
output.put(StringUtil.join(".", entry.getKey().getPathComponents()), entry.getValue());
coverity/pie
examples/spring-security/src/main/java/com/coverity/security/pie/example/config/SecurityConfig.java
// Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/model/User.java // @Entity // public class User { // @Id @GeneratedValue // private Long id; // // private String username; // // private String passwordHash; // // private Role role; // // // public String getUsername() { // return username; // } // public void setUsername(String username) { // this.username = username; // } // public String getPasswordHash() { // return passwordHash; // } // public void setPasswordHash(String passwordHash) { // this.passwordHash = passwordHash; // } // public Role getRole() { // return role; // } // public void setRole(Role role) { // this.role = role; // } // }
import java.util.Arrays; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.annotation.web.servlet.configuration.EnableWebMvcSecurity; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import com.coverity.security.pie.example.model.User;
package com.coverity.security.pie.example.config; @Configuration @EnableWebMvcSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @PersistenceContext private EntityManager entityManager; @Autowired public void configureGlobal(final AuthenticationManagerBuilder auth, final PasswordEncoder passwordEncoder) throws Exception { auth.authenticationProvider(new AuthenticationProvider() { @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { List<?> result = entityManager.createQuery("SELECT U FROM User U WHERE U.username = :username") .setParameter("username", authentication.getName()) .getResultList(); if (result.size() == 0) { throw new UsernameNotFoundException("Invalid username."); }
// Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/model/User.java // @Entity // public class User { // @Id @GeneratedValue // private Long id; // // private String username; // // private String passwordHash; // // private Role role; // // // public String getUsername() { // return username; // } // public void setUsername(String username) { // this.username = username; // } // public String getPasswordHash() { // return passwordHash; // } // public void setPasswordHash(String passwordHash) { // this.passwordHash = passwordHash; // } // public Role getRole() { // return role; // } // public void setRole(Role role) { // this.role = role; // } // } // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/config/SecurityConfig.java import java.util.Arrays; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.annotation.web.servlet.configuration.EnableWebMvcSecurity; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import com.coverity.security.pie.example.model.User; package com.coverity.security.pie.example.config; @Configuration @EnableWebMvcSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @PersistenceContext private EntityManager entityManager; @Autowired public void configureGlobal(final AuthenticationManagerBuilder auth, final PasswordEncoder passwordEncoder) throws Exception { auth.authenticationProvider(new AuthenticationProvider() { @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { List<?> result = entityManager.createQuery("SELECT U FROM User U WHERE U.username = :username") .setParameter("username", authentication.getName()) .getResultList(); if (result.size() == 0) { throw new UsernameNotFoundException("Invalid username."); }
User user = (User)result.get(0);
coverity/pie
pie-core/src/main/java/com/coverity/security/pie/util/collapser/HostnameCollapser.java
// Path: pie-core/src/main/java/com/coverity/security/pie/core/StringCollapser.java // public interface StringCollapser { // /** // * Collapses a security policy according to the concrete implementation's rules. It takes a map from facts to their // * children, and returns a collapsed version of that map. For example, given the map: // * { // * A => {'X', 'Y'}, // * B => {'Z'} // * } // * // * If the implementation determines that the facts A and B should be collapsed to fact C, then this would return // * { // * C => {'X', 'Y', 'Z'} // * } // * // * @param input A map from facts to a collection of child facts. // * @param <T> The type of the child facts; irrelevant to the internal procedure of collapsing. // * @return The collapsed map of facts to their children. // */ // public <T> Map<String, Collection<T>> collapse(Map<String, Collection<T>> input); // } // // Path: pie-core/src/main/java/com/coverity/security/pie/util/StringUtil.java // public class StringUtil { // public static String join(String s, String[] arr, int off, int end) { // if (off < 0 || end > arr.length) { // throw new IllegalArgumentException("Invalid indices"); // } // if (end <= off) { // return ""; // } // // StringBuilder sb = new StringBuilder(); // for (int i = off; i < end-1; i++) { // sb.append(arr[i]).append(s); // } // sb.append(arr[end-1]); // return sb.toString(); // } // // public static String join(String s, List<String> strings) { // if (strings.size() == 0) { // return ""; // } // StringBuilder sb = new StringBuilder(); // for (int i = 0; i < strings.size()-1; i++) { // sb.append(strings.get(i)).append(s); // } // sb.append(strings.get(strings.size()-1)); // return sb.toString(); // } // // // public static String join(String s, String ... strings) { // if (strings.length == 0) { // return ""; // } // StringBuilder sb = new StringBuilder(); // for (int i = 0; i < strings.length-1; i++) { // sb.append(strings[i]).append(s); // } // sb.append(strings[strings.length-1]); // return sb.toString(); // } // }
import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.coverity.security.pie.core.StringCollapser; import com.coverity.security.pie.util.StringUtil;
if (matchee.getPathComponents().length == 1 && matchee.getPathComponents()[0].charAt(0) == '\'') { return false; } return super.pathNameMatches(matcher, matchee); } @Override public <T> Map<String, Collection<T>> collapse(Map<String, Collection<T>> input) { Map<PathName, Collection<T>> inputMap = new HashMap<PathName, Collection<T>>(input.size()); for (Map.Entry<String, Collection<T>> hostname : input.entrySet()) { // Discard 'none' entirely if other key exists if (hostname.getKey().equals("'none'") && input.size() > 1) { continue; } inputMap.put(toPathName(hostname.getKey()), hostname.getValue()); } Map<PathName, Collection<T>> outputMap = collapsePaths(inputMap); Map<String, Collection<T>> output = new HashMap<String, Collection<T>>(outputMap.size()); for (Map.Entry<PathName, Collection<T>> pathName : outputMap.entrySet()) { if (pathName.getKey().getPathComponents().length == 1 && pathName.getKey().getPathComponents()[0].charAt(0) == '\'') { output.put(pathName.getKey().getPathComponents()[0], pathName.getValue()); } else { String[] schemeAndPort = pathName.getKey().getNonPathComponents(); StringBuilder hostname = new StringBuilder(); if (schemeAndPort != null && schemeAndPort[0] != null) { hostname.append(schemeAndPort[0]).append("://"); }
// Path: pie-core/src/main/java/com/coverity/security/pie/core/StringCollapser.java // public interface StringCollapser { // /** // * Collapses a security policy according to the concrete implementation's rules. It takes a map from facts to their // * children, and returns a collapsed version of that map. For example, given the map: // * { // * A => {'X', 'Y'}, // * B => {'Z'} // * } // * // * If the implementation determines that the facts A and B should be collapsed to fact C, then this would return // * { // * C => {'X', 'Y', 'Z'} // * } // * // * @param input A map from facts to a collection of child facts. // * @param <T> The type of the child facts; irrelevant to the internal procedure of collapsing. // * @return The collapsed map of facts to their children. // */ // public <T> Map<String, Collection<T>> collapse(Map<String, Collection<T>> input); // } // // Path: pie-core/src/main/java/com/coverity/security/pie/util/StringUtil.java // public class StringUtil { // public static String join(String s, String[] arr, int off, int end) { // if (off < 0 || end > arr.length) { // throw new IllegalArgumentException("Invalid indices"); // } // if (end <= off) { // return ""; // } // // StringBuilder sb = new StringBuilder(); // for (int i = off; i < end-1; i++) { // sb.append(arr[i]).append(s); // } // sb.append(arr[end-1]); // return sb.toString(); // } // // public static String join(String s, List<String> strings) { // if (strings.size() == 0) { // return ""; // } // StringBuilder sb = new StringBuilder(); // for (int i = 0; i < strings.size()-1; i++) { // sb.append(strings.get(i)).append(s); // } // sb.append(strings.get(strings.size()-1)); // return sb.toString(); // } // // // public static String join(String s, String ... strings) { // if (strings.length == 0) { // return ""; // } // StringBuilder sb = new StringBuilder(); // for (int i = 0; i < strings.length-1; i++) { // sb.append(strings[i]).append(s); // } // sb.append(strings[strings.length-1]); // return sb.toString(); // } // } // Path: pie-core/src/main/java/com/coverity/security/pie/util/collapser/HostnameCollapser.java import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.coverity.security.pie.core.StringCollapser; import com.coverity.security.pie.util.StringUtil; if (matchee.getPathComponents().length == 1 && matchee.getPathComponents()[0].charAt(0) == '\'') { return false; } return super.pathNameMatches(matcher, matchee); } @Override public <T> Map<String, Collection<T>> collapse(Map<String, Collection<T>> input) { Map<PathName, Collection<T>> inputMap = new HashMap<PathName, Collection<T>>(input.size()); for (Map.Entry<String, Collection<T>> hostname : input.entrySet()) { // Discard 'none' entirely if other key exists if (hostname.getKey().equals("'none'") && input.size() > 1) { continue; } inputMap.put(toPathName(hostname.getKey()), hostname.getValue()); } Map<PathName, Collection<T>> outputMap = collapsePaths(inputMap); Map<String, Collection<T>> output = new HashMap<String, Collection<T>>(outputMap.size()); for (Map.Entry<PathName, Collection<T>> pathName : outputMap.entrySet()) { if (pathName.getKey().getPathComponents().length == 1 && pathName.getKey().getPathComponents()[0].charAt(0) == '\'') { output.put(pathName.getKey().getPathComponents()[0], pathName.getValue()); } else { String[] schemeAndPort = pathName.getKey().getNonPathComponents(); StringBuilder hostname = new StringBuilder(); if (schemeAndPort != null && schemeAndPort[0] != null) { hostname.append(schemeAndPort[0]).append("://"); }
hostname.append(StringUtil.join(".", reverse(pathName.getKey().getPathComponents())));
coverity/pie
examples/spring-security/src/main/java/com/coverity/security/pie/example/service/AccountDao.java
// Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/model/Account.java // @Entity // public class Account { // // @Id @GeneratedValue // private Long id; // // @ManyToOne(optional = false) // private User user; // // @Column(nullable = false) // private BigDecimal balance; // // public User getUser() { // return user; // } // public void setUser(User user) { // this.user = user; // } // public BigDecimal getBalance() { // return balance; // } // public void setBalance(BigDecimal balance) { // this.balance = balance; // } // // // }
import java.util.List; import com.coverity.security.pie.example.model.Account; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional;
package com.coverity.security.pie.example.service; @Service public class AccountDao extends AbstractDao {
// Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/model/Account.java // @Entity // public class Account { // // @Id @GeneratedValue // private Long id; // // @ManyToOne(optional = false) // private User user; // // @Column(nullable = false) // private BigDecimal balance; // // public User getUser() { // return user; // } // public void setUser(User user) { // this.user = user; // } // public BigDecimal getBalance() { // return balance; // } // public void setBalance(BigDecimal balance) { // this.balance = balance; // } // // // } // Path: examples/spring-security/src/main/java/com/coverity/security/pie/example/service/AccountDao.java import java.util.List; import com.coverity.security.pie.example.model.Account; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; package com.coverity.security.pie.example.service; @Service public class AccountDao extends AbstractDao {
public Account getAccount(String username) {
coverity/pie
pie-maven-plugin/src/main/java/com/coverity/security/pie/core/BuildPolicyMojo.java
// Path: pie-core/src/main/java/com/coverity/security/pie/web/PieAdminFilter.java // public class PieAdminFilter implements Filter { // // public static final String ADMIN_FILTER_URI = "/c0bd580ddcb4666b1PIEec61812f3cdf305"; // // private final PieInitializer pieInitializer; // // public PieAdminFilter(PieInitializer pieInitializer) { // this.pieInitializer = pieInitializer; // } // // @Override // public void init(FilterConfig filterConfig) throws ServletException { // } // // @Override // public void doFilter(ServletRequest request, ServletResponse response, // FilterChain chain) throws IOException, ServletException { // if (request instanceof HttpServletRequest) { // HttpServletRequest httpServletRequest = (HttpServletRequest)request; // String path = null; // if (httpServletRequest.getRequestURI().length() >= httpServletRequest.getContextPath().length()) { // path = httpServletRequest.getRequestURI().substring(httpServletRequest.getContextPath().length()); // } // if (ADMIN_FILTER_URI.equals(path)) { // // PolicyEnforcer policyEnforcer = pieInitializer.getPolicyEnforcer(httpServletRequest.getParameter("policyEnforcer")); // String startTimeStr = httpServletRequest.getParameter("startTime"); // Long startTime = (startTimeStr == null ? null : Long.parseLong(startTimeStr)); // // if (policyEnforcer != null) { // PrintWriter writer = response.getWriter(); // writer.write("=== PIE REPORT ===\n"); // // String[][] violations; // if (startTime == null) { // violations = policyEnforcer.getPolicy().getViolations(); // } else { // violations = policyEnforcer.getPolicy().getViolations(startTime); // } // // for (String[] violation : violations) { // if (violation.length > 0) { // writer.write(violation[0]); // } // for (int i = 1; i < violation.length; i++) { // writer.write("\t"); // if (violation[i] != null) { // writer.write(violation[i]); // } // } // writer.write("\n"); // } // // writer.close(); // return; // } // // } // } // // chain.doFilter(request, response); // } // // @Override // public void destroy() { // } // // }
import java.io.*; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; import java.net.URLClassLoader; import java.nio.charset.StandardCharsets; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.List; import com.coverity.security.pie.web.PieAdminFilter; import org.apache.commons.io.IOUtils; import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.utils.URIBuilder; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.sonatype.aether.RepositorySystemSession;
throw new RuntimeException(e); } PolicyConfig policyConfig = new PolicyConfig(policy.getName(), pieConfig); if (!policyConfig.isEnabled()) { continue; } policy.setPolicyConfig(policyConfig); getLog().info("Creating policy for " + policy.getName()); final URL policyUrl = policyConfig.getPolicyFile(); if (!policyUrl.getProtocol().equals("file")) { throw new MojoFailureException("Cannot update a non-file policy: " + policyUrl.toString()); } final File policyFile = new File(policyUrl.getPath()); if (policyFile.exists()) { Reader fr = null; try { fr = new InputStreamReader(new FileInputStream(policyFile), StandardCharsets.UTF_8); policy.parsePolicy(fr); } catch (IOException e) { throw new MojoExecutionException("Could not parse policy file: " + policyConfig.getPolicyFile().toString()); } finally { IOUtils.closeQuietly(fr); } } URIBuilder uriBuilder; try {
// Path: pie-core/src/main/java/com/coverity/security/pie/web/PieAdminFilter.java // public class PieAdminFilter implements Filter { // // public static final String ADMIN_FILTER_URI = "/c0bd580ddcb4666b1PIEec61812f3cdf305"; // // private final PieInitializer pieInitializer; // // public PieAdminFilter(PieInitializer pieInitializer) { // this.pieInitializer = pieInitializer; // } // // @Override // public void init(FilterConfig filterConfig) throws ServletException { // } // // @Override // public void doFilter(ServletRequest request, ServletResponse response, // FilterChain chain) throws IOException, ServletException { // if (request instanceof HttpServletRequest) { // HttpServletRequest httpServletRequest = (HttpServletRequest)request; // String path = null; // if (httpServletRequest.getRequestURI().length() >= httpServletRequest.getContextPath().length()) { // path = httpServletRequest.getRequestURI().substring(httpServletRequest.getContextPath().length()); // } // if (ADMIN_FILTER_URI.equals(path)) { // // PolicyEnforcer policyEnforcer = pieInitializer.getPolicyEnforcer(httpServletRequest.getParameter("policyEnforcer")); // String startTimeStr = httpServletRequest.getParameter("startTime"); // Long startTime = (startTimeStr == null ? null : Long.parseLong(startTimeStr)); // // if (policyEnforcer != null) { // PrintWriter writer = response.getWriter(); // writer.write("=== PIE REPORT ===\n"); // // String[][] violations; // if (startTime == null) { // violations = policyEnforcer.getPolicy().getViolations(); // } else { // violations = policyEnforcer.getPolicy().getViolations(startTime); // } // // for (String[] violation : violations) { // if (violation.length > 0) { // writer.write(violation[0]); // } // for (int i = 1; i < violation.length; i++) { // writer.write("\t"); // if (violation[i] != null) { // writer.write(violation[i]); // } // } // writer.write("\n"); // } // // writer.close(); // return; // } // // } // } // // chain.doFilter(request, response); // } // // @Override // public void destroy() { // } // // } // Path: pie-maven-plugin/src/main/java/com/coverity/security/pie/core/BuildPolicyMojo.java import java.io.*; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; import java.net.URLClassLoader; import java.nio.charset.StandardCharsets; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.List; import com.coverity.security.pie.web.PieAdminFilter; import org.apache.commons.io.IOUtils; import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.utils.URIBuilder; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.sonatype.aether.RepositorySystemSession; throw new RuntimeException(e); } PolicyConfig policyConfig = new PolicyConfig(policy.getName(), pieConfig); if (!policyConfig.isEnabled()) { continue; } policy.setPolicyConfig(policyConfig); getLog().info("Creating policy for " + policy.getName()); final URL policyUrl = policyConfig.getPolicyFile(); if (!policyUrl.getProtocol().equals("file")) { throw new MojoFailureException("Cannot update a non-file policy: " + policyUrl.toString()); } final File policyFile = new File(policyUrl.getPath()); if (policyFile.exists()) { Reader fr = null; try { fr = new InputStreamReader(new FileInputStream(policyFile), StandardCharsets.UTF_8); policy.parsePolicy(fr); } catch (IOException e) { throw new MojoExecutionException("Could not parse policy file: " + policyConfig.getPolicyFile().toString()); } finally { IOUtils.closeQuietly(fr); } } URIBuilder uriBuilder; try {
uriBuilder = new URIBuilder(serverUrl.toString() + PieAdminFilter.ADMIN_FILTER_URI);
coverity/pie
pie-sm/src/main/java/com/coverity/security/pie/policy/securitymanager/CsvActionCollapser.java
// Path: pie-core/src/main/java/com/coverity/security/pie/core/StringCollapser.java // public interface StringCollapser { // /** // * Collapses a security policy according to the concrete implementation's rules. It takes a map from facts to their // * children, and returns a collapsed version of that map. For example, given the map: // * { // * A => {'X', 'Y'}, // * B => {'Z'} // * } // * // * If the implementation determines that the facts A and B should be collapsed to fact C, then this would return // * { // * C => {'X', 'Y', 'Z'} // * } // * // * @param input A map from facts to a collection of child facts. // * @param <T> The type of the child facts; irrelevant to the internal procedure of collapsing. // * @return The collapsed map of facts to their children. // */ // public <T> Map<String, Collection<T>> collapse(Map<String, Collection<T>> input); // } // // Path: pie-core/src/main/java/com/coverity/security/pie/util/StringUtil.java // public class StringUtil { // public static String join(String s, String[] arr, int off, int end) { // if (off < 0 || end > arr.length) { // throw new IllegalArgumentException("Invalid indices"); // } // if (end <= off) { // return ""; // } // // StringBuilder sb = new StringBuilder(); // for (int i = off; i < end-1; i++) { // sb.append(arr[i]).append(s); // } // sb.append(arr[end-1]); // return sb.toString(); // } // // public static String join(String s, List<String> strings) { // if (strings.size() == 0) { // return ""; // } // StringBuilder sb = new StringBuilder(); // for (int i = 0; i < strings.size()-1; i++) { // sb.append(strings.get(i)).append(s); // } // sb.append(strings.get(strings.size()-1)); // return sb.toString(); // } // // // public static String join(String s, String ... strings) { // if (strings.length == 0) { // return ""; // } // StringBuilder sb = new StringBuilder(); // for (int i = 0; i < strings.length-1; i++) { // sb.append(strings[i]).append(s); // } // sb.append(strings[strings.length-1]); // return sb.toString(); // } // }
import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import com.coverity.security.pie.core.StringCollapser; import com.coverity.security.pie.util.StringUtil;
package com.coverity.security.pie.policy.securitymanager; /** * A collapser which always collapses all facts into a single fact with comma-separated values (alphabetically ordered). */ public class CsvActionCollapser implements StringCollapser { private static final CsvActionCollapser instance = new CsvActionCollapser(); private CsvActionCollapser() { } public static CsvActionCollapser getInstance() { return instance; } @Override public <T> Map<String, Collection<T>> collapse(Map<String, Collection<T>> input) { List<String> actions = new ArrayList<String>(); for (String key : input.keySet()) { String[] keyActions = key.split(","); for (String action : keyActions) { if (!actions.contains(action)) { actions.add(action); } } } Collections.sort(actions);
// Path: pie-core/src/main/java/com/coverity/security/pie/core/StringCollapser.java // public interface StringCollapser { // /** // * Collapses a security policy according to the concrete implementation's rules. It takes a map from facts to their // * children, and returns a collapsed version of that map. For example, given the map: // * { // * A => {'X', 'Y'}, // * B => {'Z'} // * } // * // * If the implementation determines that the facts A and B should be collapsed to fact C, then this would return // * { // * C => {'X', 'Y', 'Z'} // * } // * // * @param input A map from facts to a collection of child facts. // * @param <T> The type of the child facts; irrelevant to the internal procedure of collapsing. // * @return The collapsed map of facts to their children. // */ // public <T> Map<String, Collection<T>> collapse(Map<String, Collection<T>> input); // } // // Path: pie-core/src/main/java/com/coverity/security/pie/util/StringUtil.java // public class StringUtil { // public static String join(String s, String[] arr, int off, int end) { // if (off < 0 || end > arr.length) { // throw new IllegalArgumentException("Invalid indices"); // } // if (end <= off) { // return ""; // } // // StringBuilder sb = new StringBuilder(); // for (int i = off; i < end-1; i++) { // sb.append(arr[i]).append(s); // } // sb.append(arr[end-1]); // return sb.toString(); // } // // public static String join(String s, List<String> strings) { // if (strings.size() == 0) { // return ""; // } // StringBuilder sb = new StringBuilder(); // for (int i = 0; i < strings.size()-1; i++) { // sb.append(strings.get(i)).append(s); // } // sb.append(strings.get(strings.size()-1)); // return sb.toString(); // } // // // public static String join(String s, String ... strings) { // if (strings.length == 0) { // return ""; // } // StringBuilder sb = new StringBuilder(); // for (int i = 0; i < strings.length-1; i++) { // sb.append(strings[i]).append(s); // } // sb.append(strings[strings.length-1]); // return sb.toString(); // } // } // Path: pie-sm/src/main/java/com/coverity/security/pie/policy/securitymanager/CsvActionCollapser.java import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import com.coverity.security.pie.core.StringCollapser; import com.coverity.security.pie.util.StringUtil; package com.coverity.security.pie.policy.securitymanager; /** * A collapser which always collapses all facts into a single fact with comma-separated values (alphabetically ordered). */ public class CsvActionCollapser implements StringCollapser { private static final CsvActionCollapser instance = new CsvActionCollapser(); private CsvActionCollapser() { } public static CsvActionCollapser getInstance() { return instance; } @Override public <T> Map<String, Collection<T>> collapse(Map<String, Collection<T>> input) { List<String> actions = new ArrayList<String>(); for (String key : input.keySet()) { String[] keyActions = key.split(","); for (String action : keyActions) { if (!actions.contains(action)) { actions.add(action); } } } Collections.sort(actions);
String newActions = StringUtil.join(",", actions);
coverity/pie
pie-core/src/main/java/com/coverity/security/pie/web/PieAdminFilter.java
// Path: pie-core/src/main/java/com/coverity/security/pie/core/PolicyEnforcer.java // public interface PolicyEnforcer { // // public Policy getPolicy(); // public PolicyConfig getPolicyConfig(); // // public void init(PieConfig pieConfig); // // /** // * Apply the policy to the servlet context being initialized. This enforcer should configure // * itself to both apply its policy to permission requests and keep an internal record of any // * policy violations. // * // * @param cx The servlet context currently being initialized. // */ // public void applyPolicy(ServletContext cx); // // /** // * The ServletContext to which this policy is applied is shutting down. The enforcer // * should do any cleanup it needs. // */ // public void shutdown(); // // }
import java.io.IOException; import java.io.PrintWriter; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import com.coverity.security.pie.core.PolicyEnforcer;
package com.coverity.security.pie.web; /** * A servlet filter which provides an endpoint to retrieve policy violations. At this point its intended use is to * facilitate the Maven plugin. */ public class PieAdminFilter implements Filter { public static final String ADMIN_FILTER_URI = "/c0bd580ddcb4666b1PIEec61812f3cdf305"; private final PieInitializer pieInitializer; public PieAdminFilter(PieInitializer pieInitializer) { this.pieInitializer = pieInitializer; } @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest) { HttpServletRequest httpServletRequest = (HttpServletRequest)request; String path = null; if (httpServletRequest.getRequestURI().length() >= httpServletRequest.getContextPath().length()) { path = httpServletRequest.getRequestURI().substring(httpServletRequest.getContextPath().length()); } if (ADMIN_FILTER_URI.equals(path)) {
// Path: pie-core/src/main/java/com/coverity/security/pie/core/PolicyEnforcer.java // public interface PolicyEnforcer { // // public Policy getPolicy(); // public PolicyConfig getPolicyConfig(); // // public void init(PieConfig pieConfig); // // /** // * Apply the policy to the servlet context being initialized. This enforcer should configure // * itself to both apply its policy to permission requests and keep an internal record of any // * policy violations. // * // * @param cx The servlet context currently being initialized. // */ // public void applyPolicy(ServletContext cx); // // /** // * The ServletContext to which this policy is applied is shutting down. The enforcer // * should do any cleanup it needs. // */ // public void shutdown(); // // } // Path: pie-core/src/main/java/com/coverity/security/pie/web/PieAdminFilter.java import java.io.IOException; import java.io.PrintWriter; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import com.coverity.security.pie.core.PolicyEnforcer; package com.coverity.security.pie.web; /** * A servlet filter which provides an endpoint to retrieve policy violations. At this point its intended use is to * facilitate the Maven plugin. */ public class PieAdminFilter implements Filter { public static final String ADMIN_FILTER_URI = "/c0bd580ddcb4666b1PIEec61812f3cdf305"; private final PieInitializer pieInitializer; public PieAdminFilter(PieInitializer pieInitializer) { this.pieInitializer = pieInitializer; } @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest) { HttpServletRequest httpServletRequest = (HttpServletRequest)request; String path = null; if (httpServletRequest.getRequestURI().length() >= httpServletRequest.getContextPath().length()) { path = httpServletRequest.getRequestURI().substring(httpServletRequest.getContextPath().length()); } if (ADMIN_FILTER_URI.equals(path)) {
PolicyEnforcer policyEnforcer = pieInitializer.getPolicyEnforcer(httpServletRequest.getParameter("policyEnforcer"));
coverity/pie
pie-csp/src/test/java/com/coverity/security/pie/policy/csp/CspEnforcementFilterTest.java
// Path: pie-core/src/main/java/com/coverity/security/pie/core/PolicyConfig.java // public class PolicyConfig { // private final String name; // private final PieConfig pieConfig; // // public PolicyConfig(String name, PieConfig pieConfig) { // this.name = name; // this.pieConfig = pieConfig; // } // // public boolean isEnabled() { // return getBoolean("isEnabled", true); // } // // public boolean isReportOnlyMode() { // return getBoolean("isReportOnlyMode", true); // } // // public boolean isCollapseEnabled() { // return getBoolean("isCollapseEnabled", true); // } // // public URL getPolicyFile() { // String policyFile = getProperty("policyFile"); // if (policyFile != null) { // try { // return new URL(policyFile); // } catch (MalformedURLException e) { // throw new IllegalStateException("Invalid policy URL: " + policyFile); // } // } // URL resource = this.getClass().getClassLoader().getResource(name + ".policy"); // if (resource != null) { // return resource; // } // String catalinaHome = System.getProperty("catalina.home"); // if (catalinaHome != null) { // try { // return new File(catalinaHome + File.separatorChar + "conf" + File.separatorChar + name + ".policy").toURI().toURL(); // } catch (MalformedURLException e) { // throw new IllegalStateException("Could not build default policy file path."); // } // } // // // Default to file in the CWD // try { // return new File(name + ".policy").toURI().toURL(); // } catch (MalformedURLException e) { // throw new RuntimeException(e); // } // } // // public boolean getBoolean(String prop, boolean defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Boolean.parseBoolean(v); // } // public int getInteger(String prop, int defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Integer.parseInt(v); // } // // // public String getProperty(String name) { // return pieConfig.getProperties().getProperty(this.name + "." + name); // } // }
import com.coverity.security.pie.core.PolicyConfig; import org.testng.annotations.Test; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.ServletInputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; import java.nio.charset.StandardCharsets; import static org.easymock.EasyMock.*;
package com.coverity.security.pie.policy.csp; public class CspEnforcementFilterTest { @Test public void testPolicyAppliedToRequests() throws IOException, ServletException { CspPolicy policy = createMock(CspPolicy.class); expect(policy.getPolicyForUri("/foo/bar")).andReturn("response1").anyTimes(); expect(policy.getPolicyForUri("/fizz/buzz")).andReturn("response2").anyTimes(); expect(policy.getPolicyForUri(anyObject(String.class))).andReturn("defaultResponse").anyTimes();
// Path: pie-core/src/main/java/com/coverity/security/pie/core/PolicyConfig.java // public class PolicyConfig { // private final String name; // private final PieConfig pieConfig; // // public PolicyConfig(String name, PieConfig pieConfig) { // this.name = name; // this.pieConfig = pieConfig; // } // // public boolean isEnabled() { // return getBoolean("isEnabled", true); // } // // public boolean isReportOnlyMode() { // return getBoolean("isReportOnlyMode", true); // } // // public boolean isCollapseEnabled() { // return getBoolean("isCollapseEnabled", true); // } // // public URL getPolicyFile() { // String policyFile = getProperty("policyFile"); // if (policyFile != null) { // try { // return new URL(policyFile); // } catch (MalformedURLException e) { // throw new IllegalStateException("Invalid policy URL: " + policyFile); // } // } // URL resource = this.getClass().getClassLoader().getResource(name + ".policy"); // if (resource != null) { // return resource; // } // String catalinaHome = System.getProperty("catalina.home"); // if (catalinaHome != null) { // try { // return new File(catalinaHome + File.separatorChar + "conf" + File.separatorChar + name + ".policy").toURI().toURL(); // } catch (MalformedURLException e) { // throw new IllegalStateException("Could not build default policy file path."); // } // } // // // Default to file in the CWD // try { // return new File(name + ".policy").toURI().toURL(); // } catch (MalformedURLException e) { // throw new RuntimeException(e); // } // } // // public boolean getBoolean(String prop, boolean defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Boolean.parseBoolean(v); // } // public int getInteger(String prop, int defaultValue) { // String v = getProperty(prop); // if (v == null) { // return defaultValue; // } // return Integer.parseInt(v); // } // // // public String getProperty(String name) { // return pieConfig.getProperties().getProperty(this.name + "." + name); // } // } // Path: pie-csp/src/test/java/com/coverity/security/pie/policy/csp/CspEnforcementFilterTest.java import com.coverity.security.pie.core.PolicyConfig; import org.testng.annotations.Test; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.ServletInputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; import java.nio.charset.StandardCharsets; import static org.easymock.EasyMock.*; package com.coverity.security.pie.policy.csp; public class CspEnforcementFilterTest { @Test public void testPolicyAppliedToRequests() throws IOException, ServletException { CspPolicy policy = createMock(CspPolicy.class); expect(policy.getPolicyForUri("/foo/bar")).andReturn("response1").anyTimes(); expect(policy.getPolicyForUri("/fizz/buzz")).andReturn("response2").anyTimes(); expect(policy.getPolicyForUri(anyObject(String.class))).andReturn("defaultResponse").anyTimes();
PolicyConfig policyConfig = createMock(PolicyConfig.class);
coverity/pie
pie-core/src/main/java/com/coverity/security/pie/util/collapser/FilePathCollapser.java
// Path: pie-core/src/main/java/com/coverity/security/pie/core/StringCollapser.java // public interface StringCollapser { // /** // * Collapses a security policy according to the concrete implementation's rules. It takes a map from facts to their // * children, and returns a collapsed version of that map. For example, given the map: // * { // * A => {'X', 'Y'}, // * B => {'Z'} // * } // * // * If the implementation determines that the facts A and B should be collapsed to fact C, then this would return // * { // * C => {'X', 'Y', 'Z'} // * } // * // * @param input A map from facts to a collection of child facts. // * @param <T> The type of the child facts; irrelevant to the internal procedure of collapsing. // * @return The collapsed map of facts to their children. // */ // public <T> Map<String, Collection<T>> collapse(Map<String, Collection<T>> input); // } // // Path: pie-core/src/main/java/com/coverity/security/pie/util/StringUtil.java // public class StringUtil { // public static String join(String s, String[] arr, int off, int end) { // if (off < 0 || end > arr.length) { // throw new IllegalArgumentException("Invalid indices"); // } // if (end <= off) { // return ""; // } // // StringBuilder sb = new StringBuilder(); // for (int i = off; i < end-1; i++) { // sb.append(arr[i]).append(s); // } // sb.append(arr[end-1]); // return sb.toString(); // } // // public static String join(String s, List<String> strings) { // if (strings.size() == 0) { // return ""; // } // StringBuilder sb = new StringBuilder(); // for (int i = 0; i < strings.size()-1; i++) { // sb.append(strings.get(i)).append(s); // } // sb.append(strings.get(strings.size()-1)); // return sb.toString(); // } // // // public static String join(String s, String ... strings) { // if (strings.length == 0) { // return ""; // } // StringBuilder sb = new StringBuilder(); // for (int i = 0; i < strings.length-1; i++) { // sb.append(strings[i]).append(s); // } // sb.append(strings[strings.length-1]); // return sb.toString(); // } // }
import java.util.Collection; import java.util.HashMap; import java.util.Map; import com.coverity.security.pie.core.StringCollapser; import com.coverity.security.pie.util.StringUtil;
package com.coverity.security.pie.util.collapser; /** * An implementation of the AbstractPathCollapser which collapses paths according to ant-style path matching; i.e. * /a/b/* matches everything in the /a/b directory, whereas /a/b/- matches all descendents of /a/b */ public class FilePathCollapser extends AbstractPathCollapser implements StringCollapser { public FilePathCollapser(int collapseThreshold) { super("*", "-", collapseThreshold, 0); } @Override public <T> Map<String, Collection<T>> collapse(Map<String, Collection<T>> input) { Map<PathName, Collection<T>> inputMap = new HashMap<PathName, Collection<T>>(input.size()); for (Map.Entry<String, Collection<T>> fileEntry : input.entrySet()) { inputMap.put(new PathName(fileEntry.getKey().split("/"), null), fileEntry.getValue()); } Map<PathName, Collection<T>> outputMap = collapsePaths(inputMap); Map<String, Collection<T>> output = new HashMap<String, Collection<T>>(outputMap.size()); for (Map.Entry<PathName, Collection<T>> pathEntry : outputMap.entrySet()) {
// Path: pie-core/src/main/java/com/coverity/security/pie/core/StringCollapser.java // public interface StringCollapser { // /** // * Collapses a security policy according to the concrete implementation's rules. It takes a map from facts to their // * children, and returns a collapsed version of that map. For example, given the map: // * { // * A => {'X', 'Y'}, // * B => {'Z'} // * } // * // * If the implementation determines that the facts A and B should be collapsed to fact C, then this would return // * { // * C => {'X', 'Y', 'Z'} // * } // * // * @param input A map from facts to a collection of child facts. // * @param <T> The type of the child facts; irrelevant to the internal procedure of collapsing. // * @return The collapsed map of facts to their children. // */ // public <T> Map<String, Collection<T>> collapse(Map<String, Collection<T>> input); // } // // Path: pie-core/src/main/java/com/coverity/security/pie/util/StringUtil.java // public class StringUtil { // public static String join(String s, String[] arr, int off, int end) { // if (off < 0 || end > arr.length) { // throw new IllegalArgumentException("Invalid indices"); // } // if (end <= off) { // return ""; // } // // StringBuilder sb = new StringBuilder(); // for (int i = off; i < end-1; i++) { // sb.append(arr[i]).append(s); // } // sb.append(arr[end-1]); // return sb.toString(); // } // // public static String join(String s, List<String> strings) { // if (strings.size() == 0) { // return ""; // } // StringBuilder sb = new StringBuilder(); // for (int i = 0; i < strings.size()-1; i++) { // sb.append(strings.get(i)).append(s); // } // sb.append(strings.get(strings.size()-1)); // return sb.toString(); // } // // // public static String join(String s, String ... strings) { // if (strings.length == 0) { // return ""; // } // StringBuilder sb = new StringBuilder(); // for (int i = 0; i < strings.length-1; i++) { // sb.append(strings[i]).append(s); // } // sb.append(strings[strings.length-1]); // return sb.toString(); // } // } // Path: pie-core/src/main/java/com/coverity/security/pie/util/collapser/FilePathCollapser.java import java.util.Collection; import java.util.HashMap; import java.util.Map; import com.coverity.security.pie.core.StringCollapser; import com.coverity.security.pie.util.StringUtil; package com.coverity.security.pie.util.collapser; /** * An implementation of the AbstractPathCollapser which collapses paths according to ant-style path matching; i.e. * /a/b/* matches everything in the /a/b directory, whereas /a/b/- matches all descendents of /a/b */ public class FilePathCollapser extends AbstractPathCollapser implements StringCollapser { public FilePathCollapser(int collapseThreshold) { super("*", "-", collapseThreshold, 0); } @Override public <T> Map<String, Collection<T>> collapse(Map<String, Collection<T>> input) { Map<PathName, Collection<T>> inputMap = new HashMap<PathName, Collection<T>>(input.size()); for (Map.Entry<String, Collection<T>> fileEntry : input.entrySet()) { inputMap.put(new PathName(fileEntry.getKey().split("/"), null), fileEntry.getValue()); } Map<PathName, Collection<T>> outputMap = collapsePaths(inputMap); Map<String, Collection<T>> output = new HashMap<String, Collection<T>>(outputMap.size()); for (Map.Entry<PathName, Collection<T>> pathEntry : outputMap.entrySet()) {
output.put(StringUtil.join("/", pathEntry.getKey().getPathComponents()), pathEntry.getValue());
coverity/pie
pie-core/src/main/java/com/coverity/security/pie/core/PieConfig.java
// Path: pie-core/src/main/java/com/coverity/security/pie/util/IOUtil.java // public class IOUtil { // public static void closeSilently(Closeable closeable) { // if (closeable != null) { // try { // closeable.close(); // } catch (IOException e) { // // Do nothing // } // } // } // // public static String readFile(File file) throws IOException { // return toString(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8)); // } // public static String readFile(String file) throws IOException { // return toString(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8)); // } // public static String readFile(URL file) throws IOException { // return toString(file.openStream()); // } // // public static String toString(InputStream is) throws IOException { // try { // return toString(new InputStreamReader(is, StandardCharsets.UTF_8)); // } finally { // closeSilently(is); // } // } // public static String toString(Reader reader) throws IOException { // StringBuilder sb = new StringBuilder(); // try { // char buffer[] = new char[4096]; // int n; // while ((n = reader.read(buffer)) > 0) { // sb.append(buffer, 0, n); // } // reader.close(); // } catch (IOException e) { // closeSilently(reader); // throw e; // } // return sb.toString(); // } // // // public static void writeFile(File file, String content) throws IOException { // writeFile(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8), content); // } // private static void writeFile(Writer fw, String content) throws IOException { // try { // fw.write(content); // fw.close(); // } catch (IOException e) { // closeSilently(fw); // throw e; // } // } // // }
import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.util.Properties; import com.coverity.security.pie.util.IOUtil;
package com.coverity.security.pie.core; /** * Configuration for PIE. This abstracts reading in the pieConfig.properties file and returning configuration * directives. */ public class PieConfig { private final Properties properties = new Properties(); public PieConfig() { loadProps(this.getClass().getClassLoader().getResource("pieConfig.default.properties")); File propFile = new File("pieConfig.properties"); if (propFile.exists()) { try { loadProps(propFile.toURI().toURL()); } catch (MalformedURLException e) { throw new RuntimeException(e); } } else { loadProps(this.getClass().getClassLoader().getResource("pieConfig.properties")); } } public PieConfig(URL propertiesUrl) { loadProps(this.getClass().getClassLoader().getResource("pieConfig.default.properties")); loadProps(propertiesUrl); } private void loadProps(URL propertiesUrl) { if (propertiesUrl != null) { InputStream is = null; try { is = propertiesUrl.openStream(); if (is != null) { properties.load(is); is.close(); } } catch (IOException e) {
// Path: pie-core/src/main/java/com/coverity/security/pie/util/IOUtil.java // public class IOUtil { // public static void closeSilently(Closeable closeable) { // if (closeable != null) { // try { // closeable.close(); // } catch (IOException e) { // // Do nothing // } // } // } // // public static String readFile(File file) throws IOException { // return toString(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8)); // } // public static String readFile(String file) throws IOException { // return toString(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8)); // } // public static String readFile(URL file) throws IOException { // return toString(file.openStream()); // } // // public static String toString(InputStream is) throws IOException { // try { // return toString(new InputStreamReader(is, StandardCharsets.UTF_8)); // } finally { // closeSilently(is); // } // } // public static String toString(Reader reader) throws IOException { // StringBuilder sb = new StringBuilder(); // try { // char buffer[] = new char[4096]; // int n; // while ((n = reader.read(buffer)) > 0) { // sb.append(buffer, 0, n); // } // reader.close(); // } catch (IOException e) { // closeSilently(reader); // throw e; // } // return sb.toString(); // } // // // public static void writeFile(File file, String content) throws IOException { // writeFile(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8), content); // } // private static void writeFile(Writer fw, String content) throws IOException { // try { // fw.write(content); // fw.close(); // } catch (IOException e) { // closeSilently(fw); // throw e; // } // } // // } // Path: pie-core/src/main/java/com/coverity/security/pie/core/PieConfig.java import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.util.Properties; import com.coverity.security.pie.util.IOUtil; package com.coverity.security.pie.core; /** * Configuration for PIE. This abstracts reading in the pieConfig.properties file and returning configuration * directives. */ public class PieConfig { private final Properties properties = new Properties(); public PieConfig() { loadProps(this.getClass().getClassLoader().getResource("pieConfig.default.properties")); File propFile = new File("pieConfig.properties"); if (propFile.exists()) { try { loadProps(propFile.toURI().toURL()); } catch (MalformedURLException e) { throw new RuntimeException(e); } } else { loadProps(this.getClass().getClassLoader().getResource("pieConfig.properties")); } } public PieConfig(URL propertiesUrl) { loadProps(this.getClass().getClassLoader().getResource("pieConfig.default.properties")); loadProps(propertiesUrl); } private void loadProps(URL propertiesUrl) { if (propertiesUrl != null) { InputStream is = null; try { is = propertiesUrl.openStream(); if (is != null) { properties.load(is); is.close(); } } catch (IOException e) {
IOUtil.closeSilently(is);
coverity/pie
pie-core/src/test/java/com/coverity/security/pie/core/PolicyTest.java
// Path: pie-core/src/main/java/com/coverity/security/pie/util/IOUtil.java // public class IOUtil { // public static void closeSilently(Closeable closeable) { // if (closeable != null) { // try { // closeable.close(); // } catch (IOException e) { // // Do nothing // } // } // } // // public static String readFile(File file) throws IOException { // return toString(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8)); // } // public static String readFile(String file) throws IOException { // return toString(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8)); // } // public static String readFile(URL file) throws IOException { // return toString(file.openStream()); // } // // public static String toString(InputStream is) throws IOException { // try { // return toString(new InputStreamReader(is, StandardCharsets.UTF_8)); // } finally { // closeSilently(is); // } // } // public static String toString(Reader reader) throws IOException { // StringBuilder sb = new StringBuilder(); // try { // char buffer[] = new char[4096]; // int n; // while ((n = reader.read(buffer)) > 0) { // sb.append(buffer, 0, n); // } // reader.close(); // } catch (IOException e) { // closeSilently(reader); // throw e; // } // return sb.toString(); // } // // // public static void writeFile(File file, String content) throws IOException { // writeFile(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8), content); // } // private static void writeFile(Writer fw, String content) throws IOException { // try { // fw.write(content); // fw.close(); // } catch (IOException e) { // closeSilently(fw); // throw e; // } // } // // }
import static org.testng.Assert.assertEquals; import java.io.*; import java.nio.charset.StandardCharsets; import java.util.*; import java.util.concurrent.*; import org.testng.Assert; import org.testng.annotations.Test; import com.coverity.security.pie.util.IOUtil;
package com.coverity.security.pie.core; public class PolicyTest { @Test public void testEmptyPolicy() throws IOException { File file = File.createTempFile("test-policy", null); Policy policy = new SimplePolicy(); policy.writePolicy(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8));
// Path: pie-core/src/main/java/com/coverity/security/pie/util/IOUtil.java // public class IOUtil { // public static void closeSilently(Closeable closeable) { // if (closeable != null) { // try { // closeable.close(); // } catch (IOException e) { // // Do nothing // } // } // } // // public static String readFile(File file) throws IOException { // return toString(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8)); // } // public static String readFile(String file) throws IOException { // return toString(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8)); // } // public static String readFile(URL file) throws IOException { // return toString(file.openStream()); // } // // public static String toString(InputStream is) throws IOException { // try { // return toString(new InputStreamReader(is, StandardCharsets.UTF_8)); // } finally { // closeSilently(is); // } // } // public static String toString(Reader reader) throws IOException { // StringBuilder sb = new StringBuilder(); // try { // char buffer[] = new char[4096]; // int n; // while ((n = reader.read(buffer)) > 0) { // sb.append(buffer, 0, n); // } // reader.close(); // } catch (IOException e) { // closeSilently(reader); // throw e; // } // return sb.toString(); // } // // // public static void writeFile(File file, String content) throws IOException { // writeFile(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8), content); // } // private static void writeFile(Writer fw, String content) throws IOException { // try { // fw.write(content); // fw.close(); // } catch (IOException e) { // closeSilently(fw); // throw e; // } // } // // } // Path: pie-core/src/test/java/com/coverity/security/pie/core/PolicyTest.java import static org.testng.Assert.assertEquals; import java.io.*; import java.nio.charset.StandardCharsets; import java.util.*; import java.util.concurrent.*; import org.testng.Assert; import org.testng.annotations.Test; import com.coverity.security.pie.util.IOUtil; package com.coverity.security.pie.core; public class PolicyTest { @Test public void testEmptyPolicy() throws IOException { File file = File.createTempFile("test-policy", null); Policy policy = new SimplePolicy(); policy.writePolicy(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8));
assertEquals(IOUtil.readFile(file), "{\n}\n");
nloko/SyncMyPix
src/com/nloko/android/Utils.java
// Path: src/com/nloko/android/Log.java // public final class Log { // // public static boolean debug = false; // // public static void d(String tag, String message) // { // if (debug) { // android.util.Log.d(tag, message); // } // } // // public static void w(String tag, String message) // { // android.util.Log.w(tag, message); // } // // public static void e(String tag, String message) // { // android.util.Log.e(tag, message); // } // // public static void v(String tag, String message) // { // android.util.Log.v(tag, message); // } // // public static void i(String tag, String message) // { // android.util.Log.i(tag, message); // } // }
import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.entity.BufferedHttpEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import android.content.Context; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Matrix; import android.graphics.Rect; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Build; import com.nloko.android.Log;
} ConnectivityManager connMgr=(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo info=connMgr.getActiveNetworkInfo(); return(info!=null && info.isConnected()); } public static String getMd5Hash(byte[] input) { if (input == null) { throw new IllegalArgumentException("input"); } try { MessageDigest md = MessageDigest.getInstance("MD5"); byte[] messageDigest = md.digest(input); BigInteger number = new BigInteger(1,messageDigest); //String md5 = number.toString(16); StringBuffer md5 = new StringBuffer(); md5.append(number.toString(16)); while (md5.length() < 32) { //md5 = "0" + md5; md5.insert(0, "0"); } return md5.toString(); } catch(NoSuchAlgorithmException e) {
// Path: src/com/nloko/android/Log.java // public final class Log { // // public static boolean debug = false; // // public static void d(String tag, String message) // { // if (debug) { // android.util.Log.d(tag, message); // } // } // // public static void w(String tag, String message) // { // android.util.Log.w(tag, message); // } // // public static void e(String tag, String message) // { // android.util.Log.e(tag, message); // } // // public static void v(String tag, String message) // { // android.util.Log.v(tag, message); // } // // public static void i(String tag, String message) // { // android.util.Log.i(tag, message); // } // } // Path: src/com/nloko/android/Utils.java import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.entity.BufferedHttpEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import android.content.Context; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Matrix; import android.graphics.Rect; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Build; import com.nloko.android.Log; } ConnectivityManager connMgr=(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo info=connMgr.getActiveNetworkInfo(); return(info!=null && info.isConnected()); } public static String getMd5Hash(byte[] input) { if (input == null) { throw new IllegalArgumentException("input"); } try { MessageDigest md = MessageDigest.getInstance("MD5"); byte[] messageDigest = md.digest(input); BigInteger number = new BigInteger(1,messageDigest); //String md5 = number.toString(16); StringBuffer md5 = new StringBuffer(); md5.append(number.toString(16)); while (md5.length() < 32) { //md5 = "0" + md5; md5.insert(0, "0"); } return md5.toString(); } catch(NoSuchAlgorithmException e) {
Log.e("MD5", e.getMessage());
nloko/SyncMyPix
src/com/nloko/android/syncmypix/contactutils/IContactProxy.java
// Path: src/com/nloko/android/syncmypix/PhoneContact.java // public final class PhoneContact implements Comparable<PhoneContact> { // // public PhoneContact(String id, String name) { // this(id, name, null); // } // // public PhoneContact(String id, String name, String lookup) { // this.id = id; // this.name = name; // this.lookup = lookup; // } // // public String id; // public String name; // public String lookup; // // public int compareTo(PhoneContact another) { // return name.compareTo(another.name); // } // }
import java.io.InputStream; import com.nloko.android.syncmypix.PhoneContact; import android.content.ContentResolver; import android.net.Uri;
// // IContactProxy.java is part of SyncMyPix // // Authors: // Neil Loknath <neil.loknath@gmail.com> // // Copyright (c) 2009 Neil Loknath // // SyncMyPix 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. // // SyncMyPix 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 SyncMyPix. If not, see <http://www.gnu.org/licenses/>. // package com.nloko.android.syncmypix.contactutils; public interface IContactProxy { InputStream getPhoto(ContentResolver cr, String id); boolean isContactUpdatable(ContentResolver cr, String id);
// Path: src/com/nloko/android/syncmypix/PhoneContact.java // public final class PhoneContact implements Comparable<PhoneContact> { // // public PhoneContact(String id, String name) { // this(id, name, null); // } // // public PhoneContact(String id, String name, String lookup) { // this.id = id; // this.name = name; // this.lookup = lookup; // } // // public String id; // public String name; // public String lookup; // // public int compareTo(PhoneContact another) { // return name.compareTo(another.name); // } // } // Path: src/com/nloko/android/syncmypix/contactutils/IContactProxy.java import java.io.InputStream; import com.nloko.android.syncmypix.PhoneContact; import android.content.ContentResolver; import android.net.Uri; // // IContactProxy.java is part of SyncMyPix // // Authors: // Neil Loknath <neil.loknath@gmail.com> // // Copyright (c) 2009 Neil Loknath // // SyncMyPix 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. // // SyncMyPix 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 SyncMyPix. If not, see <http://www.gnu.org/licenses/>. // package com.nloko.android.syncmypix.contactutils; public interface IContactProxy { InputStream getPhoto(ContentResolver cr, String id); boolean isContactUpdatable(ContentResolver cr, String id);
PhoneContact confirmContact(ContentResolver cr, String id, String lookup);
nloko/SyncMyPix
src/com/nloko/android/syncmypix/contactutils/ContactProxy.java
// Path: src/com/nloko/android/syncmypix/PhoneContact.java // public final class PhoneContact implements Comparable<PhoneContact> { // // public PhoneContact(String id, String name) { // this(id, name, null); // } // // public PhoneContact(String id, String name, String lookup) { // this.id = id; // this.name = name; // this.lookup = lookup; // } // // public String id; // public String name; // public String lookup; // // public int compareTo(PhoneContact another) { // return name.compareTo(another.name); // } // }
import android.provider.Contacts.Photos; import java.io.InputStream; import com.nloko.android.syncmypix.PhoneContact; import android.content.ContentResolver; import android.content.ContentValues; import android.net.Uri; import android.provider.Contacts.People;
// // ContactProxy.java is part of SyncMyPix // // Authors: // Neil Loknath <neil.loknath@gmail.com> // // Copyright (c) 2009 Neil Loknath // // SyncMyPix 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. // // SyncMyPix 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 SyncMyPix. If not, see <http://www.gnu.org/licenses/>. // package com.nloko.android.syncmypix.contactutils; public class ContactProxy implements IContactProxy { public InputStream getPhoto(ContentResolver cr, String id) { if (cr == null || id == null) { return null; } Uri contact = Uri.withAppendedPath(People.CONTENT_URI, id); return People.openContactPhotoInputStream(cr, contact); } public boolean isContactUpdatable(ContentResolver cr, String id) { return true; }
// Path: src/com/nloko/android/syncmypix/PhoneContact.java // public final class PhoneContact implements Comparable<PhoneContact> { // // public PhoneContact(String id, String name) { // this(id, name, null); // } // // public PhoneContact(String id, String name, String lookup) { // this.id = id; // this.name = name; // this.lookup = lookup; // } // // public String id; // public String name; // public String lookup; // // public int compareTo(PhoneContact another) { // return name.compareTo(another.name); // } // } // Path: src/com/nloko/android/syncmypix/contactutils/ContactProxy.java import android.provider.Contacts.Photos; import java.io.InputStream; import com.nloko.android.syncmypix.PhoneContact; import android.content.ContentResolver; import android.content.ContentValues; import android.net.Uri; import android.provider.Contacts.People; // // ContactProxy.java is part of SyncMyPix // // Authors: // Neil Loknath <neil.loknath@gmail.com> // // Copyright (c) 2009 Neil Loknath // // SyncMyPix 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. // // SyncMyPix 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 SyncMyPix. If not, see <http://www.gnu.org/licenses/>. // package com.nloko.android.syncmypix.contactutils; public class ContactProxy implements IContactProxy { public InputStream getPhoto(ContentResolver cr, String id) { if (cr == null || id == null) { return null; } Uri contact = Uri.withAppendedPath(People.CONTENT_URI, id); return People.openContactPhotoInputStream(cr, contact); } public boolean isContactUpdatable(ContentResolver cr, String id) { return true; }
public PhoneContact confirmContact(ContentResolver cr, String id, String lookup) {
nloko/SyncMyPix
src/com/nloko/android/syncmypix/views/ConfirmSyncDialog.java
// Path: src/com/nloko/android/syncmypix/SyncMyPixPreferences.java // public final class SyncMyPixPreferences { // // protected Context context; // // public SyncMyPixPreferences(Context context) // { // if (context == null) { // throw new IllegalArgumentException("context"); // } // // this.context = context; // getPreferences(context); // } // // private boolean googleSyncToggledOff; // public boolean isGoogleSyncToggledOff() // { // return googleSyncToggledOff; // } // // private boolean allowGoogleSync; // public boolean getAllowGoogleSync() // { // return allowGoogleSync; // } // // private boolean skipIfExists; // public boolean getSkipIfExists() // { // return skipIfExists; // } // // private boolean skipIfConflict; // public boolean getSkipIfConflict() // { // return skipIfConflict; // } // // private boolean overrideReadOnlyCheck; // public boolean overrideReadOnlyCheck() // { // return overrideReadOnlyCheck; // } // // private boolean maxQuality; // public boolean getMaxQuality() // { // return maxQuality; // } // // private boolean cropSquare; // public boolean getCropSquare() // { // return cropSquare; // } // // private boolean cache; // public boolean getCache() // { // return cache; // } // // private boolean intelliMatch; // public boolean getIntelliMatch() // { // return intelliMatch; // } // // private boolean phoneOnly; // public boolean getPhoneOnly() // { // return phoneOnly; // } // // private String source; // public String getSource() // { // return source; // } // // // private <T extends SyncService> String getSocialNetworkName (Class<T> source) // // { // // try { // // Method m = source.getMethod("getSocialNetworkName"); // // return (String) m.invoke(null); // // // // } catch (SecurityException e) { // // e.printStackTrace(); // // } catch (NoSuchMethodException e) { // // e.printStackTrace(); // // } catch (Exception e) { // // e.printStackTrace(); // // } // // // // return SyncService.getSocialNetworkName(); // // } // // private void getPreferences(Context context) // { // SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); // // //source = getSocialNetworkName(MainActivity.getSyncSource(context)); // // googleSyncToggledOff = prefs.getBoolean("googleSyncToggledOff", false); // skipIfConflict = prefs.getBoolean("skipIfConflict", false); // // maxQuality = true; // allowGoogleSync = true; // // //skipIfExists = prefs.getBoolean("skipIfExists", // // Integer.parseInt(Build.VERSION.SDK) >= Build.VERSION_CODES.ECLAIR ? false : true); // skipIfExists = false; // // overrideReadOnlyCheck = prefs.getBoolean("overrideReadOnlyCheck", true); // cropSquare = prefs.getBoolean("cropSquare", false); // intelliMatch = prefs.getBoolean("intelliMatch", true); // phoneOnly = prefs.getBoolean("phoneOnly", false); // cache = prefs.getBoolean("cache", true); // } // }
import com.nloko.android.syncmypix.SyncMyPixPreferences; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.graphics.Color; import android.widget.TextView;
// // ConfirmSyncDialog.java is part of SyncMyPix // // Authors: // Neil Loknath <neil.loknath@gmail.com> // // Copyright (c) 2009 Neil Loknath // // SyncMyPix 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. // // SyncMyPix 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 SyncMyPix. If not, see <http://www.gnu.org/licenses/>. // package com.nloko.android.syncmypix.views; public final class ConfirmSyncDialog extends AlertDialog { public ConfirmSyncDialog(Context context) { super(context); initialize(context); } private void initialize(Context context) {
// Path: src/com/nloko/android/syncmypix/SyncMyPixPreferences.java // public final class SyncMyPixPreferences { // // protected Context context; // // public SyncMyPixPreferences(Context context) // { // if (context == null) { // throw new IllegalArgumentException("context"); // } // // this.context = context; // getPreferences(context); // } // // private boolean googleSyncToggledOff; // public boolean isGoogleSyncToggledOff() // { // return googleSyncToggledOff; // } // // private boolean allowGoogleSync; // public boolean getAllowGoogleSync() // { // return allowGoogleSync; // } // // private boolean skipIfExists; // public boolean getSkipIfExists() // { // return skipIfExists; // } // // private boolean skipIfConflict; // public boolean getSkipIfConflict() // { // return skipIfConflict; // } // // private boolean overrideReadOnlyCheck; // public boolean overrideReadOnlyCheck() // { // return overrideReadOnlyCheck; // } // // private boolean maxQuality; // public boolean getMaxQuality() // { // return maxQuality; // } // // private boolean cropSquare; // public boolean getCropSquare() // { // return cropSquare; // } // // private boolean cache; // public boolean getCache() // { // return cache; // } // // private boolean intelliMatch; // public boolean getIntelliMatch() // { // return intelliMatch; // } // // private boolean phoneOnly; // public boolean getPhoneOnly() // { // return phoneOnly; // } // // private String source; // public String getSource() // { // return source; // } // // // private <T extends SyncService> String getSocialNetworkName (Class<T> source) // // { // // try { // // Method m = source.getMethod("getSocialNetworkName"); // // return (String) m.invoke(null); // // // // } catch (SecurityException e) { // // e.printStackTrace(); // // } catch (NoSuchMethodException e) { // // e.printStackTrace(); // // } catch (Exception e) { // // e.printStackTrace(); // // } // // // // return SyncService.getSocialNetworkName(); // // } // // private void getPreferences(Context context) // { // SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); // // //source = getSocialNetworkName(MainActivity.getSyncSource(context)); // // googleSyncToggledOff = prefs.getBoolean("googleSyncToggledOff", false); // skipIfConflict = prefs.getBoolean("skipIfConflict", false); // // maxQuality = true; // allowGoogleSync = true; // // //skipIfExists = prefs.getBoolean("skipIfExists", // // Integer.parseInt(Build.VERSION.SDK) >= Build.VERSION_CODES.ECLAIR ? false : true); // skipIfExists = false; // // overrideReadOnlyCheck = prefs.getBoolean("overrideReadOnlyCheck", true); // cropSquare = prefs.getBoolean("cropSquare", false); // intelliMatch = prefs.getBoolean("intelliMatch", true); // phoneOnly = prefs.getBoolean("phoneOnly", false); // cache = prefs.getBoolean("cache", true); // } // } // Path: src/com/nloko/android/syncmypix/views/ConfirmSyncDialog.java import com.nloko.android.syncmypix.SyncMyPixPreferences; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.graphics.Color; import android.widget.TextView; // // ConfirmSyncDialog.java is part of SyncMyPix // // Authors: // Neil Loknath <neil.loknath@gmail.com> // // Copyright (c) 2009 Neil Loknath // // SyncMyPix 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. // // SyncMyPix 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 SyncMyPix. If not, see <http://www.gnu.org/licenses/>. // package com.nloko.android.syncmypix.views; public final class ConfirmSyncDialog extends AlertDialog { public ConfirmSyncDialog(Context context) { super(context); initialize(context); } private void initialize(Context context) {
SyncMyPixPreferences prefs = new SyncMyPixPreferences(context);
nloko/SyncMyPix
src/com/nloko/android/syncmypix/SyncProgressActivity.java
// Path: src/com/nloko/android/Log.java // public final class Log { // // public static boolean debug = false; // // public static void d(String tag, String message) // { // if (debug) { // android.util.Log.d(tag, message); // } // } // // public static void w(String tag, String message) // { // android.util.Log.w(tag, message); // } // // public static void e(String tag, String message) // { // android.util.Log.e(tag, message); // } // // public static void v(String tag, String message) // { // android.util.Log.v(tag, message); // } // // public static void i(String tag, String message) // { // android.util.Log.i(tag, message); // } // } // // Path: src/com/nloko/android/syncmypix/SyncService.java // public enum SyncServiceStatus { // IDLE, // GETTING_FRIENDS, // SYNCING // }
import java.lang.ref.WeakReference; import com.nloko.android.Log; import com.nloko.android.syncmypix.SyncService.SyncServiceStatus; import android.app.Activity; import android.app.Dialog; import android.app.ProgressDialog; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.os.Bundle; import android.os.IBinder; import android.view.View; import android.view.Window; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ImageButton; import android.widget.ImageSwitcher; import android.widget.ProgressBar; import android.widget.TextSwitcher; import android.widget.TextView; import android.widget.Toast;
if (!mSyncServiceBound) { Intent i = new Intent(getApplicationContext(), MainActivity.getSyncSource(getApplicationContext())); mSyncServiceBound = bindService(i, mSyncServiceConn, Context.BIND_AUTO_CREATE); } } @Override protected void onResume() { super.onResume(); mTitleProgress.setVisibility(View.VISIBLE); } @Override protected void onDestroy() { super.onDestroy(); unbindService(mSyncServiceConn); if (mSyncService != null) { SyncService service = mSyncService.get(); if (service != null) { service.unsetListener(); } } mSyncServiceBound = false; mSyncServiceConn = null; } @Override protected void finalize() throws Throwable { super.finalize();
// Path: src/com/nloko/android/Log.java // public final class Log { // // public static boolean debug = false; // // public static void d(String tag, String message) // { // if (debug) { // android.util.Log.d(tag, message); // } // } // // public static void w(String tag, String message) // { // android.util.Log.w(tag, message); // } // // public static void e(String tag, String message) // { // android.util.Log.e(tag, message); // } // // public static void v(String tag, String message) // { // android.util.Log.v(tag, message); // } // // public static void i(String tag, String message) // { // android.util.Log.i(tag, message); // } // } // // Path: src/com/nloko/android/syncmypix/SyncService.java // public enum SyncServiceStatus { // IDLE, // GETTING_FRIENDS, // SYNCING // } // Path: src/com/nloko/android/syncmypix/SyncProgressActivity.java import java.lang.ref.WeakReference; import com.nloko.android.Log; import com.nloko.android.syncmypix.SyncService.SyncServiceStatus; import android.app.Activity; import android.app.Dialog; import android.app.ProgressDialog; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.os.Bundle; import android.os.IBinder; import android.view.View; import android.view.Window; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ImageButton; import android.widget.ImageSwitcher; import android.widget.ProgressBar; import android.widget.TextSwitcher; import android.widget.TextView; import android.widget.Toast; if (!mSyncServiceBound) { Intent i = new Intent(getApplicationContext(), MainActivity.getSyncSource(getApplicationContext())); mSyncServiceBound = bindService(i, mSyncServiceConn, Context.BIND_AUTO_CREATE); } } @Override protected void onResume() { super.onResume(); mTitleProgress.setVisibility(View.VISIBLE); } @Override protected void onDestroy() { super.onDestroy(); unbindService(mSyncServiceConn); if (mSyncService != null) { SyncService service = mSyncService.get(); if (service != null) { service.unsetListener(); } } mSyncServiceBound = false; mSyncServiceConn = null; } @Override protected void finalize() throws Throwable { super.finalize();
Log.d(TAG, "FINALIZED");
nloko/SyncMyPix
src/com/nloko/android/syncmypix/namematcher/NameMatcher2.java
// Path: src/com/nloko/android/Log.java // public final class Log { // // public static boolean debug = false; // // public static void d(String tag, String message) // { // if (debug) { // android.util.Log.d(tag, message); // } // } // // public static void w(String tag, String message) // { // android.util.Log.w(tag, message); // } // // public static void e(String tag, String message) // { // android.util.Log.e(tag, message); // } // // public static void v(String tag, String message) // { // android.util.Log.v(tag, message); // } // // public static void i(String tag, String message) // { // android.util.Log.i(tag, message); // } // } // // Path: src/com/nloko/android/syncmypix/PhoneContact.java // public final class PhoneContact implements Comparable<PhoneContact> { // // public PhoneContact(String id, String name) { // this(id, name, null); // } // // public PhoneContact(String id, String name, String lookup) { // this.id = id; // this.name = name; // this.lookup = lookup; // } // // public String id; // public String name; // public String lookup; // // public int compareTo(PhoneContact another) { // return name.compareTo(another.name); // } // }
import android.database.Cursor; import android.provider.ContactsContract; import java.io.InputStream; import com.nloko.android.Log; import com.nloko.android.syncmypix.PhoneContact; import android.content.Context;
// // NameMatcher.java is part of SyncMyPix // // Authors: // Mike Hearn <mike@plan99.net> // Neil Loknath <neil.loknath@gmail.com> // // Copyright (c) 2009 Mike Hearn // Copyright (c) 2009 Neil Loknath // // SyncMyPix 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. // // SyncMyPix 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 SyncMyPix. If not, see <http://www.gnu.org/licenses/>. // package com.nloko.android.syncmypix.namematcher; public class NameMatcher2 extends NameMatcher { protected final String TAG = "NameMatcher2"; public NameMatcher2(Context context, InputStream diminutives, boolean withPhone) throws Exception { super(context, diminutives, withPhone); } @Override
// Path: src/com/nloko/android/Log.java // public final class Log { // // public static boolean debug = false; // // public static void d(String tag, String message) // { // if (debug) { // android.util.Log.d(tag, message); // } // } // // public static void w(String tag, String message) // { // android.util.Log.w(tag, message); // } // // public static void e(String tag, String message) // { // android.util.Log.e(tag, message); // } // // public static void v(String tag, String message) // { // android.util.Log.v(tag, message); // } // // public static void i(String tag, String message) // { // android.util.Log.i(tag, message); // } // } // // Path: src/com/nloko/android/syncmypix/PhoneContact.java // public final class PhoneContact implements Comparable<PhoneContact> { // // public PhoneContact(String id, String name) { // this(id, name, null); // } // // public PhoneContact(String id, String name, String lookup) { // this.id = id; // this.name = name; // this.lookup = lookup; // } // // public String id; // public String name; // public String lookup; // // public int compareTo(PhoneContact another) { // return name.compareTo(another.name); // } // } // Path: src/com/nloko/android/syncmypix/namematcher/NameMatcher2.java import android.database.Cursor; import android.provider.ContactsContract; import java.io.InputStream; import com.nloko.android.Log; import com.nloko.android.syncmypix.PhoneContact; import android.content.Context; // // NameMatcher.java is part of SyncMyPix // // Authors: // Mike Hearn <mike@plan99.net> // Neil Loknath <neil.loknath@gmail.com> // // Copyright (c) 2009 Mike Hearn // Copyright (c) 2009 Neil Loknath // // SyncMyPix 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. // // SyncMyPix 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 SyncMyPix. If not, see <http://www.gnu.org/licenses/>. // package com.nloko.android.syncmypix.namematcher; public class NameMatcher2 extends NameMatcher { protected final String TAG = "NameMatcher2"; public NameMatcher2(Context context, InputStream diminutives, boolean withPhone) throws Exception { super(context, diminutives, withPhone); } @Override
protected PhoneContact createFromCursor(Cursor cursor) {
nloko/SyncMyPix
src/com/nloko/android/syncmypix/namematcher/NameMatcher2.java
// Path: src/com/nloko/android/Log.java // public final class Log { // // public static boolean debug = false; // // public static void d(String tag, String message) // { // if (debug) { // android.util.Log.d(tag, message); // } // } // // public static void w(String tag, String message) // { // android.util.Log.w(tag, message); // } // // public static void e(String tag, String message) // { // android.util.Log.e(tag, message); // } // // public static void v(String tag, String message) // { // android.util.Log.v(tag, message); // } // // public static void i(String tag, String message) // { // android.util.Log.i(tag, message); // } // } // // Path: src/com/nloko/android/syncmypix/PhoneContact.java // public final class PhoneContact implements Comparable<PhoneContact> { // // public PhoneContact(String id, String name) { // this(id, name, null); // } // // public PhoneContact(String id, String name, String lookup) { // this.id = id; // this.name = name; // this.lookup = lookup; // } // // public String id; // public String name; // public String lookup; // // public int compareTo(PhoneContact another) { // return name.compareTo(another.name); // } // }
import android.database.Cursor; import android.provider.ContactsContract; import java.io.InputStream; import com.nloko.android.Log; import com.nloko.android.syncmypix.PhoneContact; import android.content.Context;
// // NameMatcher.java is part of SyncMyPix // // Authors: // Mike Hearn <mike@plan99.net> // Neil Loknath <neil.loknath@gmail.com> // // Copyright (c) 2009 Mike Hearn // Copyright (c) 2009 Neil Loknath // // SyncMyPix 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. // // SyncMyPix 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 SyncMyPix. If not, see <http://www.gnu.org/licenses/>. // package com.nloko.android.syncmypix.namematcher; public class NameMatcher2 extends NameMatcher { protected final String TAG = "NameMatcher2"; public NameMatcher2(Context context, InputStream diminutives, boolean withPhone) throws Exception { super(context, diminutives, withPhone); } @Override protected PhoneContact createFromCursor(Cursor cursor) { if (cursor == null || cursor.isClosed()) { return null; } String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID)); String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)); String lookup = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
// Path: src/com/nloko/android/Log.java // public final class Log { // // public static boolean debug = false; // // public static void d(String tag, String message) // { // if (debug) { // android.util.Log.d(tag, message); // } // } // // public static void w(String tag, String message) // { // android.util.Log.w(tag, message); // } // // public static void e(String tag, String message) // { // android.util.Log.e(tag, message); // } // // public static void v(String tag, String message) // { // android.util.Log.v(tag, message); // } // // public static void i(String tag, String message) // { // android.util.Log.i(tag, message); // } // } // // Path: src/com/nloko/android/syncmypix/PhoneContact.java // public final class PhoneContact implements Comparable<PhoneContact> { // // public PhoneContact(String id, String name) { // this(id, name, null); // } // // public PhoneContact(String id, String name, String lookup) { // this.id = id; // this.name = name; // this.lookup = lookup; // } // // public String id; // public String name; // public String lookup; // // public int compareTo(PhoneContact another) { // return name.compareTo(another.name); // } // } // Path: src/com/nloko/android/syncmypix/namematcher/NameMatcher2.java import android.database.Cursor; import android.provider.ContactsContract; import java.io.InputStream; import com.nloko.android.Log; import com.nloko.android.syncmypix.PhoneContact; import android.content.Context; // // NameMatcher.java is part of SyncMyPix // // Authors: // Mike Hearn <mike@plan99.net> // Neil Loknath <neil.loknath@gmail.com> // // Copyright (c) 2009 Mike Hearn // Copyright (c) 2009 Neil Loknath // // SyncMyPix 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. // // SyncMyPix 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 SyncMyPix. If not, see <http://www.gnu.org/licenses/>. // package com.nloko.android.syncmypix.namematcher; public class NameMatcher2 extends NameMatcher { protected final String TAG = "NameMatcher2"; public NameMatcher2(Context context, InputStream diminutives, boolean withPhone) throws Exception { super(context, diminutives, withPhone); } @Override protected PhoneContact createFromCursor(Cursor cursor) { if (cursor == null || cursor.isClosed()) { return null; } String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID)); String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)); String lookup = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
Log.d(TAG, "NameMatcher is processing contact " + name + " " + lookup);
nloko/SyncMyPix
src/com/nloko/android/syncmypix/contactutils/ContactUtils.java
// Path: src/com/nloko/android/syncmypix/PhoneContact.java // public final class PhoneContact implements Comparable<PhoneContact> { // // public PhoneContact(String id, String name) { // this(id, name, null); // } // // public PhoneContact(String id, String name, String lookup) { // this.id = id; // this.name = name; // this.lookup = lookup; // } // // public String id; // public String name; // public String lookup; // // public int compareTo(PhoneContact another) { // return name.compareTo(another.name); // } // }
import java.io.InputStream; import com.nloko.android.syncmypix.PhoneContact; import android.content.ContentResolver; import android.net.Uri;
// // ContactUtils.java is part of SyncMyPix // // Authors: // Neil Loknath <neil.loknath@gmail.com> // // Copyright (c) 2009 Neil Loknath // // SyncMyPix 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. // // SyncMyPix 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 SyncMyPix. If not, see <http://www.gnu.org/licenses/>. // package com.nloko.android.syncmypix.contactutils; public final class ContactUtils { private static final String TAG = "ContactServices"; private final IContactProxy mInstance = ContactProxyFactory.create(); public InputStream getPhoto(ContentResolver cr, String id) { return mInstance.getPhoto(cr, id); } public boolean isContactUpdatable(ContentResolver cr, String id) { return mInstance.isContactUpdatable(cr, id); } public void updatePhoto (ContentResolver cr, byte[] image, String id, boolean fromthumb) { updatePhoto(cr, image, id, false, fromthumb); } public void updatePhoto (ContentResolver cr, byte[] image, String id, boolean markDirty, boolean fromthumb) { mInstance.updatePhoto(cr, image, id, markDirty, fromthumb); }
// Path: src/com/nloko/android/syncmypix/PhoneContact.java // public final class PhoneContact implements Comparable<PhoneContact> { // // public PhoneContact(String id, String name) { // this(id, name, null); // } // // public PhoneContact(String id, String name, String lookup) { // this.id = id; // this.name = name; // this.lookup = lookup; // } // // public String id; // public String name; // public String lookup; // // public int compareTo(PhoneContact another) { // return name.compareTo(another.name); // } // } // Path: src/com/nloko/android/syncmypix/contactutils/ContactUtils.java import java.io.InputStream; import com.nloko.android.syncmypix.PhoneContact; import android.content.ContentResolver; import android.net.Uri; // // ContactUtils.java is part of SyncMyPix // // Authors: // Neil Loknath <neil.loknath@gmail.com> // // Copyright (c) 2009 Neil Loknath // // SyncMyPix 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. // // SyncMyPix 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 SyncMyPix. If not, see <http://www.gnu.org/licenses/>. // package com.nloko.android.syncmypix.contactutils; public final class ContactUtils { private static final String TAG = "ContactServices"; private final IContactProxy mInstance = ContactProxyFactory.create(); public InputStream getPhoto(ContentResolver cr, String id) { return mInstance.getPhoto(cr, id); } public boolean isContactUpdatable(ContentResolver cr, String id) { return mInstance.isContactUpdatable(cr, id); } public void updatePhoto (ContentResolver cr, byte[] image, String id, boolean fromthumb) { updatePhoto(cr, image, id, false, fromthumb); } public void updatePhoto (ContentResolver cr, byte[] image, String id, boolean markDirty, boolean fromthumb) { mInstance.updatePhoto(cr, image, id, markDirty, fromthumb); }
public PhoneContact confirmContact(ContentResolver cr, String id, String lookup) {
nloko/SyncMyPix
src/com/nloko/android/syncmypix/SyncMyPixProvider.java
// Path: src/com/nloko/android/Log.java // public final class Log { // // public static boolean debug = false; // // public static void d(String tag, String message) // { // if (debug) { // android.util.Log.d(tag, message); // } // } // // public static void w(String tag, String message) // { // android.util.Log.w(tag, message); // } // // public static void e(String tag, String message) // { // android.util.Log.e(tag, message); // } // // public static void v(String tag, String message) // { // android.util.Log.v(tag, message); // } // // public static void i(String tag, String message) // { // android.util.Log.i(tag, message); // } // } // // Path: src/com/nloko/android/syncmypix/SyncMyPix.java // public static final class Contacts implements BaseColumns { // public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/contacts"); // public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.nloko.contact"; // public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.nloko.contact"; // // public static final String DEFAULT_SORT_ORDER = "_id ASC"; // public static final String LOOKUP_KEY = "lookup_key"; // public static final String PIC_URL = "pic_url"; // public static final String PHOTO_HASH = "photo_hash"; // public static final String NETWORK_PHOTO_HASH = "network_photo_hash"; // public static final String FRIEND_ID = "friend_id"; // public static final String SOURCE = "source"; // } // // Path: src/com/nloko/android/syncmypix/SyncMyPix.java // public static final class Results implements BaseColumns { // public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/results"); // public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.nloko.result"; // public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.nloko.result"; // // public static final String DEFAULT_SORT_ORDER = "name ASC"; // public static final String NAME = "name"; // public static final String PIC_URL = "pic_url"; // public static final String DESCRIPTION = "description"; // public static final String FRIEND_ID = "friend_id"; // public static final String CONTACT_ID = "contact_id"; // public static final String LOOKUP_KEY = "lookup_key"; // public static final String SYNC_ID = "sync_id"; // } // // Path: src/com/nloko/android/syncmypix/SyncMyPix.java // public static final class Sync implements BaseColumns { // public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/sync"); // public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.nloko.sync"; // public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.nloko.sync"; // // public static final String DEFAULT_SORT_ORDER = "source ASC"; // public static final String DATE_STARTED = "date_started"; // public static final String DATE_COMPLETED = "date_completed"; // public static final String UPDATED = "updated"; // public static final String SKIPPED = "skipped"; // public static final String NOT_FOUND = "not_found"; // public static final String SOURCE = "source"; // }
import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.UriMatcher; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteQueryBuilder; import android.net.Uri; import android.text.TextUtils; import java.util.HashMap; import com.nloko.android.Log; import com.nloko.android.syncmypix.SyncMyPix.Contacts; import com.nloko.android.syncmypix.SyncMyPix.Results; import com.nloko.android.syncmypix.SyncMyPix.Sync; import android.content.ContentProvider;
private static final int CONTACTS = 1; private static final int CONTACTS_ID = 2; private static final int RESULTS = 3; private static final int RESULTS_ID = 4; private static final int SYNC = 5; private static final int SYNC_ID = 6; private static final UriMatcher uriMatcher; static { uriMatcher = new UriMatcher(UriMatcher.NO_MATCH); uriMatcher.addURI(SyncMyPix.AUTHORITY, "contacts", CONTACTS); uriMatcher.addURI(SyncMyPix.AUTHORITY, "contacts/#", CONTACTS_ID); uriMatcher.addURI(SyncMyPix.AUTHORITY, "results", RESULTS); uriMatcher.addURI(SyncMyPix.AUTHORITY, "results/#", RESULTS_ID); uriMatcher.addURI(SyncMyPix.AUTHORITY, "sync", SYNC); uriMatcher.addURI(SyncMyPix.AUTHORITY, "sync/#", SYNC_ID); // Map columns to resolve ambiguity contactsProjection = new HashMap<String, String>(); contactsProjection.put(Contacts._ID, Contacts._ID); contactsProjection.put(Contacts.LOOKUP_KEY, Contacts.LOOKUP_KEY); contactsProjection.put(Contacts.PIC_URL, Contacts.PIC_URL); contactsProjection.put(Contacts.PHOTO_HASH, Contacts.PHOTO_HASH); contactsProjection.put(Contacts.NETWORK_PHOTO_HASH, Contacts.NETWORK_PHOTO_HASH); contactsProjection.put(Contacts.FRIEND_ID, Contacts.FRIEND_ID); contactsProjection.put(Contacts.SOURCE, Contacts.SOURCE); syncProjection = new HashMap<String, String>();
// Path: src/com/nloko/android/Log.java // public final class Log { // // public static boolean debug = false; // // public static void d(String tag, String message) // { // if (debug) { // android.util.Log.d(tag, message); // } // } // // public static void w(String tag, String message) // { // android.util.Log.w(tag, message); // } // // public static void e(String tag, String message) // { // android.util.Log.e(tag, message); // } // // public static void v(String tag, String message) // { // android.util.Log.v(tag, message); // } // // public static void i(String tag, String message) // { // android.util.Log.i(tag, message); // } // } // // Path: src/com/nloko/android/syncmypix/SyncMyPix.java // public static final class Contacts implements BaseColumns { // public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/contacts"); // public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.nloko.contact"; // public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.nloko.contact"; // // public static final String DEFAULT_SORT_ORDER = "_id ASC"; // public static final String LOOKUP_KEY = "lookup_key"; // public static final String PIC_URL = "pic_url"; // public static final String PHOTO_HASH = "photo_hash"; // public static final String NETWORK_PHOTO_HASH = "network_photo_hash"; // public static final String FRIEND_ID = "friend_id"; // public static final String SOURCE = "source"; // } // // Path: src/com/nloko/android/syncmypix/SyncMyPix.java // public static final class Results implements BaseColumns { // public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/results"); // public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.nloko.result"; // public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.nloko.result"; // // public static final String DEFAULT_SORT_ORDER = "name ASC"; // public static final String NAME = "name"; // public static final String PIC_URL = "pic_url"; // public static final String DESCRIPTION = "description"; // public static final String FRIEND_ID = "friend_id"; // public static final String CONTACT_ID = "contact_id"; // public static final String LOOKUP_KEY = "lookup_key"; // public static final String SYNC_ID = "sync_id"; // } // // Path: src/com/nloko/android/syncmypix/SyncMyPix.java // public static final class Sync implements BaseColumns { // public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/sync"); // public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.nloko.sync"; // public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.nloko.sync"; // // public static final String DEFAULT_SORT_ORDER = "source ASC"; // public static final String DATE_STARTED = "date_started"; // public static final String DATE_COMPLETED = "date_completed"; // public static final String UPDATED = "updated"; // public static final String SKIPPED = "skipped"; // public static final String NOT_FOUND = "not_found"; // public static final String SOURCE = "source"; // } // Path: src/com/nloko/android/syncmypix/SyncMyPixProvider.java import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.UriMatcher; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteQueryBuilder; import android.net.Uri; import android.text.TextUtils; import java.util.HashMap; import com.nloko.android.Log; import com.nloko.android.syncmypix.SyncMyPix.Contacts; import com.nloko.android.syncmypix.SyncMyPix.Results; import com.nloko.android.syncmypix.SyncMyPix.Sync; import android.content.ContentProvider; private static final int CONTACTS = 1; private static final int CONTACTS_ID = 2; private static final int RESULTS = 3; private static final int RESULTS_ID = 4; private static final int SYNC = 5; private static final int SYNC_ID = 6; private static final UriMatcher uriMatcher; static { uriMatcher = new UriMatcher(UriMatcher.NO_MATCH); uriMatcher.addURI(SyncMyPix.AUTHORITY, "contacts", CONTACTS); uriMatcher.addURI(SyncMyPix.AUTHORITY, "contacts/#", CONTACTS_ID); uriMatcher.addURI(SyncMyPix.AUTHORITY, "results", RESULTS); uriMatcher.addURI(SyncMyPix.AUTHORITY, "results/#", RESULTS_ID); uriMatcher.addURI(SyncMyPix.AUTHORITY, "sync", SYNC); uriMatcher.addURI(SyncMyPix.AUTHORITY, "sync/#", SYNC_ID); // Map columns to resolve ambiguity contactsProjection = new HashMap<String, String>(); contactsProjection.put(Contacts._ID, Contacts._ID); contactsProjection.put(Contacts.LOOKUP_KEY, Contacts.LOOKUP_KEY); contactsProjection.put(Contacts.PIC_URL, Contacts.PIC_URL); contactsProjection.put(Contacts.PHOTO_HASH, Contacts.PHOTO_HASH); contactsProjection.put(Contacts.NETWORK_PHOTO_HASH, Contacts.NETWORK_PHOTO_HASH); contactsProjection.put(Contacts.FRIEND_ID, Contacts.FRIEND_ID); contactsProjection.put(Contacts.SOURCE, Contacts.SOURCE); syncProjection = new HashMap<String, String>();
syncProjection.put(Sync._ID, SYNC_TABLE_NAME + "." + Sync._ID);
nloko/SyncMyPix
src/com/nloko/android/syncmypix/SyncMyPixProvider.java
// Path: src/com/nloko/android/Log.java // public final class Log { // // public static boolean debug = false; // // public static void d(String tag, String message) // { // if (debug) { // android.util.Log.d(tag, message); // } // } // // public static void w(String tag, String message) // { // android.util.Log.w(tag, message); // } // // public static void e(String tag, String message) // { // android.util.Log.e(tag, message); // } // // public static void v(String tag, String message) // { // android.util.Log.v(tag, message); // } // // public static void i(String tag, String message) // { // android.util.Log.i(tag, message); // } // } // // Path: src/com/nloko/android/syncmypix/SyncMyPix.java // public static final class Contacts implements BaseColumns { // public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/contacts"); // public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.nloko.contact"; // public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.nloko.contact"; // // public static final String DEFAULT_SORT_ORDER = "_id ASC"; // public static final String LOOKUP_KEY = "lookup_key"; // public static final String PIC_URL = "pic_url"; // public static final String PHOTO_HASH = "photo_hash"; // public static final String NETWORK_PHOTO_HASH = "network_photo_hash"; // public static final String FRIEND_ID = "friend_id"; // public static final String SOURCE = "source"; // } // // Path: src/com/nloko/android/syncmypix/SyncMyPix.java // public static final class Results implements BaseColumns { // public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/results"); // public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.nloko.result"; // public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.nloko.result"; // // public static final String DEFAULT_SORT_ORDER = "name ASC"; // public static final String NAME = "name"; // public static final String PIC_URL = "pic_url"; // public static final String DESCRIPTION = "description"; // public static final String FRIEND_ID = "friend_id"; // public static final String CONTACT_ID = "contact_id"; // public static final String LOOKUP_KEY = "lookup_key"; // public static final String SYNC_ID = "sync_id"; // } // // Path: src/com/nloko/android/syncmypix/SyncMyPix.java // public static final class Sync implements BaseColumns { // public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/sync"); // public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.nloko.sync"; // public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.nloko.sync"; // // public static final String DEFAULT_SORT_ORDER = "source ASC"; // public static final String DATE_STARTED = "date_started"; // public static final String DATE_COMPLETED = "date_completed"; // public static final String UPDATED = "updated"; // public static final String SKIPPED = "skipped"; // public static final String NOT_FOUND = "not_found"; // public static final String SOURCE = "source"; // }
import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.UriMatcher; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteQueryBuilder; import android.net.Uri; import android.text.TextUtils; import java.util.HashMap; import com.nloko.android.Log; import com.nloko.android.syncmypix.SyncMyPix.Contacts; import com.nloko.android.syncmypix.SyncMyPix.Results; import com.nloko.android.syncmypix.SyncMyPix.Sync; import android.content.ContentProvider;
uriMatcher.addURI(SyncMyPix.AUTHORITY, "sync/#", SYNC_ID); // Map columns to resolve ambiguity contactsProjection = new HashMap<String, String>(); contactsProjection.put(Contacts._ID, Contacts._ID); contactsProjection.put(Contacts.LOOKUP_KEY, Contacts.LOOKUP_KEY); contactsProjection.put(Contacts.PIC_URL, Contacts.PIC_URL); contactsProjection.put(Contacts.PHOTO_HASH, Contacts.PHOTO_HASH); contactsProjection.put(Contacts.NETWORK_PHOTO_HASH, Contacts.NETWORK_PHOTO_HASH); contactsProjection.put(Contacts.FRIEND_ID, Contacts.FRIEND_ID); contactsProjection.put(Contacts.SOURCE, Contacts.SOURCE); syncProjection = new HashMap<String, String>(); syncProjection.put(Sync._ID, SYNC_TABLE_NAME + "." + Sync._ID); syncProjection.put(Sync.SOURCE, Sync.SOURCE); syncProjection.put(Sync.DATE_STARTED, Sync.DATE_STARTED); syncProjection.put(Sync.DATE_COMPLETED, Sync.DATE_COMPLETED); syncProjection.put(Sync.UPDATED, Sync.UPDATED); syncProjection.put(Sync.SKIPPED, Sync.SKIPPED); syncProjection.put(Sync.NOT_FOUND, Sync.NOT_FOUND); resultsProjection = new HashMap<String, String>(); resultsProjection.put(Sync._ID, SYNC_TABLE_NAME + "." + Sync._ID); resultsProjection.put(Sync.SOURCE, Sync.SOURCE); resultsProjection.put(Sync.DATE_STARTED, Sync.DATE_STARTED); resultsProjection.put(Sync.DATE_COMPLETED, Sync.DATE_COMPLETED); resultsProjection.put(Sync.UPDATED, Sync.UPDATED); resultsProjection.put(Sync.SKIPPED, Sync.SKIPPED); resultsProjection.put(Sync.NOT_FOUND, Sync.NOT_FOUND);
// Path: src/com/nloko/android/Log.java // public final class Log { // // public static boolean debug = false; // // public static void d(String tag, String message) // { // if (debug) { // android.util.Log.d(tag, message); // } // } // // public static void w(String tag, String message) // { // android.util.Log.w(tag, message); // } // // public static void e(String tag, String message) // { // android.util.Log.e(tag, message); // } // // public static void v(String tag, String message) // { // android.util.Log.v(tag, message); // } // // public static void i(String tag, String message) // { // android.util.Log.i(tag, message); // } // } // // Path: src/com/nloko/android/syncmypix/SyncMyPix.java // public static final class Contacts implements BaseColumns { // public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/contacts"); // public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.nloko.contact"; // public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.nloko.contact"; // // public static final String DEFAULT_SORT_ORDER = "_id ASC"; // public static final String LOOKUP_KEY = "lookup_key"; // public static final String PIC_URL = "pic_url"; // public static final String PHOTO_HASH = "photo_hash"; // public static final String NETWORK_PHOTO_HASH = "network_photo_hash"; // public static final String FRIEND_ID = "friend_id"; // public static final String SOURCE = "source"; // } // // Path: src/com/nloko/android/syncmypix/SyncMyPix.java // public static final class Results implements BaseColumns { // public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/results"); // public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.nloko.result"; // public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.nloko.result"; // // public static final String DEFAULT_SORT_ORDER = "name ASC"; // public static final String NAME = "name"; // public static final String PIC_URL = "pic_url"; // public static final String DESCRIPTION = "description"; // public static final String FRIEND_ID = "friend_id"; // public static final String CONTACT_ID = "contact_id"; // public static final String LOOKUP_KEY = "lookup_key"; // public static final String SYNC_ID = "sync_id"; // } // // Path: src/com/nloko/android/syncmypix/SyncMyPix.java // public static final class Sync implements BaseColumns { // public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/sync"); // public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.nloko.sync"; // public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.nloko.sync"; // // public static final String DEFAULT_SORT_ORDER = "source ASC"; // public static final String DATE_STARTED = "date_started"; // public static final String DATE_COMPLETED = "date_completed"; // public static final String UPDATED = "updated"; // public static final String SKIPPED = "skipped"; // public static final String NOT_FOUND = "not_found"; // public static final String SOURCE = "source"; // } // Path: src/com/nloko/android/syncmypix/SyncMyPixProvider.java import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.UriMatcher; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteQueryBuilder; import android.net.Uri; import android.text.TextUtils; import java.util.HashMap; import com.nloko.android.Log; import com.nloko.android.syncmypix.SyncMyPix.Contacts; import com.nloko.android.syncmypix.SyncMyPix.Results; import com.nloko.android.syncmypix.SyncMyPix.Sync; import android.content.ContentProvider; uriMatcher.addURI(SyncMyPix.AUTHORITY, "sync/#", SYNC_ID); // Map columns to resolve ambiguity contactsProjection = new HashMap<String, String>(); contactsProjection.put(Contacts._ID, Contacts._ID); contactsProjection.put(Contacts.LOOKUP_KEY, Contacts.LOOKUP_KEY); contactsProjection.put(Contacts.PIC_URL, Contacts.PIC_URL); contactsProjection.put(Contacts.PHOTO_HASH, Contacts.PHOTO_HASH); contactsProjection.put(Contacts.NETWORK_PHOTO_HASH, Contacts.NETWORK_PHOTO_HASH); contactsProjection.put(Contacts.FRIEND_ID, Contacts.FRIEND_ID); contactsProjection.put(Contacts.SOURCE, Contacts.SOURCE); syncProjection = new HashMap<String, String>(); syncProjection.put(Sync._ID, SYNC_TABLE_NAME + "." + Sync._ID); syncProjection.put(Sync.SOURCE, Sync.SOURCE); syncProjection.put(Sync.DATE_STARTED, Sync.DATE_STARTED); syncProjection.put(Sync.DATE_COMPLETED, Sync.DATE_COMPLETED); syncProjection.put(Sync.UPDATED, Sync.UPDATED); syncProjection.put(Sync.SKIPPED, Sync.SKIPPED); syncProjection.put(Sync.NOT_FOUND, Sync.NOT_FOUND); resultsProjection = new HashMap<String, String>(); resultsProjection.put(Sync._ID, SYNC_TABLE_NAME + "." + Sync._ID); resultsProjection.put(Sync.SOURCE, Sync.SOURCE); resultsProjection.put(Sync.DATE_STARTED, Sync.DATE_STARTED); resultsProjection.put(Sync.DATE_COMPLETED, Sync.DATE_COMPLETED); resultsProjection.put(Sync.UPDATED, Sync.UPDATED); resultsProjection.put(Sync.SKIPPED, Sync.SKIPPED); resultsProjection.put(Sync.NOT_FOUND, Sync.NOT_FOUND);
resultsProjection.put(Results._ID, RESULTS_TABLE_NAME + "." + Results._ID);
nloko/SyncMyPix
src/com/nloko/android/syncmypix/SyncMyPixProvider.java
// Path: src/com/nloko/android/Log.java // public final class Log { // // public static boolean debug = false; // // public static void d(String tag, String message) // { // if (debug) { // android.util.Log.d(tag, message); // } // } // // public static void w(String tag, String message) // { // android.util.Log.w(tag, message); // } // // public static void e(String tag, String message) // { // android.util.Log.e(tag, message); // } // // public static void v(String tag, String message) // { // android.util.Log.v(tag, message); // } // // public static void i(String tag, String message) // { // android.util.Log.i(tag, message); // } // } // // Path: src/com/nloko/android/syncmypix/SyncMyPix.java // public static final class Contacts implements BaseColumns { // public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/contacts"); // public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.nloko.contact"; // public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.nloko.contact"; // // public static final String DEFAULT_SORT_ORDER = "_id ASC"; // public static final String LOOKUP_KEY = "lookup_key"; // public static final String PIC_URL = "pic_url"; // public static final String PHOTO_HASH = "photo_hash"; // public static final String NETWORK_PHOTO_HASH = "network_photo_hash"; // public static final String FRIEND_ID = "friend_id"; // public static final String SOURCE = "source"; // } // // Path: src/com/nloko/android/syncmypix/SyncMyPix.java // public static final class Results implements BaseColumns { // public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/results"); // public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.nloko.result"; // public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.nloko.result"; // // public static final String DEFAULT_SORT_ORDER = "name ASC"; // public static final String NAME = "name"; // public static final String PIC_URL = "pic_url"; // public static final String DESCRIPTION = "description"; // public static final String FRIEND_ID = "friend_id"; // public static final String CONTACT_ID = "contact_id"; // public static final String LOOKUP_KEY = "lookup_key"; // public static final String SYNC_ID = "sync_id"; // } // // Path: src/com/nloko/android/syncmypix/SyncMyPix.java // public static final class Sync implements BaseColumns { // public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/sync"); // public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.nloko.sync"; // public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.nloko.sync"; // // public static final String DEFAULT_SORT_ORDER = "source ASC"; // public static final String DATE_STARTED = "date_started"; // public static final String DATE_COMPLETED = "date_completed"; // public static final String UPDATED = "updated"; // public static final String SKIPPED = "skipped"; // public static final String NOT_FOUND = "not_found"; // public static final String SOURCE = "source"; // }
import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.UriMatcher; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteQueryBuilder; import android.net.Uri; import android.text.TextUtils; import java.util.HashMap; import com.nloko.android.Log; import com.nloko.android.syncmypix.SyncMyPix.Contacts; import com.nloko.android.syncmypix.SyncMyPix.Results; import com.nloko.android.syncmypix.SyncMyPix.Sync; import android.content.ContentProvider;
+ Contacts.PHOTO_HASH + " TEXT," + Contacts.NETWORK_PHOTO_HASH + " TEXT," + Contacts.FRIEND_ID + " TEXT DEFAULT NULL," + Contacts.SOURCE + " TEXT" + ");"); db.execSQL("CREATE TABLE " + RESULTS_TABLE_NAME + " (" + Results._ID + " INTEGER PRIMARY KEY," + Results.SYNC_ID + " INTEGER," + Results.NAME + " TEXT DEFAULT NULL," + Results.DESCRIPTION + " TEXT DEFAULT NULL," + Results.PIC_URL + " TEXT DEFAULT NULL," + Results.CONTACT_ID + " INTEGER," + Results.LOOKUP_KEY + " TEXT DEFAULT NULL," + Results.FRIEND_ID + " TEXT DEFAULT NULL" + ");"); db.execSQL("CREATE TABLE " + SYNC_TABLE_NAME + " (" + Sync._ID + " INTEGER PRIMARY KEY," + Sync.SOURCE + " TEXT DEFAULT NULL," + Sync.DATE_STARTED + " INTEGER," + Sync.DATE_COMPLETED + " INTEGER," + Sync.UPDATED + " INTEGER," + Sync.SKIPPED + " INTEGER," + Sync.NOT_FOUND + " INTEGER" + ");"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Path: src/com/nloko/android/Log.java // public final class Log { // // public static boolean debug = false; // // public static void d(String tag, String message) // { // if (debug) { // android.util.Log.d(tag, message); // } // } // // public static void w(String tag, String message) // { // android.util.Log.w(tag, message); // } // // public static void e(String tag, String message) // { // android.util.Log.e(tag, message); // } // // public static void v(String tag, String message) // { // android.util.Log.v(tag, message); // } // // public static void i(String tag, String message) // { // android.util.Log.i(tag, message); // } // } // // Path: src/com/nloko/android/syncmypix/SyncMyPix.java // public static final class Contacts implements BaseColumns { // public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/contacts"); // public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.nloko.contact"; // public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.nloko.contact"; // // public static final String DEFAULT_SORT_ORDER = "_id ASC"; // public static final String LOOKUP_KEY = "lookup_key"; // public static final String PIC_URL = "pic_url"; // public static final String PHOTO_HASH = "photo_hash"; // public static final String NETWORK_PHOTO_HASH = "network_photo_hash"; // public static final String FRIEND_ID = "friend_id"; // public static final String SOURCE = "source"; // } // // Path: src/com/nloko/android/syncmypix/SyncMyPix.java // public static final class Results implements BaseColumns { // public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/results"); // public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.nloko.result"; // public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.nloko.result"; // // public static final String DEFAULT_SORT_ORDER = "name ASC"; // public static final String NAME = "name"; // public static final String PIC_URL = "pic_url"; // public static final String DESCRIPTION = "description"; // public static final String FRIEND_ID = "friend_id"; // public static final String CONTACT_ID = "contact_id"; // public static final String LOOKUP_KEY = "lookup_key"; // public static final String SYNC_ID = "sync_id"; // } // // Path: src/com/nloko/android/syncmypix/SyncMyPix.java // public static final class Sync implements BaseColumns { // public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/sync"); // public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.nloko.sync"; // public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.nloko.sync"; // // public static final String DEFAULT_SORT_ORDER = "source ASC"; // public static final String DATE_STARTED = "date_started"; // public static final String DATE_COMPLETED = "date_completed"; // public static final String UPDATED = "updated"; // public static final String SKIPPED = "skipped"; // public static final String NOT_FOUND = "not_found"; // public static final String SOURCE = "source"; // } // Path: src/com/nloko/android/syncmypix/SyncMyPixProvider.java import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.UriMatcher; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteQueryBuilder; import android.net.Uri; import android.text.TextUtils; import java.util.HashMap; import com.nloko.android.Log; import com.nloko.android.syncmypix.SyncMyPix.Contacts; import com.nloko.android.syncmypix.SyncMyPix.Results; import com.nloko.android.syncmypix.SyncMyPix.Sync; import android.content.ContentProvider; + Contacts.PHOTO_HASH + " TEXT," + Contacts.NETWORK_PHOTO_HASH + " TEXT," + Contacts.FRIEND_ID + " TEXT DEFAULT NULL," + Contacts.SOURCE + " TEXT" + ");"); db.execSQL("CREATE TABLE " + RESULTS_TABLE_NAME + " (" + Results._ID + " INTEGER PRIMARY KEY," + Results.SYNC_ID + " INTEGER," + Results.NAME + " TEXT DEFAULT NULL," + Results.DESCRIPTION + " TEXT DEFAULT NULL," + Results.PIC_URL + " TEXT DEFAULT NULL," + Results.CONTACT_ID + " INTEGER," + Results.LOOKUP_KEY + " TEXT DEFAULT NULL," + Results.FRIEND_ID + " TEXT DEFAULT NULL" + ");"); db.execSQL("CREATE TABLE " + SYNC_TABLE_NAME + " (" + Sync._ID + " INTEGER PRIMARY KEY," + Sync.SOURCE + " TEXT DEFAULT NULL," + Sync.DATE_STARTED + " INTEGER," + Sync.DATE_COMPLETED + " INTEGER," + Sync.UPDATED + " INTEGER," + Sync.SKIPPED + " INTEGER," + Sync.NOT_FOUND + " INTEGER" + ");"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
beckchr/juel
modules/api/src/test/java/javax/el/ELContextTest.java
// Path: modules/api/src/test/java/javax/el/TestContext.java // public class TestContext extends ELContext { // @Override // public FunctionMapper getFunctionMapper() { // return null; // } // // @Override // public VariableMapper getVariableMapper() { // return null; // } // // @Override // public ELResolver getELResolver() { // return null; // } // }
import java.util.Locale; import junit.framework.TestCase; import javax.el.TestContext;
/* * Copyright 2006-2009 Odysseus Software GmbH * * 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 javax.el; public class ELContextTest extends TestCase { public void testContext() {
// Path: modules/api/src/test/java/javax/el/TestContext.java // public class TestContext extends ELContext { // @Override // public FunctionMapper getFunctionMapper() { // return null; // } // // @Override // public VariableMapper getVariableMapper() { // return null; // } // // @Override // public ELResolver getELResolver() { // return null; // } // } // Path: modules/api/src/test/java/javax/el/ELContextTest.java import java.util.Locale; import junit.framework.TestCase; import javax.el.TestContext; /* * Copyright 2006-2009 Odysseus Software GmbH * * 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 javax.el; public class ELContextTest extends TestCase { public void testContext() {
ELContext context = new TestContext();
beckchr/juel
modules/api/src/test/java/javax/el/BeanELResolverTest.java
// Path: modules/api/src/test/java/javax/el/test/TestClass.java // public class TestClass { // private static class TestInterfaceImpl implements TestInterface { // public int getFourtyTwo() { // return 42; // } // } // // private static class NestedClass { // public static class TestInterfaceImpl2 implements TestInterface { // public int getFourtyTwo() { // return 42; // } // } // } // // private TestInterface anonymousTestInterface = new TestInterface() { // public int getFourtyTwo() { // return 42; // } // }; // // public TestInterface getNestedTestInterface() { // return new TestInterfaceImpl(); // } // // public TestInterface getNestedTestInterface2() { // return new NestedClass.TestInterfaceImpl2(); // } // // public TestInterface getAnonymousTestInterface() { // return anonymousTestInterface; // } // }
import java.beans.FeatureDescriptor; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Properties; import javax.el.test.TestClass; import junit.framework.TestCase;
assertFalse(context.isPropertyResolved()); // base is bean, property == "readWrite" --> 123 context.setPropertyResolved(false); assertEquals(456, resolver.getValue(context, new TestBean(), "readWrite")); assertTrue(context.isPropertyResolved()); // base is bean, property == "writeOnly" --> exception try { resolver.getValue(context, new TestBean(), "writeOnly"); fail(); } catch (PropertyNotFoundException e) { // fine } // base is bean, property != null, but doesn't exist --> exception try { resolver.getValue(context, new TestBean(), "doesntExist"); fail(); } catch (PropertyNotFoundException e) { // fine } } public void testGetValue2() { Properties properties = new Properties(); properties.setProperty(ExpressionFactory.class.getName(), TestFactory.class.getName()); BeanELResolver resolver = new BeanELResolver(); context.setPropertyResolved(false);
// Path: modules/api/src/test/java/javax/el/test/TestClass.java // public class TestClass { // private static class TestInterfaceImpl implements TestInterface { // public int getFourtyTwo() { // return 42; // } // } // // private static class NestedClass { // public static class TestInterfaceImpl2 implements TestInterface { // public int getFourtyTwo() { // return 42; // } // } // } // // private TestInterface anonymousTestInterface = new TestInterface() { // public int getFourtyTwo() { // return 42; // } // }; // // public TestInterface getNestedTestInterface() { // return new TestInterfaceImpl(); // } // // public TestInterface getNestedTestInterface2() { // return new NestedClass.TestInterfaceImpl2(); // } // // public TestInterface getAnonymousTestInterface() { // return anonymousTestInterface; // } // } // Path: modules/api/src/test/java/javax/el/BeanELResolverTest.java import java.beans.FeatureDescriptor; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Properties; import javax.el.test.TestClass; import junit.framework.TestCase; assertFalse(context.isPropertyResolved()); // base is bean, property == "readWrite" --> 123 context.setPropertyResolved(false); assertEquals(456, resolver.getValue(context, new TestBean(), "readWrite")); assertTrue(context.isPropertyResolved()); // base is bean, property == "writeOnly" --> exception try { resolver.getValue(context, new TestBean(), "writeOnly"); fail(); } catch (PropertyNotFoundException e) { // fine } // base is bean, property != null, but doesn't exist --> exception try { resolver.getValue(context, new TestBean(), "doesntExist"); fail(); } catch (PropertyNotFoundException e) { // fine } } public void testGetValue2() { Properties properties = new Properties(); properties.setProperty(ExpressionFactory.class.getName(), TestFactory.class.getName()); BeanELResolver resolver = new BeanELResolver(); context.setPropertyResolved(false);
assertEquals(42, resolver.getValue(context, new TestClass().getAnonymousTestInterface(), "fourtyTwo"));
rodolfodpk/myeslib
myeslib-core/src/main/java/org/myeslib/core/data/Snapshot.java
// Path: myeslib-core/src/main/java/org/myeslib/core/AggregateRoot.java // public interface AggregateRoot extends Serializable { // // }
import java.io.Serializable; import org.myeslib.core.AggregateRoot; import lombok.Value;
package org.myeslib.core.data; @SuppressWarnings("serial") @Value
// Path: myeslib-core/src/main/java/org/myeslib/core/AggregateRoot.java // public interface AggregateRoot extends Serializable { // // } // Path: myeslib-core/src/main/java/org/myeslib/core/data/Snapshot.java import java.io.Serializable; import org.myeslib.core.AggregateRoot; import lombok.Value; package org.myeslib.core.data; @SuppressWarnings("serial") @Value
public class Snapshot<A extends AggregateRoot> implements Serializable {
rodolfodpk/myeslib
myeslib-jdbi/src/main/java/org/myeslib/jdbi/storage/JdbiUnitOfWorkJournal.java
// Path: myeslib-core/src/main/java/org/myeslib/core/data/UnitOfWork.java // @SuppressWarnings("serial") // @Value // public class UnitOfWork implements Comparable<UnitOfWork>, Serializable { // // final UUID id; // final Command command; // final List<? extends Event> events; // final long version; // // public UnitOfWork(UUID id, Command command, Long version, List<? extends Event> events) { // checkNotNull(id, "id cannot be null"); // checkNotNull(command, "command cannot be null"); // checkArgument(command.getTargetVersion()>=0, "target version must be >= 0"); // checkArgument(version>0, "invalid version"); // checkNotNull(events, "events cannot be null"); // for (Event e: events){ // checkNotNull(e, "event within events list cannot be null"); // } // this.id = id; // this.command = command; // this.version = version; // this.events = events; // } // // public static UnitOfWork create(UUID id, Command command, List<? extends Event> newEvents) { // checkNotNull(command.getTargetVersion(), "target version cannot be null"); // checkArgument(command.getTargetVersion()>=0, "target version must be >= 0"); // return new UnitOfWork(id, command, command.getTargetVersion()+1, newEvents); // } // // public List<Event> getEvents(){ // List<Event> result = new LinkedList<>(); // for (Event event : events) { // result.add(event); // } // return result; // } // // public int compareTo(UnitOfWork other) { // if (version < other.version) { // return -1; // } else if (version > other.version) { // return 1; // } // return 0; // } // // public Long getTargetVersion() { // return command.getTargetVersion(); // } // } // // Path: myeslib-core/src/main/java/org/myeslib/core/storage/UnitOfWorkJournal.java // public interface UnitOfWorkJournal<K> { // // public void append(final K id, final UnitOfWork uow) ; // // } // // Path: myeslib-util/src/main/java/org/myeslib/util/jdbi/UnitOfWorkJournalDao.java // public interface UnitOfWorkJournalDao<K> { // // void append(K id, UnitOfWork uow); // // }
import org.myeslib.core.data.UnitOfWork; import org.myeslib.core.storage.UnitOfWorkJournal; import org.myeslib.util.jdbi.UnitOfWorkJournalDao; import com.google.inject.Inject;
package org.myeslib.jdbi.storage; public class JdbiUnitOfWorkJournal<K> implements UnitOfWorkJournal<K> { @Inject
// Path: myeslib-core/src/main/java/org/myeslib/core/data/UnitOfWork.java // @SuppressWarnings("serial") // @Value // public class UnitOfWork implements Comparable<UnitOfWork>, Serializable { // // final UUID id; // final Command command; // final List<? extends Event> events; // final long version; // // public UnitOfWork(UUID id, Command command, Long version, List<? extends Event> events) { // checkNotNull(id, "id cannot be null"); // checkNotNull(command, "command cannot be null"); // checkArgument(command.getTargetVersion()>=0, "target version must be >= 0"); // checkArgument(version>0, "invalid version"); // checkNotNull(events, "events cannot be null"); // for (Event e: events){ // checkNotNull(e, "event within events list cannot be null"); // } // this.id = id; // this.command = command; // this.version = version; // this.events = events; // } // // public static UnitOfWork create(UUID id, Command command, List<? extends Event> newEvents) { // checkNotNull(command.getTargetVersion(), "target version cannot be null"); // checkArgument(command.getTargetVersion()>=0, "target version must be >= 0"); // return new UnitOfWork(id, command, command.getTargetVersion()+1, newEvents); // } // // public List<Event> getEvents(){ // List<Event> result = new LinkedList<>(); // for (Event event : events) { // result.add(event); // } // return result; // } // // public int compareTo(UnitOfWork other) { // if (version < other.version) { // return -1; // } else if (version > other.version) { // return 1; // } // return 0; // } // // public Long getTargetVersion() { // return command.getTargetVersion(); // } // } // // Path: myeslib-core/src/main/java/org/myeslib/core/storage/UnitOfWorkJournal.java // public interface UnitOfWorkJournal<K> { // // public void append(final K id, final UnitOfWork uow) ; // // } // // Path: myeslib-util/src/main/java/org/myeslib/util/jdbi/UnitOfWorkJournalDao.java // public interface UnitOfWorkJournalDao<K> { // // void append(K id, UnitOfWork uow); // // } // Path: myeslib-jdbi/src/main/java/org/myeslib/jdbi/storage/JdbiUnitOfWorkJournal.java import org.myeslib.core.data.UnitOfWork; import org.myeslib.core.storage.UnitOfWorkJournal; import org.myeslib.util.jdbi.UnitOfWorkJournalDao; import com.google.inject.Inject; package org.myeslib.jdbi.storage; public class JdbiUnitOfWorkJournal<K> implements UnitOfWorkJournal<K> { @Inject
public JdbiUnitOfWorkJournal(UnitOfWorkJournalDao<K> dao) {
rodolfodpk/myeslib
myeslib-jdbi/src/main/java/org/myeslib/jdbi/storage/JdbiUnitOfWorkJournal.java
// Path: myeslib-core/src/main/java/org/myeslib/core/data/UnitOfWork.java // @SuppressWarnings("serial") // @Value // public class UnitOfWork implements Comparable<UnitOfWork>, Serializable { // // final UUID id; // final Command command; // final List<? extends Event> events; // final long version; // // public UnitOfWork(UUID id, Command command, Long version, List<? extends Event> events) { // checkNotNull(id, "id cannot be null"); // checkNotNull(command, "command cannot be null"); // checkArgument(command.getTargetVersion()>=0, "target version must be >= 0"); // checkArgument(version>0, "invalid version"); // checkNotNull(events, "events cannot be null"); // for (Event e: events){ // checkNotNull(e, "event within events list cannot be null"); // } // this.id = id; // this.command = command; // this.version = version; // this.events = events; // } // // public static UnitOfWork create(UUID id, Command command, List<? extends Event> newEvents) { // checkNotNull(command.getTargetVersion(), "target version cannot be null"); // checkArgument(command.getTargetVersion()>=0, "target version must be >= 0"); // return new UnitOfWork(id, command, command.getTargetVersion()+1, newEvents); // } // // public List<Event> getEvents(){ // List<Event> result = new LinkedList<>(); // for (Event event : events) { // result.add(event); // } // return result; // } // // public int compareTo(UnitOfWork other) { // if (version < other.version) { // return -1; // } else if (version > other.version) { // return 1; // } // return 0; // } // // public Long getTargetVersion() { // return command.getTargetVersion(); // } // } // // Path: myeslib-core/src/main/java/org/myeslib/core/storage/UnitOfWorkJournal.java // public interface UnitOfWorkJournal<K> { // // public void append(final K id, final UnitOfWork uow) ; // // } // // Path: myeslib-util/src/main/java/org/myeslib/util/jdbi/UnitOfWorkJournalDao.java // public interface UnitOfWorkJournalDao<K> { // // void append(K id, UnitOfWork uow); // // }
import org.myeslib.core.data.UnitOfWork; import org.myeslib.core.storage.UnitOfWorkJournal; import org.myeslib.util.jdbi.UnitOfWorkJournalDao; import com.google.inject.Inject;
package org.myeslib.jdbi.storage; public class JdbiUnitOfWorkJournal<K> implements UnitOfWorkJournal<K> { @Inject public JdbiUnitOfWorkJournal(UnitOfWorkJournalDao<K> dao) { this.dao = dao; } private final UnitOfWorkJournalDao<K> dao; /* * (non-Javadoc) * @see org.myeslib.core.storage.UnitOfWorkJournal#append(java.lang.Object, org.myeslib.core.data.UnitOfWork) */
// Path: myeslib-core/src/main/java/org/myeslib/core/data/UnitOfWork.java // @SuppressWarnings("serial") // @Value // public class UnitOfWork implements Comparable<UnitOfWork>, Serializable { // // final UUID id; // final Command command; // final List<? extends Event> events; // final long version; // // public UnitOfWork(UUID id, Command command, Long version, List<? extends Event> events) { // checkNotNull(id, "id cannot be null"); // checkNotNull(command, "command cannot be null"); // checkArgument(command.getTargetVersion()>=0, "target version must be >= 0"); // checkArgument(version>0, "invalid version"); // checkNotNull(events, "events cannot be null"); // for (Event e: events){ // checkNotNull(e, "event within events list cannot be null"); // } // this.id = id; // this.command = command; // this.version = version; // this.events = events; // } // // public static UnitOfWork create(UUID id, Command command, List<? extends Event> newEvents) { // checkNotNull(command.getTargetVersion(), "target version cannot be null"); // checkArgument(command.getTargetVersion()>=0, "target version must be >= 0"); // return new UnitOfWork(id, command, command.getTargetVersion()+1, newEvents); // } // // public List<Event> getEvents(){ // List<Event> result = new LinkedList<>(); // for (Event event : events) { // result.add(event); // } // return result; // } // // public int compareTo(UnitOfWork other) { // if (version < other.version) { // return -1; // } else if (version > other.version) { // return 1; // } // return 0; // } // // public Long getTargetVersion() { // return command.getTargetVersion(); // } // } // // Path: myeslib-core/src/main/java/org/myeslib/core/storage/UnitOfWorkJournal.java // public interface UnitOfWorkJournal<K> { // // public void append(final K id, final UnitOfWork uow) ; // // } // // Path: myeslib-util/src/main/java/org/myeslib/util/jdbi/UnitOfWorkJournalDao.java // public interface UnitOfWorkJournalDao<K> { // // void append(K id, UnitOfWork uow); // // } // Path: myeslib-jdbi/src/main/java/org/myeslib/jdbi/storage/JdbiUnitOfWorkJournal.java import org.myeslib.core.data.UnitOfWork; import org.myeslib.core.storage.UnitOfWorkJournal; import org.myeslib.util.jdbi.UnitOfWorkJournalDao; import com.google.inject.Inject; package org.myeslib.jdbi.storage; public class JdbiUnitOfWorkJournal<K> implements UnitOfWorkJournal<K> { @Inject public JdbiUnitOfWorkJournal(UnitOfWorkJournalDao<K> dao) { this.dao = dao; } private final UnitOfWorkJournalDao<K> dao; /* * (non-Javadoc) * @see org.myeslib.core.storage.UnitOfWorkJournal#append(java.lang.Object, org.myeslib.core.data.UnitOfWork) */
public void append(final K id, final UnitOfWork uow) {
rodolfodpk/myeslib
myeslib-hazelcast/src/main/java/org/myeslib/hazelcast/storage/HzUnitOfWorkJournal.java
// Path: myeslib-core/src/main/java/org/myeslib/core/data/AggregateRootHistory.java // @SuppressWarnings("serial") // @Data // public class AggregateRootHistory implements Serializable { // // private final List<UnitOfWork> unitsOfWork; // private final Set<UnitOfWork> persisted; // // public AggregateRootHistory() { // this.unitsOfWork = new LinkedList<>(); // this.persisted = new LinkedHashSet<>(); // } // // public List<Event> getAllEvents() { // return getEventsAfterUntil(0, Long.MAX_VALUE); // } // // public List<Event> getEventsAfterUntil(long afterVersion, long untilVersion){ // List<Event> events = new LinkedList<>(); // for (UnitOfWork t : unitsOfWork) { // if (t.getVersion() > afterVersion && t.getVersion() <= untilVersion){ // for (Event event : t.getEvents()) { // events.add(event); // } // } // } // return events; // } // // public List<Event> getEventsUntil(long version){ // List<Event> events = new LinkedList<>(); // for (UnitOfWork t : unitsOfWork) { // if (t.getVersion() <= version){ // for (Event event : t.getEvents()) { // events.add(event); // } // } // } // return events; // } // // public Long getLastVersion() { // return unitsOfWork.size()==0 ? 0 : unitsOfWork.get(unitsOfWork.size()-1).getVersion(); // } // // public void add(final UnitOfWork transaction) { // checkNotNull(transaction); // unitsOfWork.add(transaction); // } // // public UnitOfWork getLastUnitOfWork() { // return unitsOfWork.get(unitsOfWork.size()-1); // } // // public List<UnitOfWork> getPendingOfPersistence() { // return Lists.newLinkedList(Sets.difference(Sets.newLinkedHashSet(unitsOfWork), persisted)); // } // // public void markAsPersisted(UnitOfWork uow) { // checkArgument(unitsOfWork.contains(uow), "unitOfWork must be part of this AggregateRootHistory in order to be marked as persisted"); // persisted.add(uow); // } // // } // // Path: myeslib-core/src/main/java/org/myeslib/core/data/UnitOfWork.java // @SuppressWarnings("serial") // @Value // public class UnitOfWork implements Comparable<UnitOfWork>, Serializable { // // final UUID id; // final Command command; // final List<? extends Event> events; // final long version; // // public UnitOfWork(UUID id, Command command, Long version, List<? extends Event> events) { // checkNotNull(id, "id cannot be null"); // checkNotNull(command, "command cannot be null"); // checkArgument(command.getTargetVersion()>=0, "target version must be >= 0"); // checkArgument(version>0, "invalid version"); // checkNotNull(events, "events cannot be null"); // for (Event e: events){ // checkNotNull(e, "event within events list cannot be null"); // } // this.id = id; // this.command = command; // this.version = version; // this.events = events; // } // // public static UnitOfWork create(UUID id, Command command, List<? extends Event> newEvents) { // checkNotNull(command.getTargetVersion(), "target version cannot be null"); // checkArgument(command.getTargetVersion()>=0, "target version must be >= 0"); // return new UnitOfWork(id, command, command.getTargetVersion()+1, newEvents); // } // // public List<Event> getEvents(){ // List<Event> result = new LinkedList<>(); // for (Event event : events) { // result.add(event); // } // return result; // } // // public int compareTo(UnitOfWork other) { // if (version < other.version) { // return -1; // } else if (version > other.version) { // return 1; // } // return 0; // } // // public Long getTargetVersion() { // return command.getTargetVersion(); // } // } // // Path: myeslib-core/src/main/java/org/myeslib/core/storage/UnitOfWorkJournal.java // public interface UnitOfWorkJournal<K> { // // public void append(final K id, final UnitOfWork uow) ; // // }
import static com.google.common.base.Preconditions.checkNotNull; import java.util.ConcurrentModificationException; import lombok.extern.slf4j.Slf4j; import org.myeslib.core.data.AggregateRootHistory; import org.myeslib.core.data.UnitOfWork; import org.myeslib.core.storage.UnitOfWorkJournal; import com.google.inject.Inject; import com.hazelcast.core.IMap;
package org.myeslib.hazelcast.storage; @Slf4j public class HzUnitOfWorkJournal<K> implements UnitOfWorkJournal<K> {
// Path: myeslib-core/src/main/java/org/myeslib/core/data/AggregateRootHistory.java // @SuppressWarnings("serial") // @Data // public class AggregateRootHistory implements Serializable { // // private final List<UnitOfWork> unitsOfWork; // private final Set<UnitOfWork> persisted; // // public AggregateRootHistory() { // this.unitsOfWork = new LinkedList<>(); // this.persisted = new LinkedHashSet<>(); // } // // public List<Event> getAllEvents() { // return getEventsAfterUntil(0, Long.MAX_VALUE); // } // // public List<Event> getEventsAfterUntil(long afterVersion, long untilVersion){ // List<Event> events = new LinkedList<>(); // for (UnitOfWork t : unitsOfWork) { // if (t.getVersion() > afterVersion && t.getVersion() <= untilVersion){ // for (Event event : t.getEvents()) { // events.add(event); // } // } // } // return events; // } // // public List<Event> getEventsUntil(long version){ // List<Event> events = new LinkedList<>(); // for (UnitOfWork t : unitsOfWork) { // if (t.getVersion() <= version){ // for (Event event : t.getEvents()) { // events.add(event); // } // } // } // return events; // } // // public Long getLastVersion() { // return unitsOfWork.size()==0 ? 0 : unitsOfWork.get(unitsOfWork.size()-1).getVersion(); // } // // public void add(final UnitOfWork transaction) { // checkNotNull(transaction); // unitsOfWork.add(transaction); // } // // public UnitOfWork getLastUnitOfWork() { // return unitsOfWork.get(unitsOfWork.size()-1); // } // // public List<UnitOfWork> getPendingOfPersistence() { // return Lists.newLinkedList(Sets.difference(Sets.newLinkedHashSet(unitsOfWork), persisted)); // } // // public void markAsPersisted(UnitOfWork uow) { // checkArgument(unitsOfWork.contains(uow), "unitOfWork must be part of this AggregateRootHistory in order to be marked as persisted"); // persisted.add(uow); // } // // } // // Path: myeslib-core/src/main/java/org/myeslib/core/data/UnitOfWork.java // @SuppressWarnings("serial") // @Value // public class UnitOfWork implements Comparable<UnitOfWork>, Serializable { // // final UUID id; // final Command command; // final List<? extends Event> events; // final long version; // // public UnitOfWork(UUID id, Command command, Long version, List<? extends Event> events) { // checkNotNull(id, "id cannot be null"); // checkNotNull(command, "command cannot be null"); // checkArgument(command.getTargetVersion()>=0, "target version must be >= 0"); // checkArgument(version>0, "invalid version"); // checkNotNull(events, "events cannot be null"); // for (Event e: events){ // checkNotNull(e, "event within events list cannot be null"); // } // this.id = id; // this.command = command; // this.version = version; // this.events = events; // } // // public static UnitOfWork create(UUID id, Command command, List<? extends Event> newEvents) { // checkNotNull(command.getTargetVersion(), "target version cannot be null"); // checkArgument(command.getTargetVersion()>=0, "target version must be >= 0"); // return new UnitOfWork(id, command, command.getTargetVersion()+1, newEvents); // } // // public List<Event> getEvents(){ // List<Event> result = new LinkedList<>(); // for (Event event : events) { // result.add(event); // } // return result; // } // // public int compareTo(UnitOfWork other) { // if (version < other.version) { // return -1; // } else if (version > other.version) { // return 1; // } // return 0; // } // // public Long getTargetVersion() { // return command.getTargetVersion(); // } // } // // Path: myeslib-core/src/main/java/org/myeslib/core/storage/UnitOfWorkJournal.java // public interface UnitOfWorkJournal<K> { // // public void append(final K id, final UnitOfWork uow) ; // // } // Path: myeslib-hazelcast/src/main/java/org/myeslib/hazelcast/storage/HzUnitOfWorkJournal.java import static com.google.common.base.Preconditions.checkNotNull; import java.util.ConcurrentModificationException; import lombok.extern.slf4j.Slf4j; import org.myeslib.core.data.AggregateRootHistory; import org.myeslib.core.data.UnitOfWork; import org.myeslib.core.storage.UnitOfWorkJournal; import com.google.inject.Inject; import com.hazelcast.core.IMap; package org.myeslib.hazelcast.storage; @Slf4j public class HzUnitOfWorkJournal<K> implements UnitOfWorkJournal<K> {
private final IMap<K, AggregateRootHistory> pastTransactionsMap ;
rodolfodpk/myeslib
myeslib-hazelcast/src/main/java/org/myeslib/hazelcast/storage/HzUnitOfWorkJournal.java
// Path: myeslib-core/src/main/java/org/myeslib/core/data/AggregateRootHistory.java // @SuppressWarnings("serial") // @Data // public class AggregateRootHistory implements Serializable { // // private final List<UnitOfWork> unitsOfWork; // private final Set<UnitOfWork> persisted; // // public AggregateRootHistory() { // this.unitsOfWork = new LinkedList<>(); // this.persisted = new LinkedHashSet<>(); // } // // public List<Event> getAllEvents() { // return getEventsAfterUntil(0, Long.MAX_VALUE); // } // // public List<Event> getEventsAfterUntil(long afterVersion, long untilVersion){ // List<Event> events = new LinkedList<>(); // for (UnitOfWork t : unitsOfWork) { // if (t.getVersion() > afterVersion && t.getVersion() <= untilVersion){ // for (Event event : t.getEvents()) { // events.add(event); // } // } // } // return events; // } // // public List<Event> getEventsUntil(long version){ // List<Event> events = new LinkedList<>(); // for (UnitOfWork t : unitsOfWork) { // if (t.getVersion() <= version){ // for (Event event : t.getEvents()) { // events.add(event); // } // } // } // return events; // } // // public Long getLastVersion() { // return unitsOfWork.size()==0 ? 0 : unitsOfWork.get(unitsOfWork.size()-1).getVersion(); // } // // public void add(final UnitOfWork transaction) { // checkNotNull(transaction); // unitsOfWork.add(transaction); // } // // public UnitOfWork getLastUnitOfWork() { // return unitsOfWork.get(unitsOfWork.size()-1); // } // // public List<UnitOfWork> getPendingOfPersistence() { // return Lists.newLinkedList(Sets.difference(Sets.newLinkedHashSet(unitsOfWork), persisted)); // } // // public void markAsPersisted(UnitOfWork uow) { // checkArgument(unitsOfWork.contains(uow), "unitOfWork must be part of this AggregateRootHistory in order to be marked as persisted"); // persisted.add(uow); // } // // } // // Path: myeslib-core/src/main/java/org/myeslib/core/data/UnitOfWork.java // @SuppressWarnings("serial") // @Value // public class UnitOfWork implements Comparable<UnitOfWork>, Serializable { // // final UUID id; // final Command command; // final List<? extends Event> events; // final long version; // // public UnitOfWork(UUID id, Command command, Long version, List<? extends Event> events) { // checkNotNull(id, "id cannot be null"); // checkNotNull(command, "command cannot be null"); // checkArgument(command.getTargetVersion()>=0, "target version must be >= 0"); // checkArgument(version>0, "invalid version"); // checkNotNull(events, "events cannot be null"); // for (Event e: events){ // checkNotNull(e, "event within events list cannot be null"); // } // this.id = id; // this.command = command; // this.version = version; // this.events = events; // } // // public static UnitOfWork create(UUID id, Command command, List<? extends Event> newEvents) { // checkNotNull(command.getTargetVersion(), "target version cannot be null"); // checkArgument(command.getTargetVersion()>=0, "target version must be >= 0"); // return new UnitOfWork(id, command, command.getTargetVersion()+1, newEvents); // } // // public List<Event> getEvents(){ // List<Event> result = new LinkedList<>(); // for (Event event : events) { // result.add(event); // } // return result; // } // // public int compareTo(UnitOfWork other) { // if (version < other.version) { // return -1; // } else if (version > other.version) { // return 1; // } // return 0; // } // // public Long getTargetVersion() { // return command.getTargetVersion(); // } // } // // Path: myeslib-core/src/main/java/org/myeslib/core/storage/UnitOfWorkJournal.java // public interface UnitOfWorkJournal<K> { // // public void append(final K id, final UnitOfWork uow) ; // // }
import static com.google.common.base.Preconditions.checkNotNull; import java.util.ConcurrentModificationException; import lombok.extern.slf4j.Slf4j; import org.myeslib.core.data.AggregateRootHistory; import org.myeslib.core.data.UnitOfWork; import org.myeslib.core.storage.UnitOfWorkJournal; import com.google.inject.Inject; import com.hazelcast.core.IMap;
package org.myeslib.hazelcast.storage; @Slf4j public class HzUnitOfWorkJournal<K> implements UnitOfWorkJournal<K> { private final IMap<K, AggregateRootHistory> pastTransactionsMap ; @Inject public HzUnitOfWorkJournal(IMap<K, AggregateRootHistory> pastTransactionsMap) { checkNotNull(pastTransactionsMap); this.pastTransactionsMap = pastTransactionsMap; } /* * (non-Javadoc) * @see org.myeslib.core.storage.UnitOfWorkJournal#append(java.lang.Object, org.myeslib.core.data.UnitOfWork) */
// Path: myeslib-core/src/main/java/org/myeslib/core/data/AggregateRootHistory.java // @SuppressWarnings("serial") // @Data // public class AggregateRootHistory implements Serializable { // // private final List<UnitOfWork> unitsOfWork; // private final Set<UnitOfWork> persisted; // // public AggregateRootHistory() { // this.unitsOfWork = new LinkedList<>(); // this.persisted = new LinkedHashSet<>(); // } // // public List<Event> getAllEvents() { // return getEventsAfterUntil(0, Long.MAX_VALUE); // } // // public List<Event> getEventsAfterUntil(long afterVersion, long untilVersion){ // List<Event> events = new LinkedList<>(); // for (UnitOfWork t : unitsOfWork) { // if (t.getVersion() > afterVersion && t.getVersion() <= untilVersion){ // for (Event event : t.getEvents()) { // events.add(event); // } // } // } // return events; // } // // public List<Event> getEventsUntil(long version){ // List<Event> events = new LinkedList<>(); // for (UnitOfWork t : unitsOfWork) { // if (t.getVersion() <= version){ // for (Event event : t.getEvents()) { // events.add(event); // } // } // } // return events; // } // // public Long getLastVersion() { // return unitsOfWork.size()==0 ? 0 : unitsOfWork.get(unitsOfWork.size()-1).getVersion(); // } // // public void add(final UnitOfWork transaction) { // checkNotNull(transaction); // unitsOfWork.add(transaction); // } // // public UnitOfWork getLastUnitOfWork() { // return unitsOfWork.get(unitsOfWork.size()-1); // } // // public List<UnitOfWork> getPendingOfPersistence() { // return Lists.newLinkedList(Sets.difference(Sets.newLinkedHashSet(unitsOfWork), persisted)); // } // // public void markAsPersisted(UnitOfWork uow) { // checkArgument(unitsOfWork.contains(uow), "unitOfWork must be part of this AggregateRootHistory in order to be marked as persisted"); // persisted.add(uow); // } // // } // // Path: myeslib-core/src/main/java/org/myeslib/core/data/UnitOfWork.java // @SuppressWarnings("serial") // @Value // public class UnitOfWork implements Comparable<UnitOfWork>, Serializable { // // final UUID id; // final Command command; // final List<? extends Event> events; // final long version; // // public UnitOfWork(UUID id, Command command, Long version, List<? extends Event> events) { // checkNotNull(id, "id cannot be null"); // checkNotNull(command, "command cannot be null"); // checkArgument(command.getTargetVersion()>=0, "target version must be >= 0"); // checkArgument(version>0, "invalid version"); // checkNotNull(events, "events cannot be null"); // for (Event e: events){ // checkNotNull(e, "event within events list cannot be null"); // } // this.id = id; // this.command = command; // this.version = version; // this.events = events; // } // // public static UnitOfWork create(UUID id, Command command, List<? extends Event> newEvents) { // checkNotNull(command.getTargetVersion(), "target version cannot be null"); // checkArgument(command.getTargetVersion()>=0, "target version must be >= 0"); // return new UnitOfWork(id, command, command.getTargetVersion()+1, newEvents); // } // // public List<Event> getEvents(){ // List<Event> result = new LinkedList<>(); // for (Event event : events) { // result.add(event); // } // return result; // } // // public int compareTo(UnitOfWork other) { // if (version < other.version) { // return -1; // } else if (version > other.version) { // return 1; // } // return 0; // } // // public Long getTargetVersion() { // return command.getTargetVersion(); // } // } // // Path: myeslib-core/src/main/java/org/myeslib/core/storage/UnitOfWorkJournal.java // public interface UnitOfWorkJournal<K> { // // public void append(final K id, final UnitOfWork uow) ; // // } // Path: myeslib-hazelcast/src/main/java/org/myeslib/hazelcast/storage/HzUnitOfWorkJournal.java import static com.google.common.base.Preconditions.checkNotNull; import java.util.ConcurrentModificationException; import lombok.extern.slf4j.Slf4j; import org.myeslib.core.data.AggregateRootHistory; import org.myeslib.core.data.UnitOfWork; import org.myeslib.core.storage.UnitOfWorkJournal; import com.google.inject.Inject; import com.hazelcast.core.IMap; package org.myeslib.hazelcast.storage; @Slf4j public class HzUnitOfWorkJournal<K> implements UnitOfWorkJournal<K> { private final IMap<K, AggregateRootHistory> pastTransactionsMap ; @Inject public HzUnitOfWorkJournal(IMap<K, AggregateRootHistory> pastTransactionsMap) { checkNotNull(pastTransactionsMap); this.pastTransactionsMap = pastTransactionsMap; } /* * (non-Javadoc) * @see org.myeslib.core.storage.UnitOfWorkJournal#append(java.lang.Object, org.myeslib.core.data.UnitOfWork) */
public void append(final K id, final UnitOfWork uow) {
rodolfodpk/myeslib
inventory-hazelcast/src/main/java/org/myeslib/example/hazelcast/routes/ReceiveCommandsAsJsonRoute.java
// Path: myeslib-core/src/main/java/org/myeslib/core/Command.java // public interface Command extends Serializable { // // UUID getCommandId(); // Long getTargetVersion(); // // } // // Path: myeslib-util/src/main/java/org/myeslib/util/gson/CommandFromStringFunction.java // public class CommandFromStringFunction implements Function<String, Command>{ // private final Gson gson; // @Inject // public CommandFromStringFunction(Gson gson){ // this.gson = gson; // } // @Override // public Command apply(String asJson) { // return gson.fromJson(asJson, Command.class); // } // }
import lombok.RequiredArgsConstructor; import org.apache.camel.Exchange; import org.apache.camel.Processor; import org.apache.camel.builder.RouteBuilder; import org.myeslib.core.Command; import org.myeslib.util.gson.CommandFromStringFunction; import com.google.inject.Inject;
package org.myeslib.example.hazelcast.routes; @RequiredArgsConstructor(onConstructor=@__(@Inject)) public class ReceiveCommandsAsJsonRoute extends RouteBuilder { final String sourceUri; final String targetUri;
// Path: myeslib-core/src/main/java/org/myeslib/core/Command.java // public interface Command extends Serializable { // // UUID getCommandId(); // Long getTargetVersion(); // // } // // Path: myeslib-util/src/main/java/org/myeslib/util/gson/CommandFromStringFunction.java // public class CommandFromStringFunction implements Function<String, Command>{ // private final Gson gson; // @Inject // public CommandFromStringFunction(Gson gson){ // this.gson = gson; // } // @Override // public Command apply(String asJson) { // return gson.fromJson(asJson, Command.class); // } // } // Path: inventory-hazelcast/src/main/java/org/myeslib/example/hazelcast/routes/ReceiveCommandsAsJsonRoute.java import lombok.RequiredArgsConstructor; import org.apache.camel.Exchange; import org.apache.camel.Processor; import org.apache.camel.builder.RouteBuilder; import org.myeslib.core.Command; import org.myeslib.util.gson.CommandFromStringFunction; import com.google.inject.Inject; package org.myeslib.example.hazelcast.routes; @RequiredArgsConstructor(onConstructor=@__(@Inject)) public class ReceiveCommandsAsJsonRoute extends RouteBuilder { final String sourceUri; final String targetUri;
final CommandFromStringFunction commandFromStringFunction;
rodolfodpk/myeslib
inventory-hazelcast/src/main/java/org/myeslib/example/hazelcast/routes/ReceiveCommandsAsJsonRoute.java
// Path: myeslib-core/src/main/java/org/myeslib/core/Command.java // public interface Command extends Serializable { // // UUID getCommandId(); // Long getTargetVersion(); // // } // // Path: myeslib-util/src/main/java/org/myeslib/util/gson/CommandFromStringFunction.java // public class CommandFromStringFunction implements Function<String, Command>{ // private final Gson gson; // @Inject // public CommandFromStringFunction(Gson gson){ // this.gson = gson; // } // @Override // public Command apply(String asJson) { // return gson.fromJson(asJson, Command.class); // } // }
import lombok.RequiredArgsConstructor; import org.apache.camel.Exchange; import org.apache.camel.Processor; import org.apache.camel.builder.RouteBuilder; import org.myeslib.core.Command; import org.myeslib.util.gson.CommandFromStringFunction; import com.google.inject.Inject;
package org.myeslib.example.hazelcast.routes; @RequiredArgsConstructor(onConstructor=@__(@Inject)) public class ReceiveCommandsAsJsonRoute extends RouteBuilder { final String sourceUri; final String targetUri; final CommandFromStringFunction commandFromStringFunction; @Override public void configure() throws Exception { from(sourceUri) .streamCaching() .routeId("receive-commands-as-json") .process(new Processor() { @Override public void process(Exchange e) throws Exception { String body = e.getIn().getBody(String.class);
// Path: myeslib-core/src/main/java/org/myeslib/core/Command.java // public interface Command extends Serializable { // // UUID getCommandId(); // Long getTargetVersion(); // // } // // Path: myeslib-util/src/main/java/org/myeslib/util/gson/CommandFromStringFunction.java // public class CommandFromStringFunction implements Function<String, Command>{ // private final Gson gson; // @Inject // public CommandFromStringFunction(Gson gson){ // this.gson = gson; // } // @Override // public Command apply(String asJson) { // return gson.fromJson(asJson, Command.class); // } // } // Path: inventory-hazelcast/src/main/java/org/myeslib/example/hazelcast/routes/ReceiveCommandsAsJsonRoute.java import lombok.RequiredArgsConstructor; import org.apache.camel.Exchange; import org.apache.camel.Processor; import org.apache.camel.builder.RouteBuilder; import org.myeslib.core.Command; import org.myeslib.util.gson.CommandFromStringFunction; import com.google.inject.Inject; package org.myeslib.example.hazelcast.routes; @RequiredArgsConstructor(onConstructor=@__(@Inject)) public class ReceiveCommandsAsJsonRoute extends RouteBuilder { final String sourceUri; final String targetUri; final CommandFromStringFunction commandFromStringFunction; @Override public void configure() throws Exception { from(sourceUri) .streamCaching() .routeId("receive-commands-as-json") .process(new Processor() { @Override public void process(Exchange e) throws Exception { String body = e.getIn().getBody(String.class);
e.getOut().setBody(commandFromStringFunction.apply(body), Command.class);
rodolfodpk/myeslib
myeslib-core/src/main/java/org/myeslib/core/data/test/EventJustForTest.java
// Path: myeslib-core/src/main/java/org/myeslib/core/Event.java // public interface Event extends Serializable { // // }
import java.util.UUID; import lombok.Value; import org.myeslib.core.Event;
package org.myeslib.core.data.test; @SuppressWarnings("serial") @Value
// Path: myeslib-core/src/main/java/org/myeslib/core/Event.java // public interface Event extends Serializable { // // } // Path: myeslib-core/src/main/java/org/myeslib/core/data/test/EventJustForTest.java import java.util.UUID; import lombok.Value; import org.myeslib.core.Event; package org.myeslib.core.data.test; @SuppressWarnings("serial") @Value
public class EventJustForTest implements Event {
rodolfodpk/myeslib
myeslib-util/src/main/java/org/myeslib/util/hazelcast/HzJobLocker.java
// Path: myeslib-util/src/main/java/org/myeslib/util/TimeUnitHelper.java // @AllArgsConstructor // public class TimeUnitHelper { // // private static final Pattern pattern = Pattern.compile("([0-9]+)(s|m|h)"); // // private final String duration; // // public TimeUnit getDurationTime() { // Matcher m = pattern.matcher(duration.trim()); // if (m.matches()){ // if ("s".equals(m.group(2))){ // return TimeUnit.SECONDS; // } else if ("m".equals(m.group(2))){ // return TimeUnit.MINUTES; // } if ("h".equals(m.group(2))){ // return TimeUnit.HOURS; // } else { // throw new IllegalArgumentException(String.format("1 Bad format for interval [%s]", duration)); // } // } else { // throw new IllegalArgumentException(String.format("2 Bad format for interval [%s]", duration)); // } // } // // public Long getDurationAsNumber() { // Matcher m = pattern.matcher(duration.trim()); // if (m.matches()){ // return new Long(m.group(1)); // } else { // throw new IllegalArgumentException(String.format("3 Bad format for interval [%s]", duration)); // } // } // // }
import java.util.concurrent.TimeUnit; import lombok.extern.slf4j.Slf4j; import org.myeslib.util.TimeUnitHelper; import com.google.inject.Inject; import com.google.inject.name.Named; import com.hazelcast.core.HazelcastInstance; import com.hazelcast.core.IMap;
package org.myeslib.util.hazelcast; @Slf4j public class HzJobLocker { public static final String LOCK_FAILED_MSG = "Cannot lock. May be there is another job instance working concurrently"; private static final String TARGET_MAP = "distributedLockMap"; @Inject public HzJobLocker(HazelcastInstance instance, @Named("job.id") String jobId, @Named("job.lock.duration") String jobDuration) { this.instance = instance; this.jobId = jobId; this.jobDuration = jobDuration; } private final HazelcastInstance instance; private final String jobId; private final String jobDuration; public boolean lock() { boolean success ; try {
// Path: myeslib-util/src/main/java/org/myeslib/util/TimeUnitHelper.java // @AllArgsConstructor // public class TimeUnitHelper { // // private static final Pattern pattern = Pattern.compile("([0-9]+)(s|m|h)"); // // private final String duration; // // public TimeUnit getDurationTime() { // Matcher m = pattern.matcher(duration.trim()); // if (m.matches()){ // if ("s".equals(m.group(2))){ // return TimeUnit.SECONDS; // } else if ("m".equals(m.group(2))){ // return TimeUnit.MINUTES; // } if ("h".equals(m.group(2))){ // return TimeUnit.HOURS; // } else { // throw new IllegalArgumentException(String.format("1 Bad format for interval [%s]", duration)); // } // } else { // throw new IllegalArgumentException(String.format("2 Bad format for interval [%s]", duration)); // } // } // // public Long getDurationAsNumber() { // Matcher m = pattern.matcher(duration.trim()); // if (m.matches()){ // return new Long(m.group(1)); // } else { // throw new IllegalArgumentException(String.format("3 Bad format for interval [%s]", duration)); // } // } // // } // Path: myeslib-util/src/main/java/org/myeslib/util/hazelcast/HzJobLocker.java import java.util.concurrent.TimeUnit; import lombok.extern.slf4j.Slf4j; import org.myeslib.util.TimeUnitHelper; import com.google.inject.Inject; import com.google.inject.name.Named; import com.hazelcast.core.HazelcastInstance; import com.hazelcast.core.IMap; package org.myeslib.util.hazelcast; @Slf4j public class HzJobLocker { public static final String LOCK_FAILED_MSG = "Cannot lock. May be there is another job instance working concurrently"; private static final String TARGET_MAP = "distributedLockMap"; @Inject public HzJobLocker(HazelcastInstance instance, @Named("job.id") String jobId, @Named("job.lock.duration") String jobDuration) { this.instance = instance; this.jobId = jobId; this.jobDuration = jobDuration; } private final HazelcastInstance instance; private final String jobId; private final String jobDuration; public boolean lock() { boolean success ; try {
TimeUnitHelper helper = new TimeUnitHelper(jobDuration);
rodolfodpk/myeslib
myeslib-jdbi/src/test/java/org/myeslib/jdbi/storage/JdbiUnitOfWorkJournalTest.java
// Path: myeslib-core/src/main/java/org/myeslib/core/Command.java // public interface Command extends Serializable { // // UUID getCommandId(); // Long getTargetVersion(); // // } // // Path: myeslib-core/src/main/java/org/myeslib/core/Event.java // public interface Event extends Serializable { // // } // // Path: myeslib-core/src/main/java/org/myeslib/core/data/UnitOfWork.java // @SuppressWarnings("serial") // @Value // public class UnitOfWork implements Comparable<UnitOfWork>, Serializable { // // final UUID id; // final Command command; // final List<? extends Event> events; // final long version; // // public UnitOfWork(UUID id, Command command, Long version, List<? extends Event> events) { // checkNotNull(id, "id cannot be null"); // checkNotNull(command, "command cannot be null"); // checkArgument(command.getTargetVersion()>=0, "target version must be >= 0"); // checkArgument(version>0, "invalid version"); // checkNotNull(events, "events cannot be null"); // for (Event e: events){ // checkNotNull(e, "event within events list cannot be null"); // } // this.id = id; // this.command = command; // this.version = version; // this.events = events; // } // // public static UnitOfWork create(UUID id, Command command, List<? extends Event> newEvents) { // checkNotNull(command.getTargetVersion(), "target version cannot be null"); // checkArgument(command.getTargetVersion()>=0, "target version must be >= 0"); // return new UnitOfWork(id, command, command.getTargetVersion()+1, newEvents); // } // // public List<Event> getEvents(){ // List<Event> result = new LinkedList<>(); // for (Event event : events) { // result.add(event); // } // return result; // } // // public int compareTo(UnitOfWork other) { // if (version < other.version) { // return -1; // } else if (version > other.version) { // return 1; // } // return 0; // } // // public Long getTargetVersion() { // return command.getTargetVersion(); // } // } // // Path: inventory-aggregate-root/src/main/java/org/myeslib/example/SampleDomain.java // @Value // public static class IncreaseInventory implements Command { // @NonNull // UUID commandId; // @NonNull // UUID id; // @NonNull // Integer howMany; // Long targetVersion; // } // // Path: inventory-aggregate-root/src/main/java/org/myeslib/example/SampleDomain.java // @Value // public static class InventoryIncreased implements Event { // @NonNull // UUID id; // @NonNull // Integer howMany; // } // // Path: myeslib-util/src/main/java/org/myeslib/util/jdbi/UnitOfWorkJournalDao.java // public interface UnitOfWorkJournalDao<K> { // // void append(K id, UnitOfWork uow); // // }
import static org.mockito.Mockito.verify; import java.util.Arrays; import java.util.UUID; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.myeslib.core.Command; import org.myeslib.core.Event; import org.myeslib.core.data.UnitOfWork; import org.myeslib.example.SampleDomain.IncreaseInventory; import org.myeslib.example.SampleDomain.InventoryIncreased; import org.myeslib.util.jdbi.UnitOfWorkJournalDao;
package org.myeslib.jdbi.storage; @RunWith(MockitoJUnitRunner.class) public class JdbiUnitOfWorkJournalTest { @Mock
// Path: myeslib-core/src/main/java/org/myeslib/core/Command.java // public interface Command extends Serializable { // // UUID getCommandId(); // Long getTargetVersion(); // // } // // Path: myeslib-core/src/main/java/org/myeslib/core/Event.java // public interface Event extends Serializable { // // } // // Path: myeslib-core/src/main/java/org/myeslib/core/data/UnitOfWork.java // @SuppressWarnings("serial") // @Value // public class UnitOfWork implements Comparable<UnitOfWork>, Serializable { // // final UUID id; // final Command command; // final List<? extends Event> events; // final long version; // // public UnitOfWork(UUID id, Command command, Long version, List<? extends Event> events) { // checkNotNull(id, "id cannot be null"); // checkNotNull(command, "command cannot be null"); // checkArgument(command.getTargetVersion()>=0, "target version must be >= 0"); // checkArgument(version>0, "invalid version"); // checkNotNull(events, "events cannot be null"); // for (Event e: events){ // checkNotNull(e, "event within events list cannot be null"); // } // this.id = id; // this.command = command; // this.version = version; // this.events = events; // } // // public static UnitOfWork create(UUID id, Command command, List<? extends Event> newEvents) { // checkNotNull(command.getTargetVersion(), "target version cannot be null"); // checkArgument(command.getTargetVersion()>=0, "target version must be >= 0"); // return new UnitOfWork(id, command, command.getTargetVersion()+1, newEvents); // } // // public List<Event> getEvents(){ // List<Event> result = new LinkedList<>(); // for (Event event : events) { // result.add(event); // } // return result; // } // // public int compareTo(UnitOfWork other) { // if (version < other.version) { // return -1; // } else if (version > other.version) { // return 1; // } // return 0; // } // // public Long getTargetVersion() { // return command.getTargetVersion(); // } // } // // Path: inventory-aggregate-root/src/main/java/org/myeslib/example/SampleDomain.java // @Value // public static class IncreaseInventory implements Command { // @NonNull // UUID commandId; // @NonNull // UUID id; // @NonNull // Integer howMany; // Long targetVersion; // } // // Path: inventory-aggregate-root/src/main/java/org/myeslib/example/SampleDomain.java // @Value // public static class InventoryIncreased implements Event { // @NonNull // UUID id; // @NonNull // Integer howMany; // } // // Path: myeslib-util/src/main/java/org/myeslib/util/jdbi/UnitOfWorkJournalDao.java // public interface UnitOfWorkJournalDao<K> { // // void append(K id, UnitOfWork uow); // // } // Path: myeslib-jdbi/src/test/java/org/myeslib/jdbi/storage/JdbiUnitOfWorkJournalTest.java import static org.mockito.Mockito.verify; import java.util.Arrays; import java.util.UUID; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.myeslib.core.Command; import org.myeslib.core.Event; import org.myeslib.core.data.UnitOfWork; import org.myeslib.example.SampleDomain.IncreaseInventory; import org.myeslib.example.SampleDomain.InventoryIncreased; import org.myeslib.util.jdbi.UnitOfWorkJournalDao; package org.myeslib.jdbi.storage; @RunWith(MockitoJUnitRunner.class) public class JdbiUnitOfWorkJournalTest { @Mock
UnitOfWorkJournalDao<UUID> dao;
rodolfodpk/myeslib
myeslib-jdbi/src/test/java/org/myeslib/jdbi/storage/JdbiUnitOfWorkJournalTest.java
// Path: myeslib-core/src/main/java/org/myeslib/core/Command.java // public interface Command extends Serializable { // // UUID getCommandId(); // Long getTargetVersion(); // // } // // Path: myeslib-core/src/main/java/org/myeslib/core/Event.java // public interface Event extends Serializable { // // } // // Path: myeslib-core/src/main/java/org/myeslib/core/data/UnitOfWork.java // @SuppressWarnings("serial") // @Value // public class UnitOfWork implements Comparable<UnitOfWork>, Serializable { // // final UUID id; // final Command command; // final List<? extends Event> events; // final long version; // // public UnitOfWork(UUID id, Command command, Long version, List<? extends Event> events) { // checkNotNull(id, "id cannot be null"); // checkNotNull(command, "command cannot be null"); // checkArgument(command.getTargetVersion()>=0, "target version must be >= 0"); // checkArgument(version>0, "invalid version"); // checkNotNull(events, "events cannot be null"); // for (Event e: events){ // checkNotNull(e, "event within events list cannot be null"); // } // this.id = id; // this.command = command; // this.version = version; // this.events = events; // } // // public static UnitOfWork create(UUID id, Command command, List<? extends Event> newEvents) { // checkNotNull(command.getTargetVersion(), "target version cannot be null"); // checkArgument(command.getTargetVersion()>=0, "target version must be >= 0"); // return new UnitOfWork(id, command, command.getTargetVersion()+1, newEvents); // } // // public List<Event> getEvents(){ // List<Event> result = new LinkedList<>(); // for (Event event : events) { // result.add(event); // } // return result; // } // // public int compareTo(UnitOfWork other) { // if (version < other.version) { // return -1; // } else if (version > other.version) { // return 1; // } // return 0; // } // // public Long getTargetVersion() { // return command.getTargetVersion(); // } // } // // Path: inventory-aggregate-root/src/main/java/org/myeslib/example/SampleDomain.java // @Value // public static class IncreaseInventory implements Command { // @NonNull // UUID commandId; // @NonNull // UUID id; // @NonNull // Integer howMany; // Long targetVersion; // } // // Path: inventory-aggregate-root/src/main/java/org/myeslib/example/SampleDomain.java // @Value // public static class InventoryIncreased implements Event { // @NonNull // UUID id; // @NonNull // Integer howMany; // } // // Path: myeslib-util/src/main/java/org/myeslib/util/jdbi/UnitOfWorkJournalDao.java // public interface UnitOfWorkJournalDao<K> { // // void append(K id, UnitOfWork uow); // // }
import static org.mockito.Mockito.verify; import java.util.Arrays; import java.util.UUID; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.myeslib.core.Command; import org.myeslib.core.Event; import org.myeslib.core.data.UnitOfWork; import org.myeslib.example.SampleDomain.IncreaseInventory; import org.myeslib.example.SampleDomain.InventoryIncreased; import org.myeslib.util.jdbi.UnitOfWorkJournalDao;
package org.myeslib.jdbi.storage; @RunWith(MockitoJUnitRunner.class) public class JdbiUnitOfWorkJournalTest { @Mock UnitOfWorkJournalDao<UUID> dao; @Test public void insert() { JdbiUnitOfWorkJournal<UUID> writer = new JdbiUnitOfWorkJournal<>(dao); UUID id = UUID.randomUUID();
// Path: myeslib-core/src/main/java/org/myeslib/core/Command.java // public interface Command extends Serializable { // // UUID getCommandId(); // Long getTargetVersion(); // // } // // Path: myeslib-core/src/main/java/org/myeslib/core/Event.java // public interface Event extends Serializable { // // } // // Path: myeslib-core/src/main/java/org/myeslib/core/data/UnitOfWork.java // @SuppressWarnings("serial") // @Value // public class UnitOfWork implements Comparable<UnitOfWork>, Serializable { // // final UUID id; // final Command command; // final List<? extends Event> events; // final long version; // // public UnitOfWork(UUID id, Command command, Long version, List<? extends Event> events) { // checkNotNull(id, "id cannot be null"); // checkNotNull(command, "command cannot be null"); // checkArgument(command.getTargetVersion()>=0, "target version must be >= 0"); // checkArgument(version>0, "invalid version"); // checkNotNull(events, "events cannot be null"); // for (Event e: events){ // checkNotNull(e, "event within events list cannot be null"); // } // this.id = id; // this.command = command; // this.version = version; // this.events = events; // } // // public static UnitOfWork create(UUID id, Command command, List<? extends Event> newEvents) { // checkNotNull(command.getTargetVersion(), "target version cannot be null"); // checkArgument(command.getTargetVersion()>=0, "target version must be >= 0"); // return new UnitOfWork(id, command, command.getTargetVersion()+1, newEvents); // } // // public List<Event> getEvents(){ // List<Event> result = new LinkedList<>(); // for (Event event : events) { // result.add(event); // } // return result; // } // // public int compareTo(UnitOfWork other) { // if (version < other.version) { // return -1; // } else if (version > other.version) { // return 1; // } // return 0; // } // // public Long getTargetVersion() { // return command.getTargetVersion(); // } // } // // Path: inventory-aggregate-root/src/main/java/org/myeslib/example/SampleDomain.java // @Value // public static class IncreaseInventory implements Command { // @NonNull // UUID commandId; // @NonNull // UUID id; // @NonNull // Integer howMany; // Long targetVersion; // } // // Path: inventory-aggregate-root/src/main/java/org/myeslib/example/SampleDomain.java // @Value // public static class InventoryIncreased implements Event { // @NonNull // UUID id; // @NonNull // Integer howMany; // } // // Path: myeslib-util/src/main/java/org/myeslib/util/jdbi/UnitOfWorkJournalDao.java // public interface UnitOfWorkJournalDao<K> { // // void append(K id, UnitOfWork uow); // // } // Path: myeslib-jdbi/src/test/java/org/myeslib/jdbi/storage/JdbiUnitOfWorkJournalTest.java import static org.mockito.Mockito.verify; import java.util.Arrays; import java.util.UUID; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.myeslib.core.Command; import org.myeslib.core.Event; import org.myeslib.core.data.UnitOfWork; import org.myeslib.example.SampleDomain.IncreaseInventory; import org.myeslib.example.SampleDomain.InventoryIncreased; import org.myeslib.util.jdbi.UnitOfWorkJournalDao; package org.myeslib.jdbi.storage; @RunWith(MockitoJUnitRunner.class) public class JdbiUnitOfWorkJournalTest { @Mock UnitOfWorkJournalDao<UUID> dao; @Test public void insert() { JdbiUnitOfWorkJournal<UUID> writer = new JdbiUnitOfWorkJournal<>(dao); UUID id = UUID.randomUUID();
Command command1 = new IncreaseInventory(UUID.randomUUID(), id, 2, 0l);
rodolfodpk/myeslib
myeslib-jdbi/src/test/java/org/myeslib/jdbi/storage/JdbiUnitOfWorkJournalTest.java
// Path: myeslib-core/src/main/java/org/myeslib/core/Command.java // public interface Command extends Serializable { // // UUID getCommandId(); // Long getTargetVersion(); // // } // // Path: myeslib-core/src/main/java/org/myeslib/core/Event.java // public interface Event extends Serializable { // // } // // Path: myeslib-core/src/main/java/org/myeslib/core/data/UnitOfWork.java // @SuppressWarnings("serial") // @Value // public class UnitOfWork implements Comparable<UnitOfWork>, Serializable { // // final UUID id; // final Command command; // final List<? extends Event> events; // final long version; // // public UnitOfWork(UUID id, Command command, Long version, List<? extends Event> events) { // checkNotNull(id, "id cannot be null"); // checkNotNull(command, "command cannot be null"); // checkArgument(command.getTargetVersion()>=0, "target version must be >= 0"); // checkArgument(version>0, "invalid version"); // checkNotNull(events, "events cannot be null"); // for (Event e: events){ // checkNotNull(e, "event within events list cannot be null"); // } // this.id = id; // this.command = command; // this.version = version; // this.events = events; // } // // public static UnitOfWork create(UUID id, Command command, List<? extends Event> newEvents) { // checkNotNull(command.getTargetVersion(), "target version cannot be null"); // checkArgument(command.getTargetVersion()>=0, "target version must be >= 0"); // return new UnitOfWork(id, command, command.getTargetVersion()+1, newEvents); // } // // public List<Event> getEvents(){ // List<Event> result = new LinkedList<>(); // for (Event event : events) { // result.add(event); // } // return result; // } // // public int compareTo(UnitOfWork other) { // if (version < other.version) { // return -1; // } else if (version > other.version) { // return 1; // } // return 0; // } // // public Long getTargetVersion() { // return command.getTargetVersion(); // } // } // // Path: inventory-aggregate-root/src/main/java/org/myeslib/example/SampleDomain.java // @Value // public static class IncreaseInventory implements Command { // @NonNull // UUID commandId; // @NonNull // UUID id; // @NonNull // Integer howMany; // Long targetVersion; // } // // Path: inventory-aggregate-root/src/main/java/org/myeslib/example/SampleDomain.java // @Value // public static class InventoryIncreased implements Event { // @NonNull // UUID id; // @NonNull // Integer howMany; // } // // Path: myeslib-util/src/main/java/org/myeslib/util/jdbi/UnitOfWorkJournalDao.java // public interface UnitOfWorkJournalDao<K> { // // void append(K id, UnitOfWork uow); // // }
import static org.mockito.Mockito.verify; import java.util.Arrays; import java.util.UUID; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.myeslib.core.Command; import org.myeslib.core.Event; import org.myeslib.core.data.UnitOfWork; import org.myeslib.example.SampleDomain.IncreaseInventory; import org.myeslib.example.SampleDomain.InventoryIncreased; import org.myeslib.util.jdbi.UnitOfWorkJournalDao;
package org.myeslib.jdbi.storage; @RunWith(MockitoJUnitRunner.class) public class JdbiUnitOfWorkJournalTest { @Mock UnitOfWorkJournalDao<UUID> dao; @Test public void insert() { JdbiUnitOfWorkJournal<UUID> writer = new JdbiUnitOfWorkJournal<>(dao); UUID id = UUID.randomUUID();
// Path: myeslib-core/src/main/java/org/myeslib/core/Command.java // public interface Command extends Serializable { // // UUID getCommandId(); // Long getTargetVersion(); // // } // // Path: myeslib-core/src/main/java/org/myeslib/core/Event.java // public interface Event extends Serializable { // // } // // Path: myeslib-core/src/main/java/org/myeslib/core/data/UnitOfWork.java // @SuppressWarnings("serial") // @Value // public class UnitOfWork implements Comparable<UnitOfWork>, Serializable { // // final UUID id; // final Command command; // final List<? extends Event> events; // final long version; // // public UnitOfWork(UUID id, Command command, Long version, List<? extends Event> events) { // checkNotNull(id, "id cannot be null"); // checkNotNull(command, "command cannot be null"); // checkArgument(command.getTargetVersion()>=0, "target version must be >= 0"); // checkArgument(version>0, "invalid version"); // checkNotNull(events, "events cannot be null"); // for (Event e: events){ // checkNotNull(e, "event within events list cannot be null"); // } // this.id = id; // this.command = command; // this.version = version; // this.events = events; // } // // public static UnitOfWork create(UUID id, Command command, List<? extends Event> newEvents) { // checkNotNull(command.getTargetVersion(), "target version cannot be null"); // checkArgument(command.getTargetVersion()>=0, "target version must be >= 0"); // return new UnitOfWork(id, command, command.getTargetVersion()+1, newEvents); // } // // public List<Event> getEvents(){ // List<Event> result = new LinkedList<>(); // for (Event event : events) { // result.add(event); // } // return result; // } // // public int compareTo(UnitOfWork other) { // if (version < other.version) { // return -1; // } else if (version > other.version) { // return 1; // } // return 0; // } // // public Long getTargetVersion() { // return command.getTargetVersion(); // } // } // // Path: inventory-aggregate-root/src/main/java/org/myeslib/example/SampleDomain.java // @Value // public static class IncreaseInventory implements Command { // @NonNull // UUID commandId; // @NonNull // UUID id; // @NonNull // Integer howMany; // Long targetVersion; // } // // Path: inventory-aggregate-root/src/main/java/org/myeslib/example/SampleDomain.java // @Value // public static class InventoryIncreased implements Event { // @NonNull // UUID id; // @NonNull // Integer howMany; // } // // Path: myeslib-util/src/main/java/org/myeslib/util/jdbi/UnitOfWorkJournalDao.java // public interface UnitOfWorkJournalDao<K> { // // void append(K id, UnitOfWork uow); // // } // Path: myeslib-jdbi/src/test/java/org/myeslib/jdbi/storage/JdbiUnitOfWorkJournalTest.java import static org.mockito.Mockito.verify; import java.util.Arrays; import java.util.UUID; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.myeslib.core.Command; import org.myeslib.core.Event; import org.myeslib.core.data.UnitOfWork; import org.myeslib.example.SampleDomain.IncreaseInventory; import org.myeslib.example.SampleDomain.InventoryIncreased; import org.myeslib.util.jdbi.UnitOfWorkJournalDao; package org.myeslib.jdbi.storage; @RunWith(MockitoJUnitRunner.class) public class JdbiUnitOfWorkJournalTest { @Mock UnitOfWorkJournalDao<UUID> dao; @Test public void insert() { JdbiUnitOfWorkJournal<UUID> writer = new JdbiUnitOfWorkJournal<>(dao); UUID id = UUID.randomUUID();
Command command1 = new IncreaseInventory(UUID.randomUUID(), id, 2, 0l);
rodolfodpk/myeslib
myeslib-jdbi/src/test/java/org/myeslib/jdbi/storage/JdbiUnitOfWorkJournalTest.java
// Path: myeslib-core/src/main/java/org/myeslib/core/Command.java // public interface Command extends Serializable { // // UUID getCommandId(); // Long getTargetVersion(); // // } // // Path: myeslib-core/src/main/java/org/myeslib/core/Event.java // public interface Event extends Serializable { // // } // // Path: myeslib-core/src/main/java/org/myeslib/core/data/UnitOfWork.java // @SuppressWarnings("serial") // @Value // public class UnitOfWork implements Comparable<UnitOfWork>, Serializable { // // final UUID id; // final Command command; // final List<? extends Event> events; // final long version; // // public UnitOfWork(UUID id, Command command, Long version, List<? extends Event> events) { // checkNotNull(id, "id cannot be null"); // checkNotNull(command, "command cannot be null"); // checkArgument(command.getTargetVersion()>=0, "target version must be >= 0"); // checkArgument(version>0, "invalid version"); // checkNotNull(events, "events cannot be null"); // for (Event e: events){ // checkNotNull(e, "event within events list cannot be null"); // } // this.id = id; // this.command = command; // this.version = version; // this.events = events; // } // // public static UnitOfWork create(UUID id, Command command, List<? extends Event> newEvents) { // checkNotNull(command.getTargetVersion(), "target version cannot be null"); // checkArgument(command.getTargetVersion()>=0, "target version must be >= 0"); // return new UnitOfWork(id, command, command.getTargetVersion()+1, newEvents); // } // // public List<Event> getEvents(){ // List<Event> result = new LinkedList<>(); // for (Event event : events) { // result.add(event); // } // return result; // } // // public int compareTo(UnitOfWork other) { // if (version < other.version) { // return -1; // } else if (version > other.version) { // return 1; // } // return 0; // } // // public Long getTargetVersion() { // return command.getTargetVersion(); // } // } // // Path: inventory-aggregate-root/src/main/java/org/myeslib/example/SampleDomain.java // @Value // public static class IncreaseInventory implements Command { // @NonNull // UUID commandId; // @NonNull // UUID id; // @NonNull // Integer howMany; // Long targetVersion; // } // // Path: inventory-aggregate-root/src/main/java/org/myeslib/example/SampleDomain.java // @Value // public static class InventoryIncreased implements Event { // @NonNull // UUID id; // @NonNull // Integer howMany; // } // // Path: myeslib-util/src/main/java/org/myeslib/util/jdbi/UnitOfWorkJournalDao.java // public interface UnitOfWorkJournalDao<K> { // // void append(K id, UnitOfWork uow); // // }
import static org.mockito.Mockito.verify; import java.util.Arrays; import java.util.UUID; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.myeslib.core.Command; import org.myeslib.core.Event; import org.myeslib.core.data.UnitOfWork; import org.myeslib.example.SampleDomain.IncreaseInventory; import org.myeslib.example.SampleDomain.InventoryIncreased; import org.myeslib.util.jdbi.UnitOfWorkJournalDao;
package org.myeslib.jdbi.storage; @RunWith(MockitoJUnitRunner.class) public class JdbiUnitOfWorkJournalTest { @Mock UnitOfWorkJournalDao<UUID> dao; @Test public void insert() { JdbiUnitOfWorkJournal<UUID> writer = new JdbiUnitOfWorkJournal<>(dao); UUID id = UUID.randomUUID(); Command command1 = new IncreaseInventory(UUID.randomUUID(), id, 2, 0l);
// Path: myeslib-core/src/main/java/org/myeslib/core/Command.java // public interface Command extends Serializable { // // UUID getCommandId(); // Long getTargetVersion(); // // } // // Path: myeslib-core/src/main/java/org/myeslib/core/Event.java // public interface Event extends Serializable { // // } // // Path: myeslib-core/src/main/java/org/myeslib/core/data/UnitOfWork.java // @SuppressWarnings("serial") // @Value // public class UnitOfWork implements Comparable<UnitOfWork>, Serializable { // // final UUID id; // final Command command; // final List<? extends Event> events; // final long version; // // public UnitOfWork(UUID id, Command command, Long version, List<? extends Event> events) { // checkNotNull(id, "id cannot be null"); // checkNotNull(command, "command cannot be null"); // checkArgument(command.getTargetVersion()>=0, "target version must be >= 0"); // checkArgument(version>0, "invalid version"); // checkNotNull(events, "events cannot be null"); // for (Event e: events){ // checkNotNull(e, "event within events list cannot be null"); // } // this.id = id; // this.command = command; // this.version = version; // this.events = events; // } // // public static UnitOfWork create(UUID id, Command command, List<? extends Event> newEvents) { // checkNotNull(command.getTargetVersion(), "target version cannot be null"); // checkArgument(command.getTargetVersion()>=0, "target version must be >= 0"); // return new UnitOfWork(id, command, command.getTargetVersion()+1, newEvents); // } // // public List<Event> getEvents(){ // List<Event> result = new LinkedList<>(); // for (Event event : events) { // result.add(event); // } // return result; // } // // public int compareTo(UnitOfWork other) { // if (version < other.version) { // return -1; // } else if (version > other.version) { // return 1; // } // return 0; // } // // public Long getTargetVersion() { // return command.getTargetVersion(); // } // } // // Path: inventory-aggregate-root/src/main/java/org/myeslib/example/SampleDomain.java // @Value // public static class IncreaseInventory implements Command { // @NonNull // UUID commandId; // @NonNull // UUID id; // @NonNull // Integer howMany; // Long targetVersion; // } // // Path: inventory-aggregate-root/src/main/java/org/myeslib/example/SampleDomain.java // @Value // public static class InventoryIncreased implements Event { // @NonNull // UUID id; // @NonNull // Integer howMany; // } // // Path: myeslib-util/src/main/java/org/myeslib/util/jdbi/UnitOfWorkJournalDao.java // public interface UnitOfWorkJournalDao<K> { // // void append(K id, UnitOfWork uow); // // } // Path: myeslib-jdbi/src/test/java/org/myeslib/jdbi/storage/JdbiUnitOfWorkJournalTest.java import static org.mockito.Mockito.verify; import java.util.Arrays; import java.util.UUID; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.myeslib.core.Command; import org.myeslib.core.Event; import org.myeslib.core.data.UnitOfWork; import org.myeslib.example.SampleDomain.IncreaseInventory; import org.myeslib.example.SampleDomain.InventoryIncreased; import org.myeslib.util.jdbi.UnitOfWorkJournalDao; package org.myeslib.jdbi.storage; @RunWith(MockitoJUnitRunner.class) public class JdbiUnitOfWorkJournalTest { @Mock UnitOfWorkJournalDao<UUID> dao; @Test public void insert() { JdbiUnitOfWorkJournal<UUID> writer = new JdbiUnitOfWorkJournal<>(dao); UUID id = UUID.randomUUID(); Command command1 = new IncreaseInventory(UUID.randomUUID(), id, 2, 0l);
Event event11 = new InventoryIncreased(id, 1);
rodolfodpk/myeslib
myeslib-jdbi/src/test/java/org/myeslib/jdbi/storage/JdbiUnitOfWorkJournalTest.java
// Path: myeslib-core/src/main/java/org/myeslib/core/Command.java // public interface Command extends Serializable { // // UUID getCommandId(); // Long getTargetVersion(); // // } // // Path: myeslib-core/src/main/java/org/myeslib/core/Event.java // public interface Event extends Serializable { // // } // // Path: myeslib-core/src/main/java/org/myeslib/core/data/UnitOfWork.java // @SuppressWarnings("serial") // @Value // public class UnitOfWork implements Comparable<UnitOfWork>, Serializable { // // final UUID id; // final Command command; // final List<? extends Event> events; // final long version; // // public UnitOfWork(UUID id, Command command, Long version, List<? extends Event> events) { // checkNotNull(id, "id cannot be null"); // checkNotNull(command, "command cannot be null"); // checkArgument(command.getTargetVersion()>=0, "target version must be >= 0"); // checkArgument(version>0, "invalid version"); // checkNotNull(events, "events cannot be null"); // for (Event e: events){ // checkNotNull(e, "event within events list cannot be null"); // } // this.id = id; // this.command = command; // this.version = version; // this.events = events; // } // // public static UnitOfWork create(UUID id, Command command, List<? extends Event> newEvents) { // checkNotNull(command.getTargetVersion(), "target version cannot be null"); // checkArgument(command.getTargetVersion()>=0, "target version must be >= 0"); // return new UnitOfWork(id, command, command.getTargetVersion()+1, newEvents); // } // // public List<Event> getEvents(){ // List<Event> result = new LinkedList<>(); // for (Event event : events) { // result.add(event); // } // return result; // } // // public int compareTo(UnitOfWork other) { // if (version < other.version) { // return -1; // } else if (version > other.version) { // return 1; // } // return 0; // } // // public Long getTargetVersion() { // return command.getTargetVersion(); // } // } // // Path: inventory-aggregate-root/src/main/java/org/myeslib/example/SampleDomain.java // @Value // public static class IncreaseInventory implements Command { // @NonNull // UUID commandId; // @NonNull // UUID id; // @NonNull // Integer howMany; // Long targetVersion; // } // // Path: inventory-aggregate-root/src/main/java/org/myeslib/example/SampleDomain.java // @Value // public static class InventoryIncreased implements Event { // @NonNull // UUID id; // @NonNull // Integer howMany; // } // // Path: myeslib-util/src/main/java/org/myeslib/util/jdbi/UnitOfWorkJournalDao.java // public interface UnitOfWorkJournalDao<K> { // // void append(K id, UnitOfWork uow); // // }
import static org.mockito.Mockito.verify; import java.util.Arrays; import java.util.UUID; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.myeslib.core.Command; import org.myeslib.core.Event; import org.myeslib.core.data.UnitOfWork; import org.myeslib.example.SampleDomain.IncreaseInventory; import org.myeslib.example.SampleDomain.InventoryIncreased; import org.myeslib.util.jdbi.UnitOfWorkJournalDao;
package org.myeslib.jdbi.storage; @RunWith(MockitoJUnitRunner.class) public class JdbiUnitOfWorkJournalTest { @Mock UnitOfWorkJournalDao<UUID> dao; @Test public void insert() { JdbiUnitOfWorkJournal<UUID> writer = new JdbiUnitOfWorkJournal<>(dao); UUID id = UUID.randomUUID(); Command command1 = new IncreaseInventory(UUID.randomUUID(), id, 2, 0l);
// Path: myeslib-core/src/main/java/org/myeslib/core/Command.java // public interface Command extends Serializable { // // UUID getCommandId(); // Long getTargetVersion(); // // } // // Path: myeslib-core/src/main/java/org/myeslib/core/Event.java // public interface Event extends Serializable { // // } // // Path: myeslib-core/src/main/java/org/myeslib/core/data/UnitOfWork.java // @SuppressWarnings("serial") // @Value // public class UnitOfWork implements Comparable<UnitOfWork>, Serializable { // // final UUID id; // final Command command; // final List<? extends Event> events; // final long version; // // public UnitOfWork(UUID id, Command command, Long version, List<? extends Event> events) { // checkNotNull(id, "id cannot be null"); // checkNotNull(command, "command cannot be null"); // checkArgument(command.getTargetVersion()>=0, "target version must be >= 0"); // checkArgument(version>0, "invalid version"); // checkNotNull(events, "events cannot be null"); // for (Event e: events){ // checkNotNull(e, "event within events list cannot be null"); // } // this.id = id; // this.command = command; // this.version = version; // this.events = events; // } // // public static UnitOfWork create(UUID id, Command command, List<? extends Event> newEvents) { // checkNotNull(command.getTargetVersion(), "target version cannot be null"); // checkArgument(command.getTargetVersion()>=0, "target version must be >= 0"); // return new UnitOfWork(id, command, command.getTargetVersion()+1, newEvents); // } // // public List<Event> getEvents(){ // List<Event> result = new LinkedList<>(); // for (Event event : events) { // result.add(event); // } // return result; // } // // public int compareTo(UnitOfWork other) { // if (version < other.version) { // return -1; // } else if (version > other.version) { // return 1; // } // return 0; // } // // public Long getTargetVersion() { // return command.getTargetVersion(); // } // } // // Path: inventory-aggregate-root/src/main/java/org/myeslib/example/SampleDomain.java // @Value // public static class IncreaseInventory implements Command { // @NonNull // UUID commandId; // @NonNull // UUID id; // @NonNull // Integer howMany; // Long targetVersion; // } // // Path: inventory-aggregate-root/src/main/java/org/myeslib/example/SampleDomain.java // @Value // public static class InventoryIncreased implements Event { // @NonNull // UUID id; // @NonNull // Integer howMany; // } // // Path: myeslib-util/src/main/java/org/myeslib/util/jdbi/UnitOfWorkJournalDao.java // public interface UnitOfWorkJournalDao<K> { // // void append(K id, UnitOfWork uow); // // } // Path: myeslib-jdbi/src/test/java/org/myeslib/jdbi/storage/JdbiUnitOfWorkJournalTest.java import static org.mockito.Mockito.verify; import java.util.Arrays; import java.util.UUID; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.myeslib.core.Command; import org.myeslib.core.Event; import org.myeslib.core.data.UnitOfWork; import org.myeslib.example.SampleDomain.IncreaseInventory; import org.myeslib.example.SampleDomain.InventoryIncreased; import org.myeslib.util.jdbi.UnitOfWorkJournalDao; package org.myeslib.jdbi.storage; @RunWith(MockitoJUnitRunner.class) public class JdbiUnitOfWorkJournalTest { @Mock UnitOfWorkJournalDao<UUID> dao; @Test public void insert() { JdbiUnitOfWorkJournal<UUID> writer = new JdbiUnitOfWorkJournal<>(dao); UUID id = UUID.randomUUID(); Command command1 = new IncreaseInventory(UUID.randomUUID(), id, 2, 0l);
Event event11 = new InventoryIncreased(id, 1);
rodolfodpk/myeslib
myeslib-jdbi/src/test/java/org/myeslib/jdbi/storage/JdbiUnitOfWorkJournalTest.java
// Path: myeslib-core/src/main/java/org/myeslib/core/Command.java // public interface Command extends Serializable { // // UUID getCommandId(); // Long getTargetVersion(); // // } // // Path: myeslib-core/src/main/java/org/myeslib/core/Event.java // public interface Event extends Serializable { // // } // // Path: myeslib-core/src/main/java/org/myeslib/core/data/UnitOfWork.java // @SuppressWarnings("serial") // @Value // public class UnitOfWork implements Comparable<UnitOfWork>, Serializable { // // final UUID id; // final Command command; // final List<? extends Event> events; // final long version; // // public UnitOfWork(UUID id, Command command, Long version, List<? extends Event> events) { // checkNotNull(id, "id cannot be null"); // checkNotNull(command, "command cannot be null"); // checkArgument(command.getTargetVersion()>=0, "target version must be >= 0"); // checkArgument(version>0, "invalid version"); // checkNotNull(events, "events cannot be null"); // for (Event e: events){ // checkNotNull(e, "event within events list cannot be null"); // } // this.id = id; // this.command = command; // this.version = version; // this.events = events; // } // // public static UnitOfWork create(UUID id, Command command, List<? extends Event> newEvents) { // checkNotNull(command.getTargetVersion(), "target version cannot be null"); // checkArgument(command.getTargetVersion()>=0, "target version must be >= 0"); // return new UnitOfWork(id, command, command.getTargetVersion()+1, newEvents); // } // // public List<Event> getEvents(){ // List<Event> result = new LinkedList<>(); // for (Event event : events) { // result.add(event); // } // return result; // } // // public int compareTo(UnitOfWork other) { // if (version < other.version) { // return -1; // } else if (version > other.version) { // return 1; // } // return 0; // } // // public Long getTargetVersion() { // return command.getTargetVersion(); // } // } // // Path: inventory-aggregate-root/src/main/java/org/myeslib/example/SampleDomain.java // @Value // public static class IncreaseInventory implements Command { // @NonNull // UUID commandId; // @NonNull // UUID id; // @NonNull // Integer howMany; // Long targetVersion; // } // // Path: inventory-aggregate-root/src/main/java/org/myeslib/example/SampleDomain.java // @Value // public static class InventoryIncreased implements Event { // @NonNull // UUID id; // @NonNull // Integer howMany; // } // // Path: myeslib-util/src/main/java/org/myeslib/util/jdbi/UnitOfWorkJournalDao.java // public interface UnitOfWorkJournalDao<K> { // // void append(K id, UnitOfWork uow); // // }
import static org.mockito.Mockito.verify; import java.util.Arrays; import java.util.UUID; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.myeslib.core.Command; import org.myeslib.core.Event; import org.myeslib.core.data.UnitOfWork; import org.myeslib.example.SampleDomain.IncreaseInventory; import org.myeslib.example.SampleDomain.InventoryIncreased; import org.myeslib.util.jdbi.UnitOfWorkJournalDao;
package org.myeslib.jdbi.storage; @RunWith(MockitoJUnitRunner.class) public class JdbiUnitOfWorkJournalTest { @Mock UnitOfWorkJournalDao<UUID> dao; @Test public void insert() { JdbiUnitOfWorkJournal<UUID> writer = new JdbiUnitOfWorkJournal<>(dao); UUID id = UUID.randomUUID(); Command command1 = new IncreaseInventory(UUID.randomUUID(), id, 2, 0l); Event event11 = new InventoryIncreased(id, 1); Event event12 = new InventoryIncreased(id, 1);
// Path: myeslib-core/src/main/java/org/myeslib/core/Command.java // public interface Command extends Serializable { // // UUID getCommandId(); // Long getTargetVersion(); // // } // // Path: myeslib-core/src/main/java/org/myeslib/core/Event.java // public interface Event extends Serializable { // // } // // Path: myeslib-core/src/main/java/org/myeslib/core/data/UnitOfWork.java // @SuppressWarnings("serial") // @Value // public class UnitOfWork implements Comparable<UnitOfWork>, Serializable { // // final UUID id; // final Command command; // final List<? extends Event> events; // final long version; // // public UnitOfWork(UUID id, Command command, Long version, List<? extends Event> events) { // checkNotNull(id, "id cannot be null"); // checkNotNull(command, "command cannot be null"); // checkArgument(command.getTargetVersion()>=0, "target version must be >= 0"); // checkArgument(version>0, "invalid version"); // checkNotNull(events, "events cannot be null"); // for (Event e: events){ // checkNotNull(e, "event within events list cannot be null"); // } // this.id = id; // this.command = command; // this.version = version; // this.events = events; // } // // public static UnitOfWork create(UUID id, Command command, List<? extends Event> newEvents) { // checkNotNull(command.getTargetVersion(), "target version cannot be null"); // checkArgument(command.getTargetVersion()>=0, "target version must be >= 0"); // return new UnitOfWork(id, command, command.getTargetVersion()+1, newEvents); // } // // public List<Event> getEvents(){ // List<Event> result = new LinkedList<>(); // for (Event event : events) { // result.add(event); // } // return result; // } // // public int compareTo(UnitOfWork other) { // if (version < other.version) { // return -1; // } else if (version > other.version) { // return 1; // } // return 0; // } // // public Long getTargetVersion() { // return command.getTargetVersion(); // } // } // // Path: inventory-aggregate-root/src/main/java/org/myeslib/example/SampleDomain.java // @Value // public static class IncreaseInventory implements Command { // @NonNull // UUID commandId; // @NonNull // UUID id; // @NonNull // Integer howMany; // Long targetVersion; // } // // Path: inventory-aggregate-root/src/main/java/org/myeslib/example/SampleDomain.java // @Value // public static class InventoryIncreased implements Event { // @NonNull // UUID id; // @NonNull // Integer howMany; // } // // Path: myeslib-util/src/main/java/org/myeslib/util/jdbi/UnitOfWorkJournalDao.java // public interface UnitOfWorkJournalDao<K> { // // void append(K id, UnitOfWork uow); // // } // Path: myeslib-jdbi/src/test/java/org/myeslib/jdbi/storage/JdbiUnitOfWorkJournalTest.java import static org.mockito.Mockito.verify; import java.util.Arrays; import java.util.UUID; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.myeslib.core.Command; import org.myeslib.core.Event; import org.myeslib.core.data.UnitOfWork; import org.myeslib.example.SampleDomain.IncreaseInventory; import org.myeslib.example.SampleDomain.InventoryIncreased; import org.myeslib.util.jdbi.UnitOfWorkJournalDao; package org.myeslib.jdbi.storage; @RunWith(MockitoJUnitRunner.class) public class JdbiUnitOfWorkJournalTest { @Mock UnitOfWorkJournalDao<UUID> dao; @Test public void insert() { JdbiUnitOfWorkJournal<UUID> writer = new JdbiUnitOfWorkJournal<>(dao); UUID id = UUID.randomUUID(); Command command1 = new IncreaseInventory(UUID.randomUUID(), id, 2, 0l); Event event11 = new InventoryIncreased(id, 1); Event event12 = new InventoryIncreased(id, 1);
UnitOfWork uow1 = UnitOfWork.create(UUID.randomUUID(), command1, Arrays.asList(event11, event12));
rodolfodpk/myeslib
myeslib-core/src/main/java/org/myeslib/core/data/AggregateRootHistory.java
// Path: myeslib-core/src/main/java/org/myeslib/core/Event.java // public interface Event extends Serializable { // // }
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkArgument; import java.io.Serializable; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import lombok.Data; import org.myeslib.core.Event; import com.google.common.collect.Lists; import com.google.common.collect.Sets;
package org.myeslib.core.data; @SuppressWarnings("serial") @Data public class AggregateRootHistory implements Serializable { private final List<UnitOfWork> unitsOfWork; private final Set<UnitOfWork> persisted; public AggregateRootHistory() { this.unitsOfWork = new LinkedList<>(); this.persisted = new LinkedHashSet<>(); }
// Path: myeslib-core/src/main/java/org/myeslib/core/Event.java // public interface Event extends Serializable { // // } // Path: myeslib-core/src/main/java/org/myeslib/core/data/AggregateRootHistory.java import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkArgument; import java.io.Serializable; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import lombok.Data; import org.myeslib.core.Event; import com.google.common.collect.Lists; import com.google.common.collect.Sets; package org.myeslib.core.data; @SuppressWarnings("serial") @Data public class AggregateRootHistory implements Serializable { private final List<UnitOfWork> unitsOfWork; private final Set<UnitOfWork> persisted; public AggregateRootHistory() { this.unitsOfWork = new LinkedList<>(); this.persisted = new LinkedHashSet<>(); }
public List<Event> getAllEvents() {
rodolfodpk/myeslib
myeslib-util/src/main/java/org/myeslib/util/hazelcast/HzStringMapStore.java
// Path: myeslib-util/src/main/java/org/myeslib/util/jdbi/ClobToStringMapper.java // public class ClobToStringMapper extends TypedMapper<String> { // // public ClobToStringMapper(){ // super(); // } // // public ClobToStringMapper(int index) // { // super(index); // } // // public ClobToStringMapper(String name) // { // super(name); // } // // @Override // protected String extractByName(ResultSet r, String name) throws SQLException { // Clob clob = r.getClob(name); // try { // return CharStreams.toString(clob.getCharacterStream()); // } catch (IOException e) { // e.printStackTrace(); // } finally { // clob.free(); // } // return null; // } // // @Override // protected String extractByIndex(ResultSet r, int index) throws SQLException { // Clob clob = r.getClob(index); // try { // return CharStreams.toString(clob.getCharacterStream()); // } catch (IOException e) { // e.printStackTrace(); // } finally { // clob.free(); // } // return null; // } // // public static final ClobToStringMapper FIRST = new ClobToStringMapper(); // }
import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.UUID; import javax.sql.DataSource; import lombok.extern.slf4j.Slf4j; import org.myeslib.util.jdbi.ClobToStringMapper; import org.skife.jdbi.v2.DBI; import org.skife.jdbi.v2.Handle; import org.skife.jdbi.v2.PreparedBatch; import org.skife.jdbi.v2.TransactionCallback; import org.skife.jdbi.v2.TransactionIsolationLevel; import org.skife.jdbi.v2.TransactionStatus; import org.skife.jdbi.v2.tweak.HandleCallback; import org.skife.jdbi.v2.util.StringMapper; import com.hazelcast.core.MapStore;
@Override public Set<UUID> loadAllKeys() { // TODO define how many keys will be pre-loaded log.debug("loading all keys from table {}", tableName); Set<UUID> result = dbi.withHandle(new HandleCallback<Set<UUID>>() { @Override public Set<UUID> withHandle(Handle h) throws Exception { List<String> strResult = h.createQuery(String.format("select id from %s", tableName)) .map(new StringMapper()).list(); Set<UUID> uResult = new HashSet<>(); for (String uuid : strResult){ uResult.add(UUID.fromString(uuid)); } return uResult; } }); log.debug("{} keys within table {} were loaded", result.size(), tableName); return result; } @Override public String load(final UUID id) { String result = null; try { log.debug("will load {} from table {}", id.toString(), tableName); result = dbi.inTransaction(TransactionIsolationLevel.READ_COMMITTED, new TransactionCallback<String>() { @Override public String inTransaction(Handle h, TransactionStatus ts) throws Exception { String sql = String.format("select aggregate_root_data from %s where id = :id", tableName);
// Path: myeslib-util/src/main/java/org/myeslib/util/jdbi/ClobToStringMapper.java // public class ClobToStringMapper extends TypedMapper<String> { // // public ClobToStringMapper(){ // super(); // } // // public ClobToStringMapper(int index) // { // super(index); // } // // public ClobToStringMapper(String name) // { // super(name); // } // // @Override // protected String extractByName(ResultSet r, String name) throws SQLException { // Clob clob = r.getClob(name); // try { // return CharStreams.toString(clob.getCharacterStream()); // } catch (IOException e) { // e.printStackTrace(); // } finally { // clob.free(); // } // return null; // } // // @Override // protected String extractByIndex(ResultSet r, int index) throws SQLException { // Clob clob = r.getClob(index); // try { // return CharStreams.toString(clob.getCharacterStream()); // } catch (IOException e) { // e.printStackTrace(); // } finally { // clob.free(); // } // return null; // } // // public static final ClobToStringMapper FIRST = new ClobToStringMapper(); // } // Path: myeslib-util/src/main/java/org/myeslib/util/hazelcast/HzStringMapStore.java import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.UUID; import javax.sql.DataSource; import lombok.extern.slf4j.Slf4j; import org.myeslib.util.jdbi.ClobToStringMapper; import org.skife.jdbi.v2.DBI; import org.skife.jdbi.v2.Handle; import org.skife.jdbi.v2.PreparedBatch; import org.skife.jdbi.v2.TransactionCallback; import org.skife.jdbi.v2.TransactionIsolationLevel; import org.skife.jdbi.v2.TransactionStatus; import org.skife.jdbi.v2.tweak.HandleCallback; import org.skife.jdbi.v2.util.StringMapper; import com.hazelcast.core.MapStore; @Override public Set<UUID> loadAllKeys() { // TODO define how many keys will be pre-loaded log.debug("loading all keys from table {}", tableName); Set<UUID> result = dbi.withHandle(new HandleCallback<Set<UUID>>() { @Override public Set<UUID> withHandle(Handle h) throws Exception { List<String> strResult = h.createQuery(String.format("select id from %s", tableName)) .map(new StringMapper()).list(); Set<UUID> uResult = new HashSet<>(); for (String uuid : strResult){ uResult.add(UUID.fromString(uuid)); } return uResult; } }); log.debug("{} keys within table {} were loaded", result.size(), tableName); return result; } @Override public String load(final UUID id) { String result = null; try { log.debug("will load {} from table {}", id.toString(), tableName); result = dbi.inTransaction(TransactionIsolationLevel.READ_COMMITTED, new TransactionCallback<String>() { @Override public String inTransaction(Handle h, TransactionStatus ts) throws Exception { String sql = String.format("select aggregate_root_data from %s where id = :id", tableName);
return h.createQuery(sql).bind("id", id.toString()).map(ClobToStringMapper.FIRST).first();
rodolfodpk/myeslib
myeslib-util/src/main/java/org/myeslib/util/jdbi/JdbiUnitOfWorkAutoCommitJournalDao.java
// Path: myeslib-core/src/main/java/org/myeslib/core/data/UnitOfWork.java // @SuppressWarnings("serial") // @Value // public class UnitOfWork implements Comparable<UnitOfWork>, Serializable { // // final UUID id; // final Command command; // final List<? extends Event> events; // final long version; // // public UnitOfWork(UUID id, Command command, Long version, List<? extends Event> events) { // checkNotNull(id, "id cannot be null"); // checkNotNull(command, "command cannot be null"); // checkArgument(command.getTargetVersion()>=0, "target version must be >= 0"); // checkArgument(version>0, "invalid version"); // checkNotNull(events, "events cannot be null"); // for (Event e: events){ // checkNotNull(e, "event within events list cannot be null"); // } // this.id = id; // this.command = command; // this.version = version; // this.events = events; // } // // public static UnitOfWork create(UUID id, Command command, List<? extends Event> newEvents) { // checkNotNull(command.getTargetVersion(), "target version cannot be null"); // checkArgument(command.getTargetVersion()>=0, "target version must be >= 0"); // return new UnitOfWork(id, command, command.getTargetVersion()+1, newEvents); // } // // public List<Event> getEvents(){ // List<Event> result = new LinkedList<>(); // for (Event event : events) { // result.add(event); // } // return result; // } // // public int compareTo(UnitOfWork other) { // if (version < other.version) { // return -1; // } else if (version > other.version) { // return 1; // } // return 0; // } // // public Long getTargetVersion() { // return command.getTargetVersion(); // } // }
import java.util.UUID; import lombok.extern.slf4j.Slf4j; import org.myeslib.core.data.UnitOfWork; import org.skife.jdbi.v2.DBI; import org.skife.jdbi.v2.Handle; import org.skife.jdbi.v2.TransactionCallback; import org.skife.jdbi.v2.TransactionIsolationLevel; import org.skife.jdbi.v2.TransactionStatus; import com.google.common.base.Function; import com.google.inject.Inject;
package org.myeslib.util.jdbi; @Slf4j public class JdbiUnitOfWorkAutoCommitJournalDao implements UnitOfWorkJournalDao<UUID> { @Inject public JdbiUnitOfWorkAutoCommitJournalDao(DBI dbi, ArTablesMetadata tables,
// Path: myeslib-core/src/main/java/org/myeslib/core/data/UnitOfWork.java // @SuppressWarnings("serial") // @Value // public class UnitOfWork implements Comparable<UnitOfWork>, Serializable { // // final UUID id; // final Command command; // final List<? extends Event> events; // final long version; // // public UnitOfWork(UUID id, Command command, Long version, List<? extends Event> events) { // checkNotNull(id, "id cannot be null"); // checkNotNull(command, "command cannot be null"); // checkArgument(command.getTargetVersion()>=0, "target version must be >= 0"); // checkArgument(version>0, "invalid version"); // checkNotNull(events, "events cannot be null"); // for (Event e: events){ // checkNotNull(e, "event within events list cannot be null"); // } // this.id = id; // this.command = command; // this.version = version; // this.events = events; // } // // public static UnitOfWork create(UUID id, Command command, List<? extends Event> newEvents) { // checkNotNull(command.getTargetVersion(), "target version cannot be null"); // checkArgument(command.getTargetVersion()>=0, "target version must be >= 0"); // return new UnitOfWork(id, command, command.getTargetVersion()+1, newEvents); // } // // public List<Event> getEvents(){ // List<Event> result = new LinkedList<>(); // for (Event event : events) { // result.add(event); // } // return result; // } // // public int compareTo(UnitOfWork other) { // if (version < other.version) { // return -1; // } else if (version > other.version) { // return 1; // } // return 0; // } // // public Long getTargetVersion() { // return command.getTargetVersion(); // } // } // Path: myeslib-util/src/main/java/org/myeslib/util/jdbi/JdbiUnitOfWorkAutoCommitJournalDao.java import java.util.UUID; import lombok.extern.slf4j.Slf4j; import org.myeslib.core.data.UnitOfWork; import org.skife.jdbi.v2.DBI; import org.skife.jdbi.v2.Handle; import org.skife.jdbi.v2.TransactionCallback; import org.skife.jdbi.v2.TransactionIsolationLevel; import org.skife.jdbi.v2.TransactionStatus; import com.google.common.base.Function; import com.google.inject.Inject; package org.myeslib.util.jdbi; @Slf4j public class JdbiUnitOfWorkAutoCommitJournalDao implements UnitOfWorkJournalDao<UUID> { @Inject public JdbiUnitOfWorkAutoCommitJournalDao(DBI dbi, ArTablesMetadata tables,
Function<UnitOfWork, String> toStringFunction) {
rodolfodpk/myeslib
inventory-cmd-producer/src/main/java/org/myeslib/cmdproducer/routes/CommandsDataSetsRoute.java
// Path: myeslib-core/src/main/java/org/myeslib/core/Command.java // public interface Command extends Serializable { // // UUID getCommandId(); // Long getTargetVersion(); // // }
import java.lang.reflect.Type; import lombok.AllArgsConstructor; import org.apache.camel.Exchange; import org.apache.camel.Processor; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.util.toolbox.AggregationStrategies; import org.myeslib.core.Command; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken;
package org.myeslib.cmdproducer.routes; @AllArgsConstructor public class CommandsDataSetsRoute extends RouteBuilder { final Gson gson; final String targetEndpoint;
// Path: myeslib-core/src/main/java/org/myeslib/core/Command.java // public interface Command extends Serializable { // // UUID getCommandId(); // Long getTargetVersion(); // // } // Path: inventory-cmd-producer/src/main/java/org/myeslib/cmdproducer/routes/CommandsDataSetsRoute.java import java.lang.reflect.Type; import lombok.AllArgsConstructor; import org.apache.camel.Exchange; import org.apache.camel.Processor; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.util.toolbox.AggregationStrategies; import org.myeslib.core.Command; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; package org.myeslib.cmdproducer.routes; @AllArgsConstructor public class CommandsDataSetsRoute extends RouteBuilder { final Gson gson; final String targetEndpoint;
final Type commandType = new TypeToken<Command>() {}.getType();
rodolfodpk/myeslib
inventory-aggregate-root/src/test/java/org/myeslib/example/InventoryItemAggregateRootTest.java
// Path: inventory-aggregate-root/src/main/java/org/myeslib/example/SampleDomain.java // @Value // public static class InventoryDecreased implements Event { // @NonNull // UUID id; // @NonNull // Integer howMany; // } // // Path: inventory-aggregate-root/src/main/java/org/myeslib/example/SampleDomain.java // @Value // public static class InventoryIncreased implements Event { // @NonNull // UUID id; // @NonNull // Integer howMany; // } // // Path: inventory-aggregate-root/src/main/java/org/myeslib/example/SampleDomain.java // @Data // public static class InventoryItemAggregateRoot implements AggregateRoot { // // UUID id; // String description; // Integer available = 0; // // public void on(InventoryItemCreated event) { // this.id = event.id; // this.description = event.description; // this.available = 0; // } // // public void on(InventoryIncreased event) { // this.available = this.available + event.howMany; // } // // public void on(InventoryDecreased event) { // this.available = this.available - event.howMany; // } // // public boolean isAvailable(int howMany) { // return getAvailable() - howMany >= 0; // } // // } // // Path: inventory-aggregate-root/src/main/java/org/myeslib/example/SampleDomain.java // @Value // public static class InventoryItemCreated implements Event { // @NonNull // UUID id; // @NonNull // String description; // }
import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; import java.util.UUID; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.runners.MockitoJUnitRunner; import org.myeslib.example.SampleDomain.InventoryDecreased; import org.myeslib.example.SampleDomain.InventoryIncreased; import org.myeslib.example.SampleDomain.InventoryItemAggregateRoot; import org.myeslib.example.SampleDomain.InventoryItemCreated;
package org.myeslib.example; @RunWith(MockitoJUnitRunner.class) public class InventoryItemAggregateRootTest { @Test public void created() {
// Path: inventory-aggregate-root/src/main/java/org/myeslib/example/SampleDomain.java // @Value // public static class InventoryDecreased implements Event { // @NonNull // UUID id; // @NonNull // Integer howMany; // } // // Path: inventory-aggregate-root/src/main/java/org/myeslib/example/SampleDomain.java // @Value // public static class InventoryIncreased implements Event { // @NonNull // UUID id; // @NonNull // Integer howMany; // } // // Path: inventory-aggregate-root/src/main/java/org/myeslib/example/SampleDomain.java // @Data // public static class InventoryItemAggregateRoot implements AggregateRoot { // // UUID id; // String description; // Integer available = 0; // // public void on(InventoryItemCreated event) { // this.id = event.id; // this.description = event.description; // this.available = 0; // } // // public void on(InventoryIncreased event) { // this.available = this.available + event.howMany; // } // // public void on(InventoryDecreased event) { // this.available = this.available - event.howMany; // } // // public boolean isAvailable(int howMany) { // return getAvailable() - howMany >= 0; // } // // } // // Path: inventory-aggregate-root/src/main/java/org/myeslib/example/SampleDomain.java // @Value // public static class InventoryItemCreated implements Event { // @NonNull // UUID id; // @NonNull // String description; // } // Path: inventory-aggregate-root/src/test/java/org/myeslib/example/InventoryItemAggregateRootTest.java import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; import java.util.UUID; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.runners.MockitoJUnitRunner; import org.myeslib.example.SampleDomain.InventoryDecreased; import org.myeslib.example.SampleDomain.InventoryIncreased; import org.myeslib.example.SampleDomain.InventoryItemAggregateRoot; import org.myeslib.example.SampleDomain.InventoryItemCreated; package org.myeslib.example; @RunWith(MockitoJUnitRunner.class) public class InventoryItemAggregateRootTest { @Test public void created() {
InventoryItemAggregateRoot aggregateRoot = new InventoryItemAggregateRoot();
rodolfodpk/myeslib
inventory-aggregate-root/src/test/java/org/myeslib/example/InventoryItemAggregateRootTest.java
// Path: inventory-aggregate-root/src/main/java/org/myeslib/example/SampleDomain.java // @Value // public static class InventoryDecreased implements Event { // @NonNull // UUID id; // @NonNull // Integer howMany; // } // // Path: inventory-aggregate-root/src/main/java/org/myeslib/example/SampleDomain.java // @Value // public static class InventoryIncreased implements Event { // @NonNull // UUID id; // @NonNull // Integer howMany; // } // // Path: inventory-aggregate-root/src/main/java/org/myeslib/example/SampleDomain.java // @Data // public static class InventoryItemAggregateRoot implements AggregateRoot { // // UUID id; // String description; // Integer available = 0; // // public void on(InventoryItemCreated event) { // this.id = event.id; // this.description = event.description; // this.available = 0; // } // // public void on(InventoryIncreased event) { // this.available = this.available + event.howMany; // } // // public void on(InventoryDecreased event) { // this.available = this.available - event.howMany; // } // // public boolean isAvailable(int howMany) { // return getAvailable() - howMany >= 0; // } // // } // // Path: inventory-aggregate-root/src/main/java/org/myeslib/example/SampleDomain.java // @Value // public static class InventoryItemCreated implements Event { // @NonNull // UUID id; // @NonNull // String description; // }
import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; import java.util.UUID; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.runners.MockitoJUnitRunner; import org.myeslib.example.SampleDomain.InventoryDecreased; import org.myeslib.example.SampleDomain.InventoryIncreased; import org.myeslib.example.SampleDomain.InventoryItemAggregateRoot; import org.myeslib.example.SampleDomain.InventoryItemCreated;
package org.myeslib.example; @RunWith(MockitoJUnitRunner.class) public class InventoryItemAggregateRootTest { @Test public void created() { InventoryItemAggregateRoot aggregateRoot = new InventoryItemAggregateRoot(); UUID id = UUID.randomUUID(); String desc = "item1";
// Path: inventory-aggregate-root/src/main/java/org/myeslib/example/SampleDomain.java // @Value // public static class InventoryDecreased implements Event { // @NonNull // UUID id; // @NonNull // Integer howMany; // } // // Path: inventory-aggregate-root/src/main/java/org/myeslib/example/SampleDomain.java // @Value // public static class InventoryIncreased implements Event { // @NonNull // UUID id; // @NonNull // Integer howMany; // } // // Path: inventory-aggregate-root/src/main/java/org/myeslib/example/SampleDomain.java // @Data // public static class InventoryItemAggregateRoot implements AggregateRoot { // // UUID id; // String description; // Integer available = 0; // // public void on(InventoryItemCreated event) { // this.id = event.id; // this.description = event.description; // this.available = 0; // } // // public void on(InventoryIncreased event) { // this.available = this.available + event.howMany; // } // // public void on(InventoryDecreased event) { // this.available = this.available - event.howMany; // } // // public boolean isAvailable(int howMany) { // return getAvailable() - howMany >= 0; // } // // } // // Path: inventory-aggregate-root/src/main/java/org/myeslib/example/SampleDomain.java // @Value // public static class InventoryItemCreated implements Event { // @NonNull // UUID id; // @NonNull // String description; // } // Path: inventory-aggregate-root/src/test/java/org/myeslib/example/InventoryItemAggregateRootTest.java import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; import java.util.UUID; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.runners.MockitoJUnitRunner; import org.myeslib.example.SampleDomain.InventoryDecreased; import org.myeslib.example.SampleDomain.InventoryIncreased; import org.myeslib.example.SampleDomain.InventoryItemAggregateRoot; import org.myeslib.example.SampleDomain.InventoryItemCreated; package org.myeslib.example; @RunWith(MockitoJUnitRunner.class) public class InventoryItemAggregateRootTest { @Test public void created() { InventoryItemAggregateRoot aggregateRoot = new InventoryItemAggregateRoot(); UUID id = UUID.randomUUID(); String desc = "item1";
InventoryItemCreated event = new InventoryItemCreated(id, desc);
rodolfodpk/myeslib
inventory-aggregate-root/src/test/java/org/myeslib/example/InventoryItemAggregateRootTest.java
// Path: inventory-aggregate-root/src/main/java/org/myeslib/example/SampleDomain.java // @Value // public static class InventoryDecreased implements Event { // @NonNull // UUID id; // @NonNull // Integer howMany; // } // // Path: inventory-aggregate-root/src/main/java/org/myeslib/example/SampleDomain.java // @Value // public static class InventoryIncreased implements Event { // @NonNull // UUID id; // @NonNull // Integer howMany; // } // // Path: inventory-aggregate-root/src/main/java/org/myeslib/example/SampleDomain.java // @Data // public static class InventoryItemAggregateRoot implements AggregateRoot { // // UUID id; // String description; // Integer available = 0; // // public void on(InventoryItemCreated event) { // this.id = event.id; // this.description = event.description; // this.available = 0; // } // // public void on(InventoryIncreased event) { // this.available = this.available + event.howMany; // } // // public void on(InventoryDecreased event) { // this.available = this.available - event.howMany; // } // // public boolean isAvailable(int howMany) { // return getAvailable() - howMany >= 0; // } // // } // // Path: inventory-aggregate-root/src/main/java/org/myeslib/example/SampleDomain.java // @Value // public static class InventoryItemCreated implements Event { // @NonNull // UUID id; // @NonNull // String description; // }
import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; import java.util.UUID; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.runners.MockitoJUnitRunner; import org.myeslib.example.SampleDomain.InventoryDecreased; import org.myeslib.example.SampleDomain.InventoryIncreased; import org.myeslib.example.SampleDomain.InventoryItemAggregateRoot; import org.myeslib.example.SampleDomain.InventoryItemCreated;
package org.myeslib.example; @RunWith(MockitoJUnitRunner.class) public class InventoryItemAggregateRootTest { @Test public void created() { InventoryItemAggregateRoot aggregateRoot = new InventoryItemAggregateRoot(); UUID id = UUID.randomUUID(); String desc = "item1"; InventoryItemCreated event = new InventoryItemCreated(id, desc); aggregateRoot.on(event); assertThat(aggregateRoot.getId(), equalTo(id)); assertThat(aggregateRoot.getDescription(), equalTo(desc)); assertThat(aggregateRoot.getAvailable(), equalTo(0)); } @Test public void increased() { InventoryItemAggregateRoot aggregateRoot = new InventoryItemAggregateRoot(); UUID id = UUID.randomUUID(); String desc = "item1"; aggregateRoot.setAvailable(0); aggregateRoot.setDescription(desc); aggregateRoot.setId(id);
// Path: inventory-aggregate-root/src/main/java/org/myeslib/example/SampleDomain.java // @Value // public static class InventoryDecreased implements Event { // @NonNull // UUID id; // @NonNull // Integer howMany; // } // // Path: inventory-aggregate-root/src/main/java/org/myeslib/example/SampleDomain.java // @Value // public static class InventoryIncreased implements Event { // @NonNull // UUID id; // @NonNull // Integer howMany; // } // // Path: inventory-aggregate-root/src/main/java/org/myeslib/example/SampleDomain.java // @Data // public static class InventoryItemAggregateRoot implements AggregateRoot { // // UUID id; // String description; // Integer available = 0; // // public void on(InventoryItemCreated event) { // this.id = event.id; // this.description = event.description; // this.available = 0; // } // // public void on(InventoryIncreased event) { // this.available = this.available + event.howMany; // } // // public void on(InventoryDecreased event) { // this.available = this.available - event.howMany; // } // // public boolean isAvailable(int howMany) { // return getAvailable() - howMany >= 0; // } // // } // // Path: inventory-aggregate-root/src/main/java/org/myeslib/example/SampleDomain.java // @Value // public static class InventoryItemCreated implements Event { // @NonNull // UUID id; // @NonNull // String description; // } // Path: inventory-aggregate-root/src/test/java/org/myeslib/example/InventoryItemAggregateRootTest.java import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; import java.util.UUID; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.runners.MockitoJUnitRunner; import org.myeslib.example.SampleDomain.InventoryDecreased; import org.myeslib.example.SampleDomain.InventoryIncreased; import org.myeslib.example.SampleDomain.InventoryItemAggregateRoot; import org.myeslib.example.SampleDomain.InventoryItemCreated; package org.myeslib.example; @RunWith(MockitoJUnitRunner.class) public class InventoryItemAggregateRootTest { @Test public void created() { InventoryItemAggregateRoot aggregateRoot = new InventoryItemAggregateRoot(); UUID id = UUID.randomUUID(); String desc = "item1"; InventoryItemCreated event = new InventoryItemCreated(id, desc); aggregateRoot.on(event); assertThat(aggregateRoot.getId(), equalTo(id)); assertThat(aggregateRoot.getDescription(), equalTo(desc)); assertThat(aggregateRoot.getAvailable(), equalTo(0)); } @Test public void increased() { InventoryItemAggregateRoot aggregateRoot = new InventoryItemAggregateRoot(); UUID id = UUID.randomUUID(); String desc = "item1"; aggregateRoot.setAvailable(0); aggregateRoot.setDescription(desc); aggregateRoot.setId(id);
InventoryIncreased event = new InventoryIncreased(id, 2);
rodolfodpk/myeslib
inventory-aggregate-root/src/test/java/org/myeslib/example/InventoryItemAggregateRootTest.java
// Path: inventory-aggregate-root/src/main/java/org/myeslib/example/SampleDomain.java // @Value // public static class InventoryDecreased implements Event { // @NonNull // UUID id; // @NonNull // Integer howMany; // } // // Path: inventory-aggregate-root/src/main/java/org/myeslib/example/SampleDomain.java // @Value // public static class InventoryIncreased implements Event { // @NonNull // UUID id; // @NonNull // Integer howMany; // } // // Path: inventory-aggregate-root/src/main/java/org/myeslib/example/SampleDomain.java // @Data // public static class InventoryItemAggregateRoot implements AggregateRoot { // // UUID id; // String description; // Integer available = 0; // // public void on(InventoryItemCreated event) { // this.id = event.id; // this.description = event.description; // this.available = 0; // } // // public void on(InventoryIncreased event) { // this.available = this.available + event.howMany; // } // // public void on(InventoryDecreased event) { // this.available = this.available - event.howMany; // } // // public boolean isAvailable(int howMany) { // return getAvailable() - howMany >= 0; // } // // } // // Path: inventory-aggregate-root/src/main/java/org/myeslib/example/SampleDomain.java // @Value // public static class InventoryItemCreated implements Event { // @NonNull // UUID id; // @NonNull // String description; // }
import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; import java.util.UUID; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.runners.MockitoJUnitRunner; import org.myeslib.example.SampleDomain.InventoryDecreased; import org.myeslib.example.SampleDomain.InventoryIncreased; import org.myeslib.example.SampleDomain.InventoryItemAggregateRoot; import org.myeslib.example.SampleDomain.InventoryItemCreated;
InventoryItemAggregateRoot aggregateRoot = new InventoryItemAggregateRoot(); UUID id = UUID.randomUUID(); String desc = "item1"; aggregateRoot.setAvailable(0); aggregateRoot.setDescription(desc); aggregateRoot.setId(id); InventoryIncreased event = new InventoryIncreased(id, 2); aggregateRoot.on(event); assertThat(aggregateRoot.getAvailable(), equalTo(2)); } @Test public void decreased() { InventoryItemAggregateRoot aggregateRoot = new InventoryItemAggregateRoot(); UUID id = UUID.randomUUID(); String desc = "item1"; aggregateRoot.setAvailable(5); aggregateRoot.setDescription(desc); aggregateRoot.setId(id);
// Path: inventory-aggregate-root/src/main/java/org/myeslib/example/SampleDomain.java // @Value // public static class InventoryDecreased implements Event { // @NonNull // UUID id; // @NonNull // Integer howMany; // } // // Path: inventory-aggregate-root/src/main/java/org/myeslib/example/SampleDomain.java // @Value // public static class InventoryIncreased implements Event { // @NonNull // UUID id; // @NonNull // Integer howMany; // } // // Path: inventory-aggregate-root/src/main/java/org/myeslib/example/SampleDomain.java // @Data // public static class InventoryItemAggregateRoot implements AggregateRoot { // // UUID id; // String description; // Integer available = 0; // // public void on(InventoryItemCreated event) { // this.id = event.id; // this.description = event.description; // this.available = 0; // } // // public void on(InventoryIncreased event) { // this.available = this.available + event.howMany; // } // // public void on(InventoryDecreased event) { // this.available = this.available - event.howMany; // } // // public boolean isAvailable(int howMany) { // return getAvailable() - howMany >= 0; // } // // } // // Path: inventory-aggregate-root/src/main/java/org/myeslib/example/SampleDomain.java // @Value // public static class InventoryItemCreated implements Event { // @NonNull // UUID id; // @NonNull // String description; // } // Path: inventory-aggregate-root/src/test/java/org/myeslib/example/InventoryItemAggregateRootTest.java import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; import java.util.UUID; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.runners.MockitoJUnitRunner; import org.myeslib.example.SampleDomain.InventoryDecreased; import org.myeslib.example.SampleDomain.InventoryIncreased; import org.myeslib.example.SampleDomain.InventoryItemAggregateRoot; import org.myeslib.example.SampleDomain.InventoryItemCreated; InventoryItemAggregateRoot aggregateRoot = new InventoryItemAggregateRoot(); UUID id = UUID.randomUUID(); String desc = "item1"; aggregateRoot.setAvailable(0); aggregateRoot.setDescription(desc); aggregateRoot.setId(id); InventoryIncreased event = new InventoryIncreased(id, 2); aggregateRoot.on(event); assertThat(aggregateRoot.getAvailable(), equalTo(2)); } @Test public void decreased() { InventoryItemAggregateRoot aggregateRoot = new InventoryItemAggregateRoot(); UUID id = UUID.randomUUID(); String desc = "item1"; aggregateRoot.setAvailable(5); aggregateRoot.setDescription(desc); aggregateRoot.setId(id);
InventoryDecreased event = new InventoryDecreased(id, 2);
rodolfodpk/myeslib
inventory-cmd-producer/src/main/java/org/myeslib/cmdproducer/datasets/IncreaseCommandDataSet.java
// Path: inventory-aggregate-root/src/main/java/org/myeslib/example/SampleDomain.java // @Value // public static class IncreaseInventory implements Command { // @NonNull // UUID commandId; // @NonNull // UUID id; // @NonNull // Integer howMany; // Long targetVersion; // }
import java.util.List; import java.util.UUID; import org.apache.camel.component.dataset.DataSetSupport; import org.myeslib.example.SampleDomain.IncreaseInventory;
package org.myeslib.cmdproducer.datasets; public class IncreaseCommandDataSet extends DataSetSupport { public final List<UUID> ids ; public IncreaseCommandDataSet(List<UUID> ids, int howManyAggregates) { this.ids = ids; setSize(howManyAggregates); setReportCount(Math.min(100, howManyAggregates)); } @Override protected Object createMessageBody(long messageIndex) { UUID id = ids.get((int) messageIndex);
// Path: inventory-aggregate-root/src/main/java/org/myeslib/example/SampleDomain.java // @Value // public static class IncreaseInventory implements Command { // @NonNull // UUID commandId; // @NonNull // UUID id; // @NonNull // Integer howMany; // Long targetVersion; // } // Path: inventory-cmd-producer/src/main/java/org/myeslib/cmdproducer/datasets/IncreaseCommandDataSet.java import java.util.List; import java.util.UUID; import org.apache.camel.component.dataset.DataSetSupport; import org.myeslib.example.SampleDomain.IncreaseInventory; package org.myeslib.cmdproducer.datasets; public class IncreaseCommandDataSet extends DataSetSupport { public final List<UUID> ids ; public IncreaseCommandDataSet(List<UUID> ids, int howManyAggregates) { this.ids = ids; setSize(howManyAggregates); setReportCount(Math.min(100, howManyAggregates)); } @Override protected Object createMessageBody(long messageIndex) { UUID id = ids.get((int) messageIndex);
IncreaseInventory command = new IncreaseInventory(UUID.randomUUID(), id, 2, 1L);
rodolfodpk/myeslib
myeslib-util/src/main/java/org/myeslib/util/hazelcast/HzStringQueueStore.java
// Path: myeslib-util/src/main/java/org/myeslib/util/jdbi/ClobToStringMapper.java // public class ClobToStringMapper extends TypedMapper<String> { // // public ClobToStringMapper(){ // super(); // } // // public ClobToStringMapper(int index) // { // super(index); // } // // public ClobToStringMapper(String name) // { // super(name); // } // // @Override // protected String extractByName(ResultSet r, String name) throws SQLException { // Clob clob = r.getClob(name); // try { // return CharStreams.toString(clob.getCharacterStream()); // } catch (IOException e) { // e.printStackTrace(); // } finally { // clob.free(); // } // return null; // } // // @Override // protected String extractByIndex(ResultSet r, int index) throws SQLException { // Clob clob = r.getClob(index); // try { // return CharStreams.toString(clob.getCharacterStream()); // } catch (IOException e) { // e.printStackTrace(); // } finally { // clob.free(); // } // return null; // } // // public static final ClobToStringMapper FIRST = new ClobToStringMapper(); // }
import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.sql.DataSource; import lombok.extern.slf4j.Slf4j; import org.myeslib.util.jdbi.ClobToStringMapper; import org.skife.jdbi.v2.DBI; import org.skife.jdbi.v2.Handle; import org.skife.jdbi.v2.PreparedBatch; import org.skife.jdbi.v2.TransactionCallback; import org.skife.jdbi.v2.TransactionIsolationLevel; import org.skife.jdbi.v2.TransactionStatus; import org.skife.jdbi.v2.tweak.HandleCallback; import com.hazelcast.core.QueueStore;
public void delete(Long id) { deleteAll(Arrays.asList(id)); } @Override public void deleteAll(final Collection<Long> ids) { log.info(String.format("deleting all within table %s", tableName)); dbi.inTransaction(new TransactionCallback<Integer>() { @Override public Integer inTransaction(Handle h, TransactionStatus ts) throws Exception { PreparedBatch pb = h.prepareBatch(String.format("delete from %s where id = :id", tableName)); for (Long id: ids){ pb.add().bind("id", id); } return pb.execute().length; } }) ; } @Override public String load(final Long id) { String result = null; try { log.info("will load {} from table {}", id.toString(), tableName); result = dbi.inTransaction(TransactionIsolationLevel.READ_COMMITTED, new TransactionCallback<String>() { @Override public String inTransaction(Handle h, TransactionStatus ts) throws Exception { String sql = String.format("select value from %s where id = :id", tableName);
// Path: myeslib-util/src/main/java/org/myeslib/util/jdbi/ClobToStringMapper.java // public class ClobToStringMapper extends TypedMapper<String> { // // public ClobToStringMapper(){ // super(); // } // // public ClobToStringMapper(int index) // { // super(index); // } // // public ClobToStringMapper(String name) // { // super(name); // } // // @Override // protected String extractByName(ResultSet r, String name) throws SQLException { // Clob clob = r.getClob(name); // try { // return CharStreams.toString(clob.getCharacterStream()); // } catch (IOException e) { // e.printStackTrace(); // } finally { // clob.free(); // } // return null; // } // // @Override // protected String extractByIndex(ResultSet r, int index) throws SQLException { // Clob clob = r.getClob(index); // try { // return CharStreams.toString(clob.getCharacterStream()); // } catch (IOException e) { // e.printStackTrace(); // } finally { // clob.free(); // } // return null; // } // // public static final ClobToStringMapper FIRST = new ClobToStringMapper(); // } // Path: myeslib-util/src/main/java/org/myeslib/util/hazelcast/HzStringQueueStore.java import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.sql.DataSource; import lombok.extern.slf4j.Slf4j; import org.myeslib.util.jdbi.ClobToStringMapper; import org.skife.jdbi.v2.DBI; import org.skife.jdbi.v2.Handle; import org.skife.jdbi.v2.PreparedBatch; import org.skife.jdbi.v2.TransactionCallback; import org.skife.jdbi.v2.TransactionIsolationLevel; import org.skife.jdbi.v2.TransactionStatus; import org.skife.jdbi.v2.tweak.HandleCallback; import com.hazelcast.core.QueueStore; public void delete(Long id) { deleteAll(Arrays.asList(id)); } @Override public void deleteAll(final Collection<Long> ids) { log.info(String.format("deleting all within table %s", tableName)); dbi.inTransaction(new TransactionCallback<Integer>() { @Override public Integer inTransaction(Handle h, TransactionStatus ts) throws Exception { PreparedBatch pb = h.prepareBatch(String.format("delete from %s where id = :id", tableName)); for (Long id: ids){ pb.add().bind("id", id); } return pb.execute().length; } }) ; } @Override public String load(final Long id) { String result = null; try { log.info("will load {} from table {}", id.toString(), tableName); result = dbi.inTransaction(TransactionIsolationLevel.READ_COMMITTED, new TransactionCallback<String>() { @Override public String inTransaction(Handle h, TransactionStatus ts) throws Exception { String sql = String.format("select value from %s where id = :id", tableName);
return h.createQuery(sql).bind("id", id).map(ClobToStringMapper.FIRST).first();
rodolfodpk/myeslib
inventory-aggregate-root/src/test/java/org/myeslib/example/InventoryItemCommandHandlerTest.java
// Path: myeslib-core/src/main/java/org/myeslib/core/Event.java // public interface Event extends Serializable { // // } // // Path: inventory-aggregate-root/src/main/java/org/myeslib/example/SampleDomain.java // @AllArgsConstructor // public static class CreateCommandHandler implements CommandHandler<CreateInventoryItem> { // // @Delegate @NonNull // final InventoryItemAggregateRoot aggregateRoot; // @NonNull // final ItemDescriptionGeneratorService service; // // public List<? extends Event> handle(CreateInventoryItem command) { // checkArgument(getId() == null, "item already exists"); // checkNotNull(service); // String description = service.generate(command.getId()); // InventoryItemCreated event = new InventoryItemCreated(command.getId(), description); // return Arrays.asList(event); // } // } // // Path: inventory-aggregate-root/src/main/java/org/myeslib/example/SampleDomain.java // @Value // public static class CreateInventoryItem implements Command { // @NonNull // UUID commandId; // @NonNull // UUID id; // Long targetVersion = 0L; // } // // Path: inventory-aggregate-root/src/main/java/org/myeslib/example/SampleDomain.java // @AllArgsConstructor // public static class DecreaseCommandHandler implements CommandHandler<DecreaseInventory> { // // @Delegate @NonNull // final InventoryItemAggregateRoot aggregateRoot; // // public List<? extends Event> handle(DecreaseInventory command) { // checkArgument(getId() != null, "before decreasing you must create an item"); // checkArgument(getId().equals(command.getId()), "item id does not match"); // checkArgument(isAvailable(command.howMany), "there are not enough items available"); // InventoryDecreased event = new InventoryDecreased(command.getId(), command.getHowMany()); // return Arrays.asList(event); // } // } // // Path: inventory-aggregate-root/src/main/java/org/myeslib/example/SampleDomain.java // @Value // public static class DecreaseInventory implements Command { // @NonNull // UUID commandId; // @NonNull // UUID id; // @NonNull // Integer howMany; // Long targetVersion; // } // // Path: inventory-aggregate-root/src/main/java/org/myeslib/example/SampleDomain.java // @AllArgsConstructor // public static class IncreaseCommandHandler implements CommandHandler<IncreaseInventory> { // // @Delegate @NonNull // final InventoryItemAggregateRoot aggregateRoot; // // public List<? extends Event> handle(IncreaseInventory command) { // checkArgument(getId() != null, "before increasing you must create an item"); // checkArgument(getId().equals(command.getId()), "item id does not match"); // InventoryIncreased event = new InventoryIncreased(command.getId(), command.getHowMany()); // return Arrays.asList(event); // } // } // // Path: inventory-aggregate-root/src/main/java/org/myeslib/example/SampleDomain.java // @Value // public static class IncreaseInventory implements Command { // @NonNull // UUID commandId; // @NonNull // UUID id; // @NonNull // Integer howMany; // Long targetVersion; // } // // Path: inventory-aggregate-root/src/main/java/org/myeslib/example/SampleDomain.java // @Value // public static class InventoryDecreased implements Event { // @NonNull // UUID id; // @NonNull // Integer howMany; // } // // Path: inventory-aggregate-root/src/main/java/org/myeslib/example/SampleDomain.java // @Value // public static class InventoryIncreased implements Event { // @NonNull // UUID id; // @NonNull // Integer howMany; // } // // Path: inventory-aggregate-root/src/main/java/org/myeslib/example/SampleDomain.java // @Data // public static class InventoryItemAggregateRoot implements AggregateRoot { // // UUID id; // String description; // Integer available = 0; // // public void on(InventoryItemCreated event) { // this.id = event.id; // this.description = event.description; // this.available = 0; // } // // public void on(InventoryIncreased event) { // this.available = this.available + event.howMany; // } // // public void on(InventoryDecreased event) { // this.available = this.available - event.howMany; // } // // public boolean isAvailable(int howMany) { // return getAvailable() - howMany >= 0; // } // // } // // Path: inventory-aggregate-root/src/main/java/org/myeslib/example/SampleDomain.java // @Value // public static class InventoryItemCreated implements Event { // @NonNull // UUID id; // @NonNull // String description; // } // // Path: inventory-aggregate-root/src/main/java/org/myeslib/example/SampleDomain.java // public static interface ItemDescriptionGeneratorService { // String generate(UUID id); // }
import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.List; import java.util.UUID; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.myeslib.core.Event; import org.myeslib.example.SampleDomain.CreateCommandHandler; import org.myeslib.example.SampleDomain.CreateInventoryItem; import org.myeslib.example.SampleDomain.DecreaseCommandHandler; import org.myeslib.example.SampleDomain.DecreaseInventory; import org.myeslib.example.SampleDomain.IncreaseCommandHandler; import org.myeslib.example.SampleDomain.IncreaseInventory; import org.myeslib.example.SampleDomain.InventoryDecreased; import org.myeslib.example.SampleDomain.InventoryIncreased; import org.myeslib.example.SampleDomain.InventoryItemAggregateRoot; import org.myeslib.example.SampleDomain.InventoryItemCreated; import org.myeslib.example.SampleDomain.ItemDescriptionGeneratorService;
package org.myeslib.example; @RunWith(MockitoJUnitRunner.class) public class InventoryItemCommandHandlerTest { @Mock
// Path: myeslib-core/src/main/java/org/myeslib/core/Event.java // public interface Event extends Serializable { // // } // // Path: inventory-aggregate-root/src/main/java/org/myeslib/example/SampleDomain.java // @AllArgsConstructor // public static class CreateCommandHandler implements CommandHandler<CreateInventoryItem> { // // @Delegate @NonNull // final InventoryItemAggregateRoot aggregateRoot; // @NonNull // final ItemDescriptionGeneratorService service; // // public List<? extends Event> handle(CreateInventoryItem command) { // checkArgument(getId() == null, "item already exists"); // checkNotNull(service); // String description = service.generate(command.getId()); // InventoryItemCreated event = new InventoryItemCreated(command.getId(), description); // return Arrays.asList(event); // } // } // // Path: inventory-aggregate-root/src/main/java/org/myeslib/example/SampleDomain.java // @Value // public static class CreateInventoryItem implements Command { // @NonNull // UUID commandId; // @NonNull // UUID id; // Long targetVersion = 0L; // } // // Path: inventory-aggregate-root/src/main/java/org/myeslib/example/SampleDomain.java // @AllArgsConstructor // public static class DecreaseCommandHandler implements CommandHandler<DecreaseInventory> { // // @Delegate @NonNull // final InventoryItemAggregateRoot aggregateRoot; // // public List<? extends Event> handle(DecreaseInventory command) { // checkArgument(getId() != null, "before decreasing you must create an item"); // checkArgument(getId().equals(command.getId()), "item id does not match"); // checkArgument(isAvailable(command.howMany), "there are not enough items available"); // InventoryDecreased event = new InventoryDecreased(command.getId(), command.getHowMany()); // return Arrays.asList(event); // } // } // // Path: inventory-aggregate-root/src/main/java/org/myeslib/example/SampleDomain.java // @Value // public static class DecreaseInventory implements Command { // @NonNull // UUID commandId; // @NonNull // UUID id; // @NonNull // Integer howMany; // Long targetVersion; // } // // Path: inventory-aggregate-root/src/main/java/org/myeslib/example/SampleDomain.java // @AllArgsConstructor // public static class IncreaseCommandHandler implements CommandHandler<IncreaseInventory> { // // @Delegate @NonNull // final InventoryItemAggregateRoot aggregateRoot; // // public List<? extends Event> handle(IncreaseInventory command) { // checkArgument(getId() != null, "before increasing you must create an item"); // checkArgument(getId().equals(command.getId()), "item id does not match"); // InventoryIncreased event = new InventoryIncreased(command.getId(), command.getHowMany()); // return Arrays.asList(event); // } // } // // Path: inventory-aggregate-root/src/main/java/org/myeslib/example/SampleDomain.java // @Value // public static class IncreaseInventory implements Command { // @NonNull // UUID commandId; // @NonNull // UUID id; // @NonNull // Integer howMany; // Long targetVersion; // } // // Path: inventory-aggregate-root/src/main/java/org/myeslib/example/SampleDomain.java // @Value // public static class InventoryDecreased implements Event { // @NonNull // UUID id; // @NonNull // Integer howMany; // } // // Path: inventory-aggregate-root/src/main/java/org/myeslib/example/SampleDomain.java // @Value // public static class InventoryIncreased implements Event { // @NonNull // UUID id; // @NonNull // Integer howMany; // } // // Path: inventory-aggregate-root/src/main/java/org/myeslib/example/SampleDomain.java // @Data // public static class InventoryItemAggregateRoot implements AggregateRoot { // // UUID id; // String description; // Integer available = 0; // // public void on(InventoryItemCreated event) { // this.id = event.id; // this.description = event.description; // this.available = 0; // } // // public void on(InventoryIncreased event) { // this.available = this.available + event.howMany; // } // // public void on(InventoryDecreased event) { // this.available = this.available - event.howMany; // } // // public boolean isAvailable(int howMany) { // return getAvailable() - howMany >= 0; // } // // } // // Path: inventory-aggregate-root/src/main/java/org/myeslib/example/SampleDomain.java // @Value // public static class InventoryItemCreated implements Event { // @NonNull // UUID id; // @NonNull // String description; // } // // Path: inventory-aggregate-root/src/main/java/org/myeslib/example/SampleDomain.java // public static interface ItemDescriptionGeneratorService { // String generate(UUID id); // } // Path: inventory-aggregate-root/src/test/java/org/myeslib/example/InventoryItemCommandHandlerTest.java import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.List; import java.util.UUID; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.myeslib.core.Event; import org.myeslib.example.SampleDomain.CreateCommandHandler; import org.myeslib.example.SampleDomain.CreateInventoryItem; import org.myeslib.example.SampleDomain.DecreaseCommandHandler; import org.myeslib.example.SampleDomain.DecreaseInventory; import org.myeslib.example.SampleDomain.IncreaseCommandHandler; import org.myeslib.example.SampleDomain.IncreaseInventory; import org.myeslib.example.SampleDomain.InventoryDecreased; import org.myeslib.example.SampleDomain.InventoryIncreased; import org.myeslib.example.SampleDomain.InventoryItemAggregateRoot; import org.myeslib.example.SampleDomain.InventoryItemCreated; import org.myeslib.example.SampleDomain.ItemDescriptionGeneratorService; package org.myeslib.example; @RunWith(MockitoJUnitRunner.class) public class InventoryItemCommandHandlerTest { @Mock
ItemDescriptionGeneratorService uuidGeneratorService ;
rodolfodpk/myeslib
myeslib-util/src/main/java/org/myeslib/util/hazelcast/HzMapStore.java
// Path: myeslib-core/src/main/java/org/myeslib/core/data/AggregateRootHistory.java // @SuppressWarnings("serial") // @Data // public class AggregateRootHistory implements Serializable { // // private final List<UnitOfWork> unitsOfWork; // private final Set<UnitOfWork> persisted; // // public AggregateRootHistory() { // this.unitsOfWork = new LinkedList<>(); // this.persisted = new LinkedHashSet<>(); // } // // public List<Event> getAllEvents() { // return getEventsAfterUntil(0, Long.MAX_VALUE); // } // // public List<Event> getEventsAfterUntil(long afterVersion, long untilVersion){ // List<Event> events = new LinkedList<>(); // for (UnitOfWork t : unitsOfWork) { // if (t.getVersion() > afterVersion && t.getVersion() <= untilVersion){ // for (Event event : t.getEvents()) { // events.add(event); // } // } // } // return events; // } // // public List<Event> getEventsUntil(long version){ // List<Event> events = new LinkedList<>(); // for (UnitOfWork t : unitsOfWork) { // if (t.getVersion() <= version){ // for (Event event : t.getEvents()) { // events.add(event); // } // } // } // return events; // } // // public Long getLastVersion() { // return unitsOfWork.size()==0 ? 0 : unitsOfWork.get(unitsOfWork.size()-1).getVersion(); // } // // public void add(final UnitOfWork transaction) { // checkNotNull(transaction); // unitsOfWork.add(transaction); // } // // public UnitOfWork getLastUnitOfWork() { // return unitsOfWork.get(unitsOfWork.size()-1); // } // // public List<UnitOfWork> getPendingOfPersistence() { // return Lists.newLinkedList(Sets.difference(Sets.newLinkedHashSet(unitsOfWork), persisted)); // } // // public void markAsPersisted(UnitOfWork uow) { // checkArgument(unitsOfWork.contains(uow), "unitOfWork must be part of this AggregateRootHistory in order to be marked as persisted"); // persisted.add(uow); // } // // } // // Path: myeslib-core/src/main/java/org/myeslib/core/data/UnitOfWork.java // @SuppressWarnings("serial") // @Value // public class UnitOfWork implements Comparable<UnitOfWork>, Serializable { // // final UUID id; // final Command command; // final List<? extends Event> events; // final long version; // // public UnitOfWork(UUID id, Command command, Long version, List<? extends Event> events) { // checkNotNull(id, "id cannot be null"); // checkNotNull(command, "command cannot be null"); // checkArgument(command.getTargetVersion()>=0, "target version must be >= 0"); // checkArgument(version>0, "invalid version"); // checkNotNull(events, "events cannot be null"); // for (Event e: events){ // checkNotNull(e, "event within events list cannot be null"); // } // this.id = id; // this.command = command; // this.version = version; // this.events = events; // } // // public static UnitOfWork create(UUID id, Command command, List<? extends Event> newEvents) { // checkNotNull(command.getTargetVersion(), "target version cannot be null"); // checkArgument(command.getTargetVersion()>=0, "target version must be >= 0"); // return new UnitOfWork(id, command, command.getTargetVersion()+1, newEvents); // } // // public List<Event> getEvents(){ // List<Event> result = new LinkedList<>(); // for (Event event : events) { // result.add(event); // } // return result; // } // // public int compareTo(UnitOfWork other) { // if (version < other.version) { // return -1; // } else if (version > other.version) { // return 1; // } // return 0; // } // // public Long getTargetVersion() { // return command.getTargetVersion(); // } // } // // Path: myeslib-util/src/main/java/org/myeslib/util/jdbi/AggregateRootHistoryReaderDao.java // public interface AggregateRootHistoryReaderDao<K> { // // AggregateRootHistory get(K id); // // } // // Path: myeslib-util/src/main/java/org/myeslib/util/jdbi/UnitOfWorkJournalDao.java // public interface UnitOfWorkJournalDao<K> { // // void append(K id, UnitOfWork uow); // // }
import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import lombok.extern.slf4j.Slf4j; import org.myeslib.core.data.AggregateRootHistory; import org.myeslib.core.data.UnitOfWork; import org.myeslib.util.jdbi.AggregateRootHistoryReaderDao; import org.myeslib.util.jdbi.UnitOfWorkJournalDao; import com.google.inject.Inject; import com.hazelcast.core.MapStore; import com.hazelcast.core.PostProcessingMapStore;
package org.myeslib.util.hazelcast; @Slf4j public class HzMapStore implements MapStore<UUID, AggregateRootHistory>, PostProcessingMapStore{
// Path: myeslib-core/src/main/java/org/myeslib/core/data/AggregateRootHistory.java // @SuppressWarnings("serial") // @Data // public class AggregateRootHistory implements Serializable { // // private final List<UnitOfWork> unitsOfWork; // private final Set<UnitOfWork> persisted; // // public AggregateRootHistory() { // this.unitsOfWork = new LinkedList<>(); // this.persisted = new LinkedHashSet<>(); // } // // public List<Event> getAllEvents() { // return getEventsAfterUntil(0, Long.MAX_VALUE); // } // // public List<Event> getEventsAfterUntil(long afterVersion, long untilVersion){ // List<Event> events = new LinkedList<>(); // for (UnitOfWork t : unitsOfWork) { // if (t.getVersion() > afterVersion && t.getVersion() <= untilVersion){ // for (Event event : t.getEvents()) { // events.add(event); // } // } // } // return events; // } // // public List<Event> getEventsUntil(long version){ // List<Event> events = new LinkedList<>(); // for (UnitOfWork t : unitsOfWork) { // if (t.getVersion() <= version){ // for (Event event : t.getEvents()) { // events.add(event); // } // } // } // return events; // } // // public Long getLastVersion() { // return unitsOfWork.size()==0 ? 0 : unitsOfWork.get(unitsOfWork.size()-1).getVersion(); // } // // public void add(final UnitOfWork transaction) { // checkNotNull(transaction); // unitsOfWork.add(transaction); // } // // public UnitOfWork getLastUnitOfWork() { // return unitsOfWork.get(unitsOfWork.size()-1); // } // // public List<UnitOfWork> getPendingOfPersistence() { // return Lists.newLinkedList(Sets.difference(Sets.newLinkedHashSet(unitsOfWork), persisted)); // } // // public void markAsPersisted(UnitOfWork uow) { // checkArgument(unitsOfWork.contains(uow), "unitOfWork must be part of this AggregateRootHistory in order to be marked as persisted"); // persisted.add(uow); // } // // } // // Path: myeslib-core/src/main/java/org/myeslib/core/data/UnitOfWork.java // @SuppressWarnings("serial") // @Value // public class UnitOfWork implements Comparable<UnitOfWork>, Serializable { // // final UUID id; // final Command command; // final List<? extends Event> events; // final long version; // // public UnitOfWork(UUID id, Command command, Long version, List<? extends Event> events) { // checkNotNull(id, "id cannot be null"); // checkNotNull(command, "command cannot be null"); // checkArgument(command.getTargetVersion()>=0, "target version must be >= 0"); // checkArgument(version>0, "invalid version"); // checkNotNull(events, "events cannot be null"); // for (Event e: events){ // checkNotNull(e, "event within events list cannot be null"); // } // this.id = id; // this.command = command; // this.version = version; // this.events = events; // } // // public static UnitOfWork create(UUID id, Command command, List<? extends Event> newEvents) { // checkNotNull(command.getTargetVersion(), "target version cannot be null"); // checkArgument(command.getTargetVersion()>=0, "target version must be >= 0"); // return new UnitOfWork(id, command, command.getTargetVersion()+1, newEvents); // } // // public List<Event> getEvents(){ // List<Event> result = new LinkedList<>(); // for (Event event : events) { // result.add(event); // } // return result; // } // // public int compareTo(UnitOfWork other) { // if (version < other.version) { // return -1; // } else if (version > other.version) { // return 1; // } // return 0; // } // // public Long getTargetVersion() { // return command.getTargetVersion(); // } // } // // Path: myeslib-util/src/main/java/org/myeslib/util/jdbi/AggregateRootHistoryReaderDao.java // public interface AggregateRootHistoryReaderDao<K> { // // AggregateRootHistory get(K id); // // } // // Path: myeslib-util/src/main/java/org/myeslib/util/jdbi/UnitOfWorkJournalDao.java // public interface UnitOfWorkJournalDao<K> { // // void append(K id, UnitOfWork uow); // // } // Path: myeslib-util/src/main/java/org/myeslib/util/hazelcast/HzMapStore.java import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import lombok.extern.slf4j.Slf4j; import org.myeslib.core.data.AggregateRootHistory; import org.myeslib.core.data.UnitOfWork; import org.myeslib.util.jdbi.AggregateRootHistoryReaderDao; import org.myeslib.util.jdbi.UnitOfWorkJournalDao; import com.google.inject.Inject; import com.hazelcast.core.MapStore; import com.hazelcast.core.PostProcessingMapStore; package org.myeslib.util.hazelcast; @Slf4j public class HzMapStore implements MapStore<UUID, AggregateRootHistory>, PostProcessingMapStore{
private final UnitOfWorkJournalDao<UUID> writer;
rodolfodpk/myeslib
myeslib-util/src/main/java/org/myeslib/util/hazelcast/HzMapStore.java
// Path: myeslib-core/src/main/java/org/myeslib/core/data/AggregateRootHistory.java // @SuppressWarnings("serial") // @Data // public class AggregateRootHistory implements Serializable { // // private final List<UnitOfWork> unitsOfWork; // private final Set<UnitOfWork> persisted; // // public AggregateRootHistory() { // this.unitsOfWork = new LinkedList<>(); // this.persisted = new LinkedHashSet<>(); // } // // public List<Event> getAllEvents() { // return getEventsAfterUntil(0, Long.MAX_VALUE); // } // // public List<Event> getEventsAfterUntil(long afterVersion, long untilVersion){ // List<Event> events = new LinkedList<>(); // for (UnitOfWork t : unitsOfWork) { // if (t.getVersion() > afterVersion && t.getVersion() <= untilVersion){ // for (Event event : t.getEvents()) { // events.add(event); // } // } // } // return events; // } // // public List<Event> getEventsUntil(long version){ // List<Event> events = new LinkedList<>(); // for (UnitOfWork t : unitsOfWork) { // if (t.getVersion() <= version){ // for (Event event : t.getEvents()) { // events.add(event); // } // } // } // return events; // } // // public Long getLastVersion() { // return unitsOfWork.size()==0 ? 0 : unitsOfWork.get(unitsOfWork.size()-1).getVersion(); // } // // public void add(final UnitOfWork transaction) { // checkNotNull(transaction); // unitsOfWork.add(transaction); // } // // public UnitOfWork getLastUnitOfWork() { // return unitsOfWork.get(unitsOfWork.size()-1); // } // // public List<UnitOfWork> getPendingOfPersistence() { // return Lists.newLinkedList(Sets.difference(Sets.newLinkedHashSet(unitsOfWork), persisted)); // } // // public void markAsPersisted(UnitOfWork uow) { // checkArgument(unitsOfWork.contains(uow), "unitOfWork must be part of this AggregateRootHistory in order to be marked as persisted"); // persisted.add(uow); // } // // } // // Path: myeslib-core/src/main/java/org/myeslib/core/data/UnitOfWork.java // @SuppressWarnings("serial") // @Value // public class UnitOfWork implements Comparable<UnitOfWork>, Serializable { // // final UUID id; // final Command command; // final List<? extends Event> events; // final long version; // // public UnitOfWork(UUID id, Command command, Long version, List<? extends Event> events) { // checkNotNull(id, "id cannot be null"); // checkNotNull(command, "command cannot be null"); // checkArgument(command.getTargetVersion()>=0, "target version must be >= 0"); // checkArgument(version>0, "invalid version"); // checkNotNull(events, "events cannot be null"); // for (Event e: events){ // checkNotNull(e, "event within events list cannot be null"); // } // this.id = id; // this.command = command; // this.version = version; // this.events = events; // } // // public static UnitOfWork create(UUID id, Command command, List<? extends Event> newEvents) { // checkNotNull(command.getTargetVersion(), "target version cannot be null"); // checkArgument(command.getTargetVersion()>=0, "target version must be >= 0"); // return new UnitOfWork(id, command, command.getTargetVersion()+1, newEvents); // } // // public List<Event> getEvents(){ // List<Event> result = new LinkedList<>(); // for (Event event : events) { // result.add(event); // } // return result; // } // // public int compareTo(UnitOfWork other) { // if (version < other.version) { // return -1; // } else if (version > other.version) { // return 1; // } // return 0; // } // // public Long getTargetVersion() { // return command.getTargetVersion(); // } // } // // Path: myeslib-util/src/main/java/org/myeslib/util/jdbi/AggregateRootHistoryReaderDao.java // public interface AggregateRootHistoryReaderDao<K> { // // AggregateRootHistory get(K id); // // } // // Path: myeslib-util/src/main/java/org/myeslib/util/jdbi/UnitOfWorkJournalDao.java // public interface UnitOfWorkJournalDao<K> { // // void append(K id, UnitOfWork uow); // // }
import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import lombok.extern.slf4j.Slf4j; import org.myeslib.core.data.AggregateRootHistory; import org.myeslib.core.data.UnitOfWork; import org.myeslib.util.jdbi.AggregateRootHistoryReaderDao; import org.myeslib.util.jdbi.UnitOfWorkJournalDao; import com.google.inject.Inject; import com.hazelcast.core.MapStore; import com.hazelcast.core.PostProcessingMapStore;
package org.myeslib.util.hazelcast; @Slf4j public class HzMapStore implements MapStore<UUID, AggregateRootHistory>, PostProcessingMapStore{ private final UnitOfWorkJournalDao<UUID> writer;
// Path: myeslib-core/src/main/java/org/myeslib/core/data/AggregateRootHistory.java // @SuppressWarnings("serial") // @Data // public class AggregateRootHistory implements Serializable { // // private final List<UnitOfWork> unitsOfWork; // private final Set<UnitOfWork> persisted; // // public AggregateRootHistory() { // this.unitsOfWork = new LinkedList<>(); // this.persisted = new LinkedHashSet<>(); // } // // public List<Event> getAllEvents() { // return getEventsAfterUntil(0, Long.MAX_VALUE); // } // // public List<Event> getEventsAfterUntil(long afterVersion, long untilVersion){ // List<Event> events = new LinkedList<>(); // for (UnitOfWork t : unitsOfWork) { // if (t.getVersion() > afterVersion && t.getVersion() <= untilVersion){ // for (Event event : t.getEvents()) { // events.add(event); // } // } // } // return events; // } // // public List<Event> getEventsUntil(long version){ // List<Event> events = new LinkedList<>(); // for (UnitOfWork t : unitsOfWork) { // if (t.getVersion() <= version){ // for (Event event : t.getEvents()) { // events.add(event); // } // } // } // return events; // } // // public Long getLastVersion() { // return unitsOfWork.size()==0 ? 0 : unitsOfWork.get(unitsOfWork.size()-1).getVersion(); // } // // public void add(final UnitOfWork transaction) { // checkNotNull(transaction); // unitsOfWork.add(transaction); // } // // public UnitOfWork getLastUnitOfWork() { // return unitsOfWork.get(unitsOfWork.size()-1); // } // // public List<UnitOfWork> getPendingOfPersistence() { // return Lists.newLinkedList(Sets.difference(Sets.newLinkedHashSet(unitsOfWork), persisted)); // } // // public void markAsPersisted(UnitOfWork uow) { // checkArgument(unitsOfWork.contains(uow), "unitOfWork must be part of this AggregateRootHistory in order to be marked as persisted"); // persisted.add(uow); // } // // } // // Path: myeslib-core/src/main/java/org/myeslib/core/data/UnitOfWork.java // @SuppressWarnings("serial") // @Value // public class UnitOfWork implements Comparable<UnitOfWork>, Serializable { // // final UUID id; // final Command command; // final List<? extends Event> events; // final long version; // // public UnitOfWork(UUID id, Command command, Long version, List<? extends Event> events) { // checkNotNull(id, "id cannot be null"); // checkNotNull(command, "command cannot be null"); // checkArgument(command.getTargetVersion()>=0, "target version must be >= 0"); // checkArgument(version>0, "invalid version"); // checkNotNull(events, "events cannot be null"); // for (Event e: events){ // checkNotNull(e, "event within events list cannot be null"); // } // this.id = id; // this.command = command; // this.version = version; // this.events = events; // } // // public static UnitOfWork create(UUID id, Command command, List<? extends Event> newEvents) { // checkNotNull(command.getTargetVersion(), "target version cannot be null"); // checkArgument(command.getTargetVersion()>=0, "target version must be >= 0"); // return new UnitOfWork(id, command, command.getTargetVersion()+1, newEvents); // } // // public List<Event> getEvents(){ // List<Event> result = new LinkedList<>(); // for (Event event : events) { // result.add(event); // } // return result; // } // // public int compareTo(UnitOfWork other) { // if (version < other.version) { // return -1; // } else if (version > other.version) { // return 1; // } // return 0; // } // // public Long getTargetVersion() { // return command.getTargetVersion(); // } // } // // Path: myeslib-util/src/main/java/org/myeslib/util/jdbi/AggregateRootHistoryReaderDao.java // public interface AggregateRootHistoryReaderDao<K> { // // AggregateRootHistory get(K id); // // } // // Path: myeslib-util/src/main/java/org/myeslib/util/jdbi/UnitOfWorkJournalDao.java // public interface UnitOfWorkJournalDao<K> { // // void append(K id, UnitOfWork uow); // // } // Path: myeslib-util/src/main/java/org/myeslib/util/hazelcast/HzMapStore.java import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import lombok.extern.slf4j.Slf4j; import org.myeslib.core.data.AggregateRootHistory; import org.myeslib.core.data.UnitOfWork; import org.myeslib.util.jdbi.AggregateRootHistoryReaderDao; import org.myeslib.util.jdbi.UnitOfWorkJournalDao; import com.google.inject.Inject; import com.hazelcast.core.MapStore; import com.hazelcast.core.PostProcessingMapStore; package org.myeslib.util.hazelcast; @Slf4j public class HzMapStore implements MapStore<UUID, AggregateRootHistory>, PostProcessingMapStore{ private final UnitOfWorkJournalDao<UUID> writer;
private final AggregateRootHistoryReaderDao<UUID> reader;