answer
stringlengths
17
10.2M
package com.canoo.dolphin.client.javafx; import com.canoo.dolphin.collections.ObservableList; import com.canoo.dolphin.impl.collections.ObservableArrayList; import com.canoo.dolphin.mapping.Property; import javafx.beans.property.*; import javafx.beans.value.WritableBooleanValue; import javafx.beans.value.WritableDoubleValue; import javafx.beans.value.WritableIntegerValue; import javafx.beans.value.WritableStringValue; import javafx.collections.FXCollections; import org.testng.annotations.Test; import java.util.Arrays; import static org.testng.Assert.*; public class FXBinderTest { private final static double EPSILON = 1e-10; @Test public void testJavaFXDoubleUnidirectional() { Property<Double> doubleDolphinProperty = new MockedProperty<>(); Property<Number> numberDolphinProperty = new MockedProperty<>(); DoubleProperty doubleJavaFXProperty = new SimpleDoubleProperty(); WritableDoubleValue writableDoubleValue = new SimpleDoubleProperty(); doubleDolphinProperty.set(47.0); assertNotEquals(doubleJavaFXProperty.doubleValue(), 47.0, EPSILON); Binding binding = FXBinder.bind(doubleJavaFXProperty).to(doubleDolphinProperty); assertEquals(doubleJavaFXProperty.doubleValue(), 47.0, EPSILON); doubleDolphinProperty.set(100.0); assertEquals(doubleJavaFXProperty.doubleValue(), 100.0, EPSILON); doubleDolphinProperty.set(null); assertEquals(doubleJavaFXProperty.doubleValue(), 0.0, EPSILON); binding.unbind(); doubleDolphinProperty.set(100.0); assertEquals(doubleJavaFXProperty.doubleValue(), 0.0, EPSILON); numberDolphinProperty.set(12.0); binding = FXBinder.bind(doubleJavaFXProperty).to(numberDolphinProperty); assertEquals(doubleJavaFXProperty.doubleValue(), 12.0, EPSILON); numberDolphinProperty.set(null); assertEquals(doubleJavaFXProperty.doubleValue(), 0.0, EPSILON); binding.unbind(); numberDolphinProperty.set(100.0); assertEquals(doubleJavaFXProperty.doubleValue(), 0.0, EPSILON); doubleDolphinProperty.set(47.0); binding = FXBinder.bind(writableDoubleValue).to(doubleDolphinProperty); assertEquals(writableDoubleValue.get(), 47.0, EPSILON); doubleDolphinProperty.set(100.0); assertEquals(writableDoubleValue.get(), 100.0, EPSILON); doubleDolphinProperty.set(null); assertEquals(writableDoubleValue.get(), 0.0, EPSILON); binding.unbind(); doubleDolphinProperty.set(100.0); assertEquals(writableDoubleValue.get(), 0.0, EPSILON); } @Test public void testJavaFXDoubleBidirectional() { Property<Double> doubleDolphinProperty = new MockedProperty<>(); Property<Number> numberDolphinProperty = new MockedProperty<>(); DoubleProperty doubleJavaFXProperty = new SimpleDoubleProperty(); doubleDolphinProperty.set(47.0); assertNotEquals(doubleJavaFXProperty.doubleValue(), 47.0, EPSILON); Binding binding = FXBinder.bind(doubleJavaFXProperty).bidirectionalToNumeric(doubleDolphinProperty); assertEquals(doubleJavaFXProperty.doubleValue(), 47.0, EPSILON); doubleDolphinProperty.set(100.0); assertEquals(doubleJavaFXProperty.doubleValue(), 100.0, EPSILON); doubleDolphinProperty.set(null); assertEquals(doubleJavaFXProperty.doubleValue(), 0.0, EPSILON); doubleJavaFXProperty.set(12.0); assertEquals(doubleDolphinProperty.get().doubleValue(), 12.0, EPSILON); doubleJavaFXProperty.setValue(null); assertEquals(doubleDolphinProperty.get().doubleValue(), 0.0, EPSILON); binding.unbind(); doubleDolphinProperty.set(100.0); assertEquals(doubleJavaFXProperty.doubleValue(), 0.0, EPSILON); numberDolphinProperty.set(12.0); binding = FXBinder.bind(doubleJavaFXProperty).bidirectionalTo(numberDolphinProperty); assertEquals(doubleJavaFXProperty.doubleValue(), 12.0, EPSILON); numberDolphinProperty.set(null); assertEquals(doubleJavaFXProperty.doubleValue(), 0.0, EPSILON); doubleJavaFXProperty.set(12.0); assertEquals(numberDolphinProperty.get().doubleValue(), 12.0, EPSILON); doubleJavaFXProperty.setValue(null); assertEquals(numberDolphinProperty.get().doubleValue(), 0.0, EPSILON); binding.unbind(); numberDolphinProperty.set(100.0); assertEquals(doubleJavaFXProperty.doubleValue(), 0.0, EPSILON); } @Test public void testJavaFXDoubleUnidirectionalWithConverter() { Property<String> stringDolphinProperty = new MockedProperty<>(); DoubleProperty doubleJavaFXProperty = new SimpleDoubleProperty(); WritableDoubleValue writableDoubleValue = new SimpleDoubleProperty(); Converter<String, Double> stringDoubleConverter = s -> s == null ? null : Double.parseDouble(s); stringDolphinProperty.set("47.0"); assertNotEquals(doubleJavaFXProperty.doubleValue(), 47.0, EPSILON); Binding binding = FXBinder.bind(doubleJavaFXProperty).to(stringDolphinProperty, stringDoubleConverter); assertEquals(doubleJavaFXProperty.doubleValue(), 47.0, EPSILON); stringDolphinProperty.set("100.0"); assertEquals(doubleJavaFXProperty.doubleValue(), 100.0, EPSILON); stringDolphinProperty.set(null); assertEquals(doubleJavaFXProperty.doubleValue(), 0.0, EPSILON); binding.unbind(); stringDolphinProperty.set("100.0"); assertEquals(doubleJavaFXProperty.doubleValue(), 0.0, EPSILON); stringDolphinProperty.set("12.0"); binding = FXBinder.bind(doubleJavaFXProperty).to(stringDolphinProperty, stringDoubleConverter); assertEquals(doubleJavaFXProperty.doubleValue(), 12.0, EPSILON); stringDolphinProperty.set(null); assertEquals(doubleJavaFXProperty.doubleValue(), 0.0, EPSILON); binding.unbind(); stringDolphinProperty.set("100.0"); assertEquals(doubleJavaFXProperty.doubleValue(), 0.0, EPSILON); stringDolphinProperty.set("47.0"); binding = FXBinder.bind(writableDoubleValue).to(stringDolphinProperty, stringDoubleConverter); assertEquals(writableDoubleValue.get(), 47.0, EPSILON); stringDolphinProperty.set("100.0"); assertEquals(writableDoubleValue.get(), 100.0, EPSILON); stringDolphinProperty.set(null); assertEquals(writableDoubleValue.get(), 0.0, EPSILON); binding.unbind(); stringDolphinProperty.set("100.0"); assertEquals(writableDoubleValue.get(), 0.0, EPSILON); } @Test public void testJavaFXDoubleBidirectionalWithConverter() { Property<String> stringDolphinProperty = new MockedProperty<>(); DoubleProperty doubleJavaFXProperty = new SimpleDoubleProperty(); Converter<String, Double> stringDoubleConverter = s -> s == null ? null : Double.parseDouble(s); Converter<Double, String> doubleStringConverter = d -> d == null ? null : d.toString(); BidirectionalConverter<String, Double> doubleBidirectionalConverter = new DefaultBidirectionalConverter<>(stringDoubleConverter, doubleStringConverter); stringDolphinProperty.set("47.0"); assertNotEquals(doubleJavaFXProperty.doubleValue(), 47.0, EPSILON); Binding binding = FXBinder.bind(doubleJavaFXProperty).bidirectionalToNumeric(stringDolphinProperty, doubleBidirectionalConverter); assertEquals(doubleJavaFXProperty.doubleValue(), 47.0, EPSILON); stringDolphinProperty.set("100.0"); assertEquals(doubleJavaFXProperty.doubleValue(), 100.0, EPSILON); stringDolphinProperty.set(null); assertEquals(doubleJavaFXProperty.doubleValue(), 0.0, EPSILON); doubleJavaFXProperty.set(12.0); assertEquals(stringDolphinProperty.get(), "12.0"); doubleJavaFXProperty.setValue(null); assertEquals(stringDolphinProperty.get(), "0.0"); binding.unbind(); stringDolphinProperty.set("100.0"); assertEquals(doubleJavaFXProperty.doubleValue(), 0.0, EPSILON); } @Test public void testJavaFXBooleanUnidirectional() { Property<Boolean> booleanDolphinProperty = new MockedProperty<>(); BooleanProperty booleanJavaFXProperty = new SimpleBooleanProperty(); WritableBooleanValue writableBooleanValue = new SimpleBooleanProperty(); booleanDolphinProperty.set(true); assertNotEquals(booleanJavaFXProperty.get(), true); Binding binding = FXBinder.bind(booleanJavaFXProperty).to(booleanDolphinProperty); assertEquals(booleanJavaFXProperty.get(), true); booleanDolphinProperty.set(false); assertEquals(booleanJavaFXProperty.get(), false); booleanDolphinProperty.set(null); assertEquals(booleanJavaFXProperty.get(), false); binding.unbind(); booleanDolphinProperty.set(true); assertEquals(booleanJavaFXProperty.get(), false); binding = FXBinder.bind(writableBooleanValue).to(booleanDolphinProperty); assertEquals(writableBooleanValue.get(), true); booleanDolphinProperty.set(false); assertEquals(writableBooleanValue.get(), false); booleanDolphinProperty.set(null); assertEquals(writableBooleanValue.get(), false); binding.unbind(); booleanDolphinProperty.set(true); assertEquals(writableBooleanValue.get(), false); } @Test public void testJavaFXBooleanUnidirectionalWithConverter() { Property<String> stringDolphinProperty = new MockedProperty<>(); BooleanProperty booleanJavaFXProperty = new SimpleBooleanProperty(); WritableBooleanValue writableBooleanValue = new SimpleBooleanProperty(); Converter<String, Boolean> stringBooleanConverter = s -> s == null ? null : Boolean.parseBoolean(s); stringDolphinProperty.set("Hello"); assertEquals(booleanJavaFXProperty.get(), false); Binding binding = FXBinder.bind(booleanJavaFXProperty).to(stringDolphinProperty, stringBooleanConverter); assertEquals(booleanJavaFXProperty.get(), false); stringDolphinProperty.set("true"); assertEquals(booleanJavaFXProperty.get(), true); stringDolphinProperty.set(null); assertEquals(booleanJavaFXProperty.get(), false); binding.unbind(); stringDolphinProperty.set("true"); assertEquals(booleanJavaFXProperty.get(), false); stringDolphinProperty.set("false"); binding = FXBinder.bind(writableBooleanValue).to(stringDolphinProperty, stringBooleanConverter); assertEquals(writableBooleanValue.get(), false); stringDolphinProperty.set("true"); assertEquals(writableBooleanValue.get(), true); stringDolphinProperty.set(null); assertEquals(writableBooleanValue.get(), false); binding.unbind(); stringDolphinProperty.set("true"); assertEquals(writableBooleanValue.get(), false); } @Test public void testJavaFXBooleanBidirectional() { Property<Boolean> booleanDolphinProperty = new MockedProperty<>(); BooleanProperty booleanJavaFXProperty = new SimpleBooleanProperty(); booleanDolphinProperty.set(true); assertNotEquals(booleanJavaFXProperty.get(), true); Binding binding = FXBinder.bind(booleanJavaFXProperty).bidirectionalTo(booleanDolphinProperty); assertEquals(booleanJavaFXProperty.get(), true); booleanDolphinProperty.set(false); assertEquals(booleanJavaFXProperty.get(), false); booleanDolphinProperty.set(null); assertEquals(booleanJavaFXProperty.get(), false); booleanJavaFXProperty.set(true); assertEquals(booleanDolphinProperty.get().booleanValue(), true); booleanJavaFXProperty.setValue(null); assertEquals(booleanDolphinProperty.get().booleanValue(), false); binding.unbind(); booleanDolphinProperty.set(true); assertEquals(booleanJavaFXProperty.get(), false); } @Test public void testJavaFXBooleanBidirectionalWithConverter() { Property<String> stringDolphinProperty = new MockedProperty<>(); BooleanProperty booleanJavaFXProperty = new SimpleBooleanProperty(); Converter<Boolean, String> booleanStringConverter = b -> b == null ? null : b.toString(); Converter<String, Boolean> stringBooleanConverter = s -> s == null ? null : Boolean.parseBoolean(s); BidirectionalConverter<Boolean, String> booleanStringBidirectionalConverter = new DefaultBidirectionalConverter<>(booleanStringConverter, stringBooleanConverter); stringDolphinProperty.set("true"); assertNotEquals(booleanJavaFXProperty.get(), true); Binding binding = FXBinder.bind(booleanJavaFXProperty).bidirectionalTo(stringDolphinProperty, booleanStringBidirectionalConverter.invert()); assertEquals(booleanJavaFXProperty.get(), true); stringDolphinProperty.set("false"); assertEquals(booleanJavaFXProperty.get(), false); stringDolphinProperty.set(null); assertEquals(booleanJavaFXProperty.get(), false); booleanJavaFXProperty.set(true); assertEquals(stringDolphinProperty.get(), "true"); booleanJavaFXProperty.setValue(null); assertEquals(stringDolphinProperty.get(), "false"); binding.unbind(); stringDolphinProperty.set("true"); assertEquals(booleanJavaFXProperty.get(), false); } @Test public void testJavaFXStringUnidirectional() { Property<String> stringDolphinProperty = new MockedProperty<>(); StringProperty stringJavaFXProperty = new SimpleStringProperty(); WritableStringValue writableStringValue = new SimpleStringProperty(); stringDolphinProperty.set("Hello"); assertNotEquals(stringJavaFXProperty.get(), "Hello"); Binding binding = FXBinder.bind(stringJavaFXProperty).to(stringDolphinProperty); assertEquals(stringJavaFXProperty.get(), "Hello"); stringDolphinProperty.set("Hello JavaFX"); assertEquals(stringJavaFXProperty.get(), "Hello JavaFX"); stringDolphinProperty.set(null); assertEquals(stringJavaFXProperty.get(), null); binding.unbind(); stringDolphinProperty.set("Hello JavaFX"); assertEquals(stringJavaFXProperty.get(), null); binding = FXBinder.bind(writableStringValue).to(stringDolphinProperty); assertEquals(writableStringValue.get(), "Hello JavaFX"); stringDolphinProperty.set("Dolphin Platform"); assertEquals(writableStringValue.get(), "Dolphin Platform"); stringDolphinProperty.set(null); assertEquals(writableStringValue.get(), null); binding.unbind(); stringDolphinProperty.set("Dolphin Platform"); assertEquals(writableStringValue.get(), null); } @Test public void testJavaFXStringBidirectional() { Property<String> stringDolphinProperty = new MockedProperty<>(); StringProperty stringJavaFXProperty = new SimpleStringProperty(); stringDolphinProperty.set("Hello"); assertNotEquals(stringJavaFXProperty.get(), "Hello"); Binding binding = FXBinder.bind(stringJavaFXProperty).bidirectionalTo(stringDolphinProperty); assertEquals(stringJavaFXProperty.get(), "Hello"); stringDolphinProperty.set("Hello World"); assertEquals(stringJavaFXProperty.get(), "Hello World"); stringDolphinProperty.set(null); assertEquals(stringJavaFXProperty.get(), null); stringJavaFXProperty.set("Hello from JavaFX"); assertEquals(stringDolphinProperty.get(), "Hello from JavaFX"); stringJavaFXProperty.setValue(null); assertEquals(stringDolphinProperty.get(), null); binding.unbind(); stringDolphinProperty.set("Hello Dolphin"); assertEquals(stringJavaFXProperty.get(), null); } @Test public void testJavaFXIntegerUnidirectional() { Property<Integer> integerDolphinProperty = new MockedProperty<>(); Property<Number> numberDolphinProperty = new MockedProperty<>(); IntegerProperty integerJavaFXProperty = new SimpleIntegerProperty(); WritableIntegerValue writableIntegerValue = new SimpleIntegerProperty(); integerDolphinProperty.set(47); assertNotEquals(integerJavaFXProperty.doubleValue(), 47); Binding binding = FXBinder.bind(integerJavaFXProperty).to(integerDolphinProperty); assertEquals(integerJavaFXProperty.get(), 47); integerDolphinProperty.set(100); assertEquals(integerJavaFXProperty.get(), 100); integerDolphinProperty.set(null); assertEquals(integerJavaFXProperty.get(), 0); binding.unbind(); integerDolphinProperty.set(100); assertEquals(integerJavaFXProperty.get(), 0); numberDolphinProperty.set(12); binding = FXBinder.bind(integerJavaFXProperty).to(numberDolphinProperty); assertEquals(integerJavaFXProperty.get(), 12); numberDolphinProperty.set(null); assertEquals(integerJavaFXProperty.get(), 0); binding.unbind(); numberDolphinProperty.set(100); assertEquals(integerJavaFXProperty.get(), 0); integerDolphinProperty.set(47); binding = FXBinder.bind(writableIntegerValue).to(integerDolphinProperty); assertEquals(writableIntegerValue.get(), 47); integerDolphinProperty.set(100); assertEquals(writableIntegerValue.get(), 100); integerDolphinProperty.set(null); assertEquals(writableIntegerValue.get(), 0); binding.unbind(); integerDolphinProperty.set(100); assertEquals(writableIntegerValue.get(), 0); } @Test public void testJavaFXIntegerBidirectional() { Property<Integer> integerDolphinProperty = new MockedProperty<>(); Property<Number> numberDolphinProperty = new MockedProperty<>(); IntegerProperty integerJavaFXProperty = new SimpleIntegerProperty(); integerDolphinProperty.set(47); assertNotEquals(integerJavaFXProperty.get(), 47); Binding binding = FXBinder.bind(integerJavaFXProperty).bidirectionalToNumeric(integerDolphinProperty); assertEquals(integerJavaFXProperty.get(), 47); integerDolphinProperty.set(100); assertEquals(integerJavaFXProperty.get(), 100); integerDolphinProperty.set(null); assertEquals(integerJavaFXProperty.get(), 0); integerJavaFXProperty.set(12); assertEquals(integerDolphinProperty.get().intValue(), 12); integerJavaFXProperty.setValue(null); assertEquals(integerDolphinProperty.get().intValue(), 0); binding.unbind(); integerDolphinProperty.set(100); assertEquals(integerJavaFXProperty.get(), 0); numberDolphinProperty.set(12); binding = FXBinder.bind(integerJavaFXProperty).bidirectionalTo(numberDolphinProperty); assertEquals(integerJavaFXProperty.get(), 12); numberDolphinProperty.set(null); assertEquals(integerJavaFXProperty.get(), 0); integerJavaFXProperty.set(12); assertEquals(numberDolphinProperty.get().intValue(), 12); integerJavaFXProperty.setValue(null); assertEquals(numberDolphinProperty.get().intValue(), 0); binding.unbind(); numberDolphinProperty.set(100); assertEquals(integerJavaFXProperty.get(), 0); } @Test public void testUnidirectionalChain() { Property<String> stringDolphinProperty1 = new MockedProperty<>(); StringProperty stringJavaFXProperty1 = new SimpleStringProperty(); Property<String> stringDolphinProperty2 = new MockedProperty<>(); StringProperty stringJavaFXProperty2 = new SimpleStringProperty(); Binding binding1 = FXBinder.bind(stringDolphinProperty1).to(stringJavaFXProperty1); Binding binding2 = FXBinder.bind(stringJavaFXProperty2).to(stringDolphinProperty1); Binding binding3 = FXBinder.bind(stringDolphinProperty2).to(stringJavaFXProperty2); stringJavaFXProperty1.setValue("Hello"); assertEquals(stringDolphinProperty1.get(), "Hello"); assertEquals(stringDolphinProperty2.get(), "Hello"); assertEquals(stringJavaFXProperty1.get(), "Hello"); assertEquals(stringJavaFXProperty2.get(), "Hello"); binding2.unbind(); stringJavaFXProperty1.setValue("Hello World"); assertEquals(stringDolphinProperty1.get(), "Hello World"); assertEquals(stringDolphinProperty2.get(), "Hello"); assertEquals(stringJavaFXProperty1.get(), "Hello World"); assertEquals(stringJavaFXProperty2.get(), "Hello"); binding1.unbind(); binding3.unbind(); } @Test public void testBidirectionalChain() { Property<String> stringDolphinProperty1 = new MockedProperty<>(); StringProperty stringJavaFXProperty1 = new SimpleStringProperty(); Property<String> stringDolphinProperty2 = new MockedProperty<>(); StringProperty stringJavaFXProperty2 = new SimpleStringProperty(); Binding binding1 = FXBinder.bind(stringDolphinProperty1).bidirectionalTo(stringJavaFXProperty1); Binding binding2 = FXBinder.bind(stringJavaFXProperty2).bidirectionalTo(stringDolphinProperty1); Binding binding3 = FXBinder.bind(stringDolphinProperty2).bidirectionalTo(stringJavaFXProperty2); stringJavaFXProperty1.setValue("Hello"); assertEquals(stringDolphinProperty1.get(), "Hello"); assertEquals(stringDolphinProperty2.get(), "Hello"); assertEquals(stringJavaFXProperty1.get(), "Hello"); assertEquals(stringJavaFXProperty2.get(), "Hello"); stringDolphinProperty1.set("Hello World"); assertEquals(stringDolphinProperty1.get(), "Hello World"); assertEquals(stringDolphinProperty2.get(), "Hello World"); assertEquals(stringJavaFXProperty1.get(), "Hello World"); assertEquals(stringJavaFXProperty2.get(), "Hello World"); stringJavaFXProperty2.setValue("Hello"); assertEquals(stringDolphinProperty1.get(), "Hello"); assertEquals(stringDolphinProperty2.get(), "Hello"); assertEquals(stringJavaFXProperty1.get(), "Hello"); assertEquals(stringJavaFXProperty2.get(), "Hello"); stringDolphinProperty2.set("Hello World"); assertEquals(stringDolphinProperty1.get(), "Hello World"); assertEquals(stringDolphinProperty2.get(), "Hello World"); assertEquals(stringJavaFXProperty1.get(), "Hello World"); assertEquals(stringJavaFXProperty2.get(), "Hello World"); binding2.unbind(); stringJavaFXProperty1.setValue("Hello"); assertEquals(stringDolphinProperty1.get(), "Hello"); assertEquals(stringDolphinProperty2.get(), "Hello World"); assertEquals(stringJavaFXProperty1.get(), "Hello"); assertEquals(stringJavaFXProperty2.get(), "Hello World"); binding1.unbind(); binding3.unbind(); } @Test public void testListBinding() { ObservableList<String> dolphinList = new ObservableArrayList<>(); javafx.collections.ObservableList<String> javaFXList = FXCollections.observableArrayList(); Binding binding = FXBinder.bind(javaFXList).to(dolphinList); assertEquals(dolphinList.size(), 0); assertEquals(javaFXList.size(), 0); dolphinList.add("Hello"); assertEquals(dolphinList.size(), 1); assertEquals(javaFXList.size(), 1); assertTrue(dolphinList.contains("Hello")); assertTrue(javaFXList.contains("Hello")); dolphinList.add("World"); dolphinList.add("Dolphin"); assertEquals(dolphinList.size(), 3); assertEquals(javaFXList.size(), 3); assertEquals(dolphinList.indexOf("Hello"), 0); assertEquals(dolphinList.indexOf("World"), 1); assertEquals(dolphinList.indexOf("Dolphin"), 2); assertEquals(javaFXList.indexOf("Hello"), 0); assertEquals(javaFXList.indexOf("World"), 1); assertEquals(javaFXList.indexOf("Dolphin"), 2); dolphinList.clear(); assertEquals(dolphinList.size(), 0); assertEquals(javaFXList.size(), 0); dolphinList.add("Java"); assertEquals(dolphinList.size(), 1); assertEquals(javaFXList.size(), 1); assertTrue(dolphinList.contains("Java")); assertTrue(javaFXList.contains("Java")); binding.unbind(); assertEquals(dolphinList.size(), 1); assertEquals(javaFXList.size(), 1); assertTrue(dolphinList.contains("Java")); assertTrue(javaFXList.contains("Java")); dolphinList.add("Duke"); assertEquals(dolphinList.size(), 2); assertEquals(javaFXList.size(), 1); assertTrue(dolphinList.contains("Java")); assertTrue(dolphinList.contains("Duke")); assertTrue(javaFXList.contains("Java")); } @Test public void severalBindings() { ObservableList<String> dolphinList1 = new ObservableArrayList<>(); ObservableList<String> dolphinList2 = new ObservableArrayList<>(); ObservableList<String> dolphinList3 = new ObservableArrayList<>(); ObservableList<String> dolphinList4 = new ObservableArrayList<>(); javafx.collections.ObservableList<String> javaFXList1 = FXCollections.observableArrayList(); javafx.collections.ObservableList<String> javaFXList2 = FXCollections.observableArrayList(); javafx.collections.ObservableList<String> javaFXList3 = FXCollections.observableArrayList(); javafx.collections.ObservableList<String> javaFXList4 = FXCollections.observableArrayList(); Binding binding1 = FXBinder.bind(javaFXList1).to(dolphinList1); Binding binding2 = FXBinder.bind(javaFXList2).to(dolphinList2); Binding binding3 = FXBinder.bind(javaFXList3).to(dolphinList3); Binding binding4 = FXBinder.bind(javaFXList4).to(dolphinList4); binding1.unbind(); binding2.unbind(); binding1 = FXBinder.bind(javaFXList1).to(dolphinList2); binding2 = FXBinder.bind(javaFXList2).to(dolphinList1); binding3.unbind(); binding4.unbind(); binding3 = FXBinder.bind(javaFXList3).to(dolphinList4); binding4 = FXBinder.bind(javaFXList4).to(dolphinList3); binding1.unbind(); binding2.unbind(); binding3.unbind(); binding4.unbind(); binding1 = FXBinder.bind(javaFXList1).to(dolphinList4); binding2 = FXBinder.bind(javaFXList2).to(dolphinList3); binding3 = FXBinder.bind(javaFXList3).to(dolphinList2); binding4 = FXBinder.bind(javaFXList4).to(dolphinList1); binding1.unbind(); binding2.unbind(); binding3.unbind(); binding4.unbind(); } @Test public void testErrorOnMultipleListBinding() { ObservableList<String> dolphinList = new ObservableArrayList<>(); ObservableList<String> dolphinList2 = new ObservableArrayList<>(); javafx.collections.ObservableList<String> javaFXList = FXCollections.observableArrayList(); FXBinder.bind(javaFXList).to(dolphinList); try { FXBinder.bind(javaFXList).to(dolphinList2); fail("A JavaFX list can only be bound to one Dolphin list"); } catch (Exception e){ } } @Test public void testCorrectUnbind() { ObservableList<String> dolphinList = new ObservableArrayList<>(); ObservableList<String> dolphinList2 = new ObservableArrayList<>(); javafx.collections.ObservableList<String> javaFXList = FXCollections.observableArrayList(); Binding binding = FXBinder.bind(javaFXList).to(dolphinList); dolphinList.add("Foo"); assertEquals(dolphinList.size(), 1); assertEquals(dolphinList2.size(), 0); assertEquals(javaFXList.size(), 1); binding.unbind(); FXBinder.bind(javaFXList).to(dolphinList2); assertEquals(dolphinList.size(), 1); assertEquals(dolphinList2.size(), 0); assertEquals(javaFXList.size(), 0); dolphinList2.add("Foo"); dolphinList2.add("Bar"); assertEquals(dolphinList.size(), 1); assertEquals(dolphinList2.size(), 2); assertEquals(javaFXList.size(), 2); } @Test public void testConvertedListBinding() { ObservableList<Boolean> dolphinList = new ObservableArrayList<>(); javafx.collections.ObservableList<String> javaFXList = FXCollections.observableArrayList(); Binding binding = FXBinder.bind(javaFXList).to(dolphinList, value -> value.toString()); dolphinList.add(true); assertEquals(dolphinList.size(), 1); assertEquals(javaFXList.size(), 1); assertEquals(javaFXList.get(0), "true"); } @Test public void testSeveralBinds() { ObservableList<String> dolphinList = new ObservableArrayList<>(); javafx.collections.ObservableList<String> javaFXList = FXCollections.observableArrayList(); for(int i = 0; i < 10; i++) { Binding binding = FXBinder.bind(javaFXList).to(dolphinList); binding.unbind(); } dolphinList.addAll(Arrays.asList("A", "B", "C")); for(int i = 0; i < 10; i++) { Binding binding = FXBinder.bind(javaFXList).to(dolphinList); binding.unbind(); } } @Test public void testListBindingWithNonEmptyLists() { ObservableList<String> dolphinList = new ObservableArrayList<>(); javafx.collections.ObservableList<String> javaFXList = FXCollections.observableArrayList(); dolphinList.addAll(Arrays.asList("A", "B", "C")); Binding binding1 = FXBinder.bind(javaFXList).to(dolphinList); assertEquals(dolphinList.size(), 3); assertEquals(javaFXList.size(), 3); assertTrue(dolphinList.contains("A")); assertTrue(dolphinList.contains("B")); assertTrue(dolphinList.contains("C")); assertTrue(javaFXList.contains("A")); assertTrue(javaFXList.contains("B")); assertTrue(javaFXList.contains("C")); binding1.unbind(); dolphinList.clear(); javaFXList.clear(); javaFXList.addAll("A", "B", "C"); Binding binding2 = FXBinder.bind(javaFXList).to(dolphinList); assertEquals(dolphinList.size(), 0); assertEquals(javaFXList.size(), 0); binding2.unbind(); dolphinList.clear(); javaFXList.clear(); dolphinList.addAll(Arrays.asList("A", "B", "C")); javaFXList.addAll("D", "E", "F"); FXBinder.bind(javaFXList).to(dolphinList); assertEquals(dolphinList.size(), 3); assertEquals(javaFXList.size(), 3); assertTrue(dolphinList.contains("A")); assertTrue(dolphinList.contains("B")); assertTrue(dolphinList.contains("C")); assertTrue(javaFXList.contains("A")); assertTrue(javaFXList.contains("B")); assertTrue(javaFXList.contains("C")); } }
package org.jetbrains.jps.backwardRefs.index; import com.intellij.openapi.util.io.DataInputOutputUtilRt; import com.intellij.util.indexing.DataIndexer; import com.intellij.util.indexing.IndexExtension; import com.intellij.util.indexing.IndexId; import com.intellij.util.io.DataExternalizer; import com.intellij.util.io.DataInputOutputUtil; import com.intellij.util.io.KeyDescriptor; import com.intellij.util.io.VoidDataExternalizer; import org.jetbrains.annotations.NotNull; import org.jetbrains.jps.backwardRefs.CompilerRef; import org.jetbrains.jps.backwardRefs.CompilerRefDescriptor; import org.jetbrains.jps.backwardRefs.SignatureData; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.util.Arrays; import java.util.Collection; import java.util.List; public class JavaCompilerIndices { //TODO manage version separately public static final int VERSION = 7; public static final IndexId<CompilerRef, Integer> BACK_USAGES = IndexId.create("back.refs"); public static final IndexId<CompilerRef, Collection<CompilerRef>> BACK_HIERARCHY = IndexId.create("back.hierarchy"); public static final IndexId<CompilerRef, Void> BACK_CLASS_DEF = IndexId.create("back.class.def"); public static final IndexId<SignatureData, Collection<CompilerRef>> BACK_MEMBER_SIGN = IndexId.create("back.member.sign"); public static final IndexId<CompilerRef, Collection<CompilerRef>> BACK_CAST = IndexId.create("back.cast"); public static final IndexId<CompilerRef, Void> IMPLICIT_TO_STRING = IndexId.create("implicit.to.string"); public static List<IndexExtension<?, ?, CompiledFileData>> getIndices() { return Arrays.asList(createBackwardClassDefinitionExtension(), createBackwardUsagesExtension(), createBackwardHierarchyExtension(), createBackwardSignatureExtension(), createBackwardCastExtension(), createImplicitToStringExtension()); } private static IndexExtension<CompilerRef, Void, CompiledFileData> createImplicitToStringExtension() { return new IndexExtension<CompilerRef, Void, CompiledFileData>() { @NotNull @Override public IndexId<CompilerRef, Void> getName() { return IMPLICIT_TO_STRING; } @NotNull @Override public DataIndexer<CompilerRef, Void, CompiledFileData> getIndexer() { return CompiledFileData::getImplicitToString; } @NotNull @Override public KeyDescriptor<CompilerRef> getKeyDescriptor() { return CompilerRefDescriptor.INSTANCE; } @NotNull @Override public DataExternalizer<Void> getValueExternalizer() { return VoidDataExternalizer.INSTANCE; } @Override public int getVersion() { return VERSION; } }; } private static IndexExtension<CompilerRef, Collection<CompilerRef>, CompiledFileData> createBackwardCastExtension() { return new IndexExtension<CompilerRef, Collection<CompilerRef>, CompiledFileData>() { @NotNull @Override public IndexId<CompilerRef, Collection<CompilerRef>> getName() { return BACK_CAST; } @NotNull @Override public DataIndexer<CompilerRef, Collection<CompilerRef>, CompiledFileData> getIndexer() { return CompiledFileData::getCasts; } @NotNull @Override public KeyDescriptor<CompilerRef> getKeyDescriptor() { return CompilerRefDescriptor.INSTANCE; } @NotNull @Override public DataExternalizer<Collection<CompilerRef>> getValueExternalizer() { return createCompilerRefSeqExternalizer(); } @Override public int getVersion() { return VERSION; } }; } private static IndexExtension<CompilerRef, Integer, CompiledFileData> createBackwardUsagesExtension() { return new IndexExtension<CompilerRef, Integer, CompiledFileData>() { @Override public int getVersion() { return VERSION; } @Override @NotNull public IndexId<CompilerRef, Integer> getName() { return BACK_USAGES; } @Override @NotNull public DataIndexer<CompilerRef, Integer, CompiledFileData> getIndexer() { return CompiledFileData::getReferences; } @Override @NotNull public KeyDescriptor<CompilerRef> getKeyDescriptor() { return CompilerRefDescriptor.INSTANCE; } @Override @NotNull public DataExternalizer<Integer> getValueExternalizer() { return new UnsignedByteExternalizer(); } }; } private static class UnsignedByteExternalizer implements DataExternalizer<Integer> { @Override public void save(@NotNull DataOutput out, Integer value) throws IOException { int v = value; if (v > 255) { v = 255; } out.writeByte(v); } @Override public Integer read(@NotNull DataInput in) throws IOException { return in.readByte() & 0xFF; } } private static IndexExtension<CompilerRef, Collection<CompilerRef>, CompiledFileData> createBackwardHierarchyExtension() { return new IndexExtension<CompilerRef, Collection<CompilerRef>, CompiledFileData>() { @Override public int getVersion() { return VERSION; } @Override @NotNull public IndexId<CompilerRef, Collection<CompilerRef>> getName() { return BACK_HIERARCHY; } @Override @NotNull public DataIndexer<CompilerRef, Collection<CompilerRef>, CompiledFileData> getIndexer() { return CompiledFileData::getBackwardHierarchy; } @Override @NotNull public KeyDescriptor<CompilerRef> getKeyDescriptor() { return CompilerRefDescriptor.INSTANCE; } @Override @NotNull public DataExternalizer<Collection<CompilerRef>> getValueExternalizer() { return createCompilerRefSeqExternalizer(); } }; } private static IndexExtension<CompilerRef, Void, CompiledFileData> createBackwardClassDefinitionExtension() { return new IndexExtension<CompilerRef, Void, CompiledFileData>() { @Override public int getVersion() { return VERSION; } @Override @NotNull public IndexId<CompilerRef, Void> getName() { return BACK_CLASS_DEF; } @Override @NotNull public DataIndexer<CompilerRef, Void, CompiledFileData> getIndexer() { return CompiledFileData::getDefinitions; } @Override @NotNull public KeyDescriptor<CompilerRef> getKeyDescriptor() { return CompilerRefDescriptor.INSTANCE; } @Override @NotNull public DataExternalizer<Void> getValueExternalizer() { return VoidDataExternalizer.INSTANCE; } }; } private static IndexExtension<SignatureData, Collection<CompilerRef>, CompiledFileData> createBackwardSignatureExtension() { return new IndexExtension<SignatureData, Collection<CompilerRef>, CompiledFileData>() { @NotNull @Override public IndexId<SignatureData, Collection<CompilerRef>> getName() { return BACK_MEMBER_SIGN; } @NotNull @Override public DataIndexer<SignatureData, Collection<CompilerRef>, CompiledFileData> getIndexer() { return CompiledFileData::getSignatureData; } @NotNull @Override public KeyDescriptor<SignatureData> getKeyDescriptor() { return createSignatureDataDescriptor(); } @NotNull @Override public DataExternalizer<Collection<CompilerRef>> getValueExternalizer() { return createCompilerRefSeqExternalizer(); } @Override public int getVersion() { return VERSION; } }; } @NotNull private static DataExternalizer<Collection<CompilerRef>> createCompilerRefSeqExternalizer() { return new DataExternalizer<Collection<CompilerRef>>() { @Override public void save(@NotNull final DataOutput out, Collection<CompilerRef> value) throws IOException { DataInputOutputUtilRt.writeSeq(out, value, lightRef -> CompilerRefDescriptor.INSTANCE.save(out, lightRef)); } @Override public Collection<CompilerRef> read(@NotNull final DataInput in) throws IOException { return DataInputOutputUtilRt.readSeq(in, () -> CompilerRefDescriptor.INSTANCE.read(in)); } }; } private static KeyDescriptor<SignatureData> createSignatureDataDescriptor() { return new KeyDescriptor<SignatureData>() { @Override public int getHashCode(SignatureData value) { return value.hashCode(); } @Override public boolean isEqual(SignatureData val1, SignatureData val2) { return val1.equals(val2); } @Override public void save(@NotNull DataOutput out, SignatureData value) throws IOException { DataInputOutputUtil.writeINT(out, value.getRawReturnType()); out.writeByte(value.getIteratorKind()); out.writeBoolean(value.isStatic()); } @Override public SignatureData read(@NotNull DataInput in) throws IOException { return new SignatureData(DataInputOutputUtil.readINT(in), in.readByte(), in.readBoolean()); } }; } }
package hu.webarticum.jsatbuilder.builder.common; import static org.junit.Assert.*; import org.junit.Test; import hu.webarticum.jsatbuilder.builder.core.ConstraintSetSolverFiller; import hu.webarticum.jsatbuilder.builder.core.Variable; import hu.webarticum.jsatbuilder.solver.core.Solver; public class CommonTest { @Test public void test1() throws Exception { ConstraintSetSolverFiller constraints = new ConstraintSetSolverFiller(true); Variable v1_1 = new Variable("1.1"); Variable v1_2 = new Variable("1.2"); Variable v1_3 = new Variable("1.3"); Variable v2_1 = new Variable("2.1"); Variable v2_2 = new Variable("2.2"); constraints.add(new OneConstraint(v1_1, v1_2, v1_3)); constraints.add(new OneConstraint(v2_1, v2_2)); constraints.add(new OneConstraint(v1_1, v2_1)); constraints.add(new OrConstraint(v1_2, v1_3)); constraints.add(new OrConstraint(v1_2, v2_2)); Solver solver = createSolverWith(constraints); if (!solver.run()) { fail("Solution not found!"); } Solver.Model model = solver.getModel(); if (model.get(v1_1)) { fail("Wrong solution (1.1 must be false)"); } if (!model.get(v1_2)) { fail("Wrong solution (1.2 must be true)"); } if (model.get(v1_3)) { fail("Wrong solution (1.3 must be false)"); } if (!model.get(v2_1)) { fail("Wrong solution (2.1 must be true)"); } if (model.get(v2_2)) { fail("Wrong solution (2.2 must be false)"); } } @Test public void test2AIsTrue() throws Exception { doSimpleTest(true); } @Test public void test2AIsFalse() throws Exception { doSimpleTest(false); } private void doSimpleTest(boolean aIsTrue) throws Exception { Variable a = new Variable("a"); Variable b = new Variable("b"); Variable c = new Variable("c"); Variable d = new Variable("d"); ConstraintSetSolverFiller constraints = new ConstraintSetSolverFiller(); constraints.add(new OrConstraint(a, b)); constraints.add(new EqualConstraint( new DefinitionLiteral(c, true), new DefinitionLiteral(d, false)) ); constraints.add(new EqualConstraint(a, c)); constraints.add(new EqualConstraint(b, d)); constraints.add(new GeneralClauseSetConstraint(new DefinitionLiteral[][] { { new DefinitionLiteral(a, aIsTrue) } })); Solver solver = createSolverWith(constraints); if (!solver.run()) { fail("Model was not found"); } Solver.Model model = solver.getModel(); assertEquals(aIsTrue, model.get(a)); assertEquals(!aIsTrue, model.get(b)); assertEquals(aIsTrue, model.get(c)); assertEquals(!aIsTrue, model.get(d)); } private Solver createSolverWith(ConstraintSetSolverFiller constraints) throws Exception { String className = "hu.webarticum.jsatbuilder.solver.sat4j.LightSat4jSolver"; Solver solver = (Solver)Class.forName(className).newInstance(); constraints.fillSolver(solver); return solver; } }
package jsprit.analysis.toolbox; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import jsprit.core.algorithm.VehicleRoutingAlgorithm; import jsprit.core.algorithm.VehicleRoutingAlgorithmFactory; import jsprit.core.problem.VehicleRoutingProblem; import jsprit.core.problem.solution.VehicleRoutingProblemSolution; import jsprit.core.util.BenchmarkInstance; import org.apache.log4j.Level; import org.apache.log4j.Logger; public class ComputationalLaboratory { /** * Listener-interface to listen to calculation. * * <p>Note that calculations are run concurrently, i.e. a unique task that is distributed to an available thread is * {algorithm, instance, run}. * * @author schroeder * */ public static interface CalculationListener { public void calculationStarts(final BenchmarkInstance p, final String algorithmName, final VehicleRoutingAlgorithm algorithm, final int run); public void calculationEnds(final BenchmarkInstance p, final String algorithmName, final VehicleRoutingAlgorithm algorithm, final int run, final Collection<VehicleRoutingProblemSolution> solutions); } /** * Collects whatever indicators you require by algorithmName, instanceName, run and indicator. * * @author schroeder * */ public static class DataCollector { public static class Key { private String instanceName; private String algorithmName; private int run; private String indicatorName; public Key(String instanceName, String algorithmName, int run,String indicatorName) { super(); this.instanceName = instanceName; this.algorithmName = algorithmName; this.run = run; this.indicatorName = indicatorName; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((algorithmName == null) ? 0 : algorithmName .hashCode()); result = prime * result + ((indicatorName == null) ? 0 : indicatorName .hashCode()); result = prime * result + ((instanceName == null) ? 0 : instanceName.hashCode()); result = prime * result + run; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Key other = (Key) obj; if (algorithmName == null) { if (other.algorithmName != null) return false; } else if (!algorithmName.equals(other.algorithmName)) return false; if (indicatorName == null) { if (other.indicatorName != null) return false; } else if (!indicatorName.equals(other.indicatorName)) return false; if (instanceName == null) { if (other.instanceName != null) return false; } else if (!instanceName.equals(other.instanceName)) return false; if (run != other.run) return false; return true; } public String getInstanceName() { return instanceName; } public String getAlgorithmName() { return algorithmName; } public int getRun() { return run; } public String getIndicatorName() { return indicatorName; } @Override public String toString() { return "[algorithm="+algorithmName+"][instance="+instanceName+"][run="+run+"][indicator="+indicatorName+"]"; } } private ConcurrentHashMap<Key, Double> data = new ConcurrentHashMap<ComputationalLaboratory.DataCollector.Key, Double>(); /** * Adds a single date by instanceName, algorithmName, run and indicatorName. * <p>If there is already an entry for this instance, algorithm, run and indicatorName, it is overwritten. * * @param instanceName * @param algorithmName * @param run * @param indicatorName * @param value */ public void addDate(String instanceName, String algorithmName, int run, String indicatorName, double value){ Key key = new Key(instanceName,algorithmName,run,indicatorName); data.put(key, value); } /** * Returns a collections of indicator values representing the calculated values of individual runs. * * @param instanceName * @param algorithmName * @param indicator * @return */ public Collection<Double> getData(String instanceName, String algorithmName, String indicator){ List<Double> values = new ArrayList<Double>(); for(Key key : data.keySet()){ if(key.getAlgorithmName().equals(algorithmName) && key.getInstanceName().equals(instanceName) && key.getIndicatorName().equals(indicator)){ values.add(data.get(key)); } } return values; } /** * Returns indicator value. * * @param instanceName * @param algorithmName * @param run * @param indicator * @return */ public Double getDate(String instanceName, String algorithmName, int run, String indicator){ return data.get(new Key(instanceName,algorithmName,run,indicator)); } /** * Returns all keys that have been created. A key is a unique combination of algorithmName, instanceName, run and indicator. * * @return */ public Set<Key> keySet(){ return data.keySet(); } /** * Returns date associated to specified key. * * @param key * @return */ public Double getData(Key key){ return data.get(key); } } private static class Algorithm { private String name; private VehicleRoutingAlgorithmFactory factory; public Algorithm(String name, VehicleRoutingAlgorithmFactory factory) { super(); this.name = name; this.factory = factory; } } private List<BenchmarkInstance> benchmarkInstances = new ArrayList<BenchmarkInstance>(); private int runs = 1; private Collection<CalculationListener> listeners = new ArrayList<ComputationalLaboratory.CalculationListener>(); private List<Algorithm> algorithms = new ArrayList<ComputationalLaboratory.Algorithm>(); private Set<String> algorithmNames = new HashSet<String>(); private Set<String> instanceNames = new HashSet<String>(); private int threads = Runtime.getRuntime().availableProcessors()+1; public ComputationalLaboratory() { Logger.getRootLogger().setLevel(Level.ERROR); } public void addAlgorithmFactory(String name, VehicleRoutingAlgorithmFactory factory){ if(algorithmNames.contains(name)) throw new IllegalStateException("there is already a algorithmFactory with the same name (algorithmName="+name+"). unique names are required."); algorithms.add(new Algorithm(name,factory)); algorithmNames.add(name); } public void addInstance(String name, VehicleRoutingProblem problem){ if(benchmarkInstances.contains(name)) throw new IllegalStateException("there is already an instance with the same name (instanceName="+name+"). unique names are required."); benchmarkInstances.add(new BenchmarkInstance(name,problem,null,null)); instanceNames.add(name); } public void addInstance(BenchmarkInstance instance){ if(benchmarkInstances.contains(instance.name)) throw new IllegalStateException("there is already an instance with the same name (instanceName="+instance.name+"). unique names are required."); benchmarkInstances.add(instance); instanceNames.add(instance.name); } public void addAllInstances(Collection<BenchmarkInstance> instances){ for(BenchmarkInstance i : instances){ addInstance(i); } } public void addInstance(String name, VehicleRoutingProblem problem, Double bestKnownResult, Double bestKnownVehicles){ addInstance(new BenchmarkInstance(name,problem,bestKnownResult,bestKnownVehicles)); } /** * Adds listener to listen computational experiments. * * @param listener */ public void addListener(CalculationListener listener){ listeners.add(listener); } /** * Sets nuOfRuns with same algorithm on same instance. * <p>Default is 1 * * @param runs */ public void setNuOfRuns(int runs){ this.runs = runs; } public void run(){ if(algorithms.isEmpty()){ throw new IllegalStateException("no algorithm specified. at least one algorithm needs to be specified."); } if(benchmarkInstances.isEmpty()){ throw new IllegalStateException("no instance specified. at least one instance needs to be specified."); } System.out.println("start benchmarking [nuAlgorithms="+algorithms.size()+"][nuInstances=" + benchmarkInstances.size() + "][runsPerInstance=" + runs + "]"); double startTime = System.currentTimeMillis(); ExecutorService executor = Executors.newFixedThreadPool(threads); for(final Algorithm algorithm : algorithms){ for(final BenchmarkInstance p : benchmarkInstances){ for(int run=0;run<runs;run++){ final int r = run; executor.submit(new Runnable(){ @Override public void run() { runAlgorithm(p, algorithm, r+1); } }); } } } try { executor.shutdown(); executor.awaitTermination(Long.MAX_VALUE, TimeUnit.MINUTES); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("benchmarking done [time="+(System.currentTimeMillis()-startTime)/1000 + "sec]"); } /** * Sets number of threads. * <p>By default: <code>nuThreads = Runtime.getRuntime().availableProcessors()+1</code> * * @param threads */ public void setThreads(int threads) { this.threads = threads; } private void runAlgorithm(BenchmarkInstance p, Algorithm algorithm, int run) { System.out.println("[algorithm=" + algorithm.name + "][instance="+p.name+"][run="+run+"][status=start]"); VehicleRoutingAlgorithm vra = algorithm.factory.createAlgorithm(p.vrp); informCalculationStarts(p, algorithm.name, vra, run); Collection<VehicleRoutingProblemSolution> solutions = vra.searchSolutions(); System.out.println("[algorithm=" + algorithm.name + "][instance="+p.name+"][run="+run+"][status=finished]"); informCalculationsEnds(p, algorithm.name, vra, run, solutions); } private void informCalculationStarts(BenchmarkInstance p, String name, VehicleRoutingAlgorithm vra, int run) { for(CalculationListener l : listeners) l.calculationStarts(p, name, vra, run); } private void informCalculationsEnds(BenchmarkInstance p, String name, VehicleRoutingAlgorithm vra, int run, Collection<VehicleRoutingProblemSolution> solutions) { for(CalculationListener l : listeners) l.calculationEnds(p, name, vra, run, solutions); } }
package eu.fbk.knowledgestore.populator.naf; import com.google.common.io.ByteStreams; import eu.fbk.knowledgestore.data.Data; import eu.fbk.knowledgestore.data.Record; import eu.fbk.knowledgestore.populator.naf.model.*; import eu.fbk.knowledgestore.vocabulary.KS; import eu.fbk.knowledgestore.vocabulary.NIF; import eu.fbk.knowledgestore.vocabulary.NWR; import eu.fbk.rdfpro.util.IO; import org.openrdf.model.URI; import org.openrdf.model.impl.URIImpl; import org.openrdf.model.impl.ValueFactoryImpl; import org.openrdf.model.vocabulary.DCTERMS; import org.openrdf.model.vocabulary.RDF; import org.slf4j.Logger; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import java.io.*; import java.net.URL; import java.nio.file.Path; import java.nio.file.Paths; import java.util.*; public class processNAF { public static void main(String[] args) throws JAXBException, IOException { // args[0] is the path, [args[1] is the disabled_Items] String disabled_Items = "", path = ""; if (args.length > 0) { path = args[0]; if (args.length > 1) disabled_Items = args[1]; } else { System.err .println("eu.fbk.knowledgestore.populator.naf.processNAF path disabled_items \ndisabled_items = [Entities|Mentions|Resources] "); System.exit(-1); } processNAFVariables vars = new processNAFVariables(); analyzePathAndRunSystem(path, disabled_Items, vars); } public static KSPresentation init(String fPath, Writer inout, String disabled_Items, boolean store_partical_info) throws JAXBException, IOException { processNAFVariables vars = new processNAFVariables(); vars.storePartialInforInCaseOfError = store_partical_info; vars.out = inout; statistics stat = readFile(fPath, disabled_Items, vars); KSPresentation returned = new KSPresentation(); returned.setNaf_file_path(fPath); returned.setNews(vars.rawText); returned.setMentions(vars.mentionListHash); returned.setNaf(vars.nafFile2); returned.setNewsResource(vars.newsFile2); returned.setStats(stat); return returned; } private static void analyzePathAndRunSystem(String path, String disabled_Items,processNAFVariables vars) throws JAXBException, IOException { vars.filePath = new File(path); if (vars.filePath.exists() && vars.filePath.isDirectory()) { // create report file in the same directory of running the system vars.out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File( vars.filePath.getPath(), "report.txt")), "utf-8")); File[] listOfFiles = vars.filePath.listFiles(); for (int i = 0; i < listOfFiles.length; i++) { if (listOfFiles[i].isFile() && listOfFiles[i].getName().endsWith(".naf")) { System.err.println(i + "=" + listOfFiles[i].getName()); vars.out.append("\n" + i + "=" + listOfFiles[i].getName() + "\n"); readFile(listOfFiles[i].getPath(), disabled_Items,vars); } vars.out.flush(); System.gc(); Runtime.getRuntime().gc(); } } else if (vars.filePath.exists() && vars.filePath.isFile()) { // create report file in the same directory of running the system vars.out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File( vars.filePath.getPath() + ".report.txt")), "utf-8")); vars.out.append(vars.filePath.getPath() + "\n"); readFile(vars.filePath.getPath(), disabled_Items,vars); } vars.out.flush(); vars.out.close(); } public static statistics readFile(String filepath, String disabled_Items, processNAFVariables vars) throws JAXBException, IOException { vars.storePartialInforInCaseOfError = true; vars.filePath = new File(filepath); logDebug("Start working with (" + vars.filePath.getName() + ")",vars); String disabledItems = "";// Default empty so generate all layers of data if (disabled_Items != null && (disabled_Items.matches("(?i)Entity") || disabled_Items.contains("(?i)Mention") || disabled_Items.contains("(?i)Resource"))) { disabledItems = disabled_Items; logDebug("Disable layer: " + disabledItems,vars); } readNAFFile(vars.filePath,vars); getNAFHEADERMentions(vars.doc.getNafHeader(),vars); vars.rawText = vars.doc.getRaw().getvalue(); vars.globalText = vars.doc.getText(); vars.globalTerms = vars.doc.getTerms(); getEntitiesMentions(vars.doc.getEntities(), disabledItems,vars); getCoreferencesMentions(vars.doc.getCoreferences(),vars); getTimeExpressionsMentions(vars.doc.getTimeExpressions(),vars); // getFactualityMentions(vars.doc.getFactualitylayer(),vars); getFactualityMentionsV3(vars.doc.getFactualities(),vars); getSRLMentions(vars); getCLinksMentions(vars.doc.getCausalRelations(),vars); getTLinksMentions(vars.doc.getTemporalRelations(),vars); // logDebug("ROL1 before dumpStack()") ; Thread.currentThread().dumpStack(); fixMentions(vars); logDebug("End of NAF populating.",vars); statistics st = new statistics(); st.setObjectMention((vars.corefMention2+vars.entityMen2)); st.setPER(vars.PER); st.setORG(vars.ORG); st.setLOC(vars.LOC); st.setFin(vars.fin); st.setMix(vars.mix); st.setPRO(vars.PRO); st.setNo_mapping(vars.no_mapping); st.setTimeMention(vars.timeMention2); st.setEventMention((vars.factualityMentions2 + vars.srlMention2)); st.setParticipationMention(vars.rolewithEntity2); st.setEntity(vars.entityMen); st.setCoref(vars.corefMention); st.setCorefMentionEvent(vars.corefMentionEvent); st.setCorefMentionNotEvent(vars.corefMentionNotEvent); st.setFactuality(vars.factualityMentions); st.setRole(vars.roleMentions); st.setRolewithEntity(vars.rolewithEntity); st.setRolewithoutEntity(vars.rolewithoutEntity); st.setSrl(vars.srlMention); st.setTimex(vars.timeMention); st.setClinkMention(vars.clinkMentions); st.setClinkMentionDiscarded(vars.clinkMentionsDiscarded); st.setTlinkMention(vars.tlinkMentions); st.setTlinkMentionsEnriched(vars.tlinkMentionsEnriched); st.setTlinkMentionDiscarded(vars.tlinkMentionsDiscarded); logDebug(st.getStats(),vars); return st; } private static void getEntitiesMentions(Entities obj, String disabledItems,processNAFVariables vars) { if (!checkHeaderTextTerms(vars)) { logError("Error: populating stopped",vars); } else { logDebug("Start mapping the Entities mentions:",vars); } for (Entity entObj : ((Entities) obj).getEntity()) { String deg = ""; int referencesElements = 0; String charS = null; /* process <references> or <externalReferences> */ for (Object generalEntObj : entObj.getReferencesOrExternalReferences()) { if (generalEntObj instanceof References) { /* process <references> */ referencesElements++; if (((References) generalEntObj).getSpan().size() < 1) { logDebug("Every entity must contain a 'span' element inside 'references'", vars); } if (((References) generalEntObj).getSpan().size() > 1) { logDebug("xpath(///NAF/entities/entity/references/span/), spanSize(" + ((References) generalEntObj).getSpan().size() + ") Every entity must contain a unique 'span' element inside 'references'",vars); } for (Span spansObj : ((References) generalEntObj).getSpan()) { boolean addMentionFlag = true; if (spansObj.getTarget().size() < 1) { addMentionFlag = false; logDebug("Every span in an entity must contain at least one target inside", vars); continue; } Record m = Record.create(); deg += "RDF.TYPE:OBJECT_MENTION,ENTITY_MENTION,MENTION"; m.add(RDF.TYPE, NWR.OBJECT_MENTION, NWR.ENTITY_MENTION, KS.MENTION); deg = "MENTION_OF:" + vars.news_file_id.stringValue() + "|" + deg; m.add(KS.MENTION_OF, vars.news_file_id); if (((References) generalEntObj).getSpan().size() > 1) { m.add(NWR.LOCAL_COREF_ID, entObj.getId()); deg += "|LOCAL_COREF_ID:" + entObj.getId(); } generateTheMIdAndSetID(spansObj, m,vars); charS = m.getUnique(NIF.BEGIN_INDEX, Integer.class) + "," + m.getUnique(NIF.END_INDEX, Integer.class); deg = "MentionId:" + m.getID() + "|" + deg; /* don't use predefined types from guidelines but keep the mention with type provided in the NAF */ boolean keepEntityTypeProvidedByNaf = true,dbpedia=true; String type3charLC = ""; if(!dbpedia){ if(entObj.getType()!=null&&entObj.getType()!=""&&!entObj.getType().equalsIgnoreCase("misc")){ type3charLC = entObj.getType().substring(0, 3).toLowerCase(); }else{ type3charLC = "misc"; entObj.setType("misc"); } if (keepEntityTypeProvidedByNaf) { URI dynamicTypeUri = ValueFactoryImpl.getInstance().createURI(NWR.NAMESPACE, "entity_type_" + entObj.getType().toLowerCase()); m.add(NWR.ENTITY_TYPE, dynamicTypeUri); deg += "|ENTITY_TYPE:" + dynamicTypeUri; logDebug("ROL1: <entity> added new mention for id " + entObj.getId() + ", charSpan |" + getCharSpanFromSpan(spansObj,vars) + "|, type " + dynamicTypeUri,vars); } else { if (vars.entityTypeMapper.containsKey(type3charLC) && vars.entityTypeMapper.get(type3charLC) != null) { m.add(NWR.ENTITY_TYPE, vars.entityTypeMapper.get(type3charLC)); deg += "|ENTITY_TYPE:" + vars.entityTypeMapper.get(type3charLC); logDebug("ROL1: <entity> STRANGE added new mention for id " + entObj.getId() + ", charSpan |" + getCharSpanFromSpan(spansObj,vars) + "|, type " + vars.entityTypeMapper.get(type3charLC),vars); } else { addMentionFlag = false; logDebug("xpath(//NAF/entities/entity/@type),type(" + entObj.getType() + "), id(" + entObj.getId() + ") NO mapping for it", vars); vars.no_mapping++; } } }//dbpedia finish else{ if(entObj.getType()==null||entObj.getType().equals("")){ type3charLC = "misc"; entObj.setType("misc"); }else{ if(entObj.getType().toLowerCase().contains("per")||entObj.getType().toLowerCase().contains("dbpedia:person")){ entObj.setType("person"); type3charLC = entObj.getType().substring(0, 3).toLowerCase(); }else if(entObj.getType().toLowerCase().contains("org")||entObj.getType().toLowerCase().contains("dbpedia:organisation")){ entObj.setType("organization"); type3charLC = entObj.getType().substring(0, 3).toLowerCase(); } else if(entObj.getType().toLowerCase().contains("loc")||entObj.getType().toLowerCase().contains("DBpedia:Place")){ entObj.setType("location"); type3charLC = entObj.getType().substring(0, 3).toLowerCase(); }else { entObj.setType("misc"); type3charLC = "misc"; } } URI dynamicTypeUri = ValueFactoryImpl.getInstance().createURI(NWR.NAMESPACE, "entity_type_" + entObj.getType().toLowerCase()); m.add(NWR.ENTITY_TYPE, dynamicTypeUri); deg += "|ENTITY_TYPE:" + dynamicTypeUri; logDebug("ROL1: <entity> added new mention for id " + entObj.getId() + ", charSpan |" + getCharSpanFromSpan(spansObj,vars) + "|, type " + dynamicTypeUri,vars); } if (addMentionFlag) { if (addOrMergeAMention(m,vars)==1) { String charS2 = m.getUnique(NIF.BEGIN_INDEX, Integer.class) + "," + m.getUnique(NIF.END_INDEX, Integer.class); vars.entityMentions.put(charS2, m); if (type3charLC.equalsIgnoreCase("PER")) vars.PER++; if (type3charLC.equalsIgnoreCase("LOC")) vars.LOC++; if (type3charLC.equalsIgnoreCase("ORG")) vars.ORG++; if (type3charLC.equalsIgnoreCase("PRO")) vars.PRO++; if (type3charLC.equalsIgnoreCase("fin")) vars.fin++; if (type3charLC.equalsIgnoreCase("mix")||type3charLC.equalsIgnoreCase("misc")) vars.mix++; vars.entityMen2++; vars.entityMen++; } } } } else if (generalEntObj instanceof ExternalReferences) { /* process <externalReferences> */ // do it only if management of (KS) "Entity" layer is not disabled if (! disabledItems.matches("(?i)Entity")) { boolean firstTimeFlag = true; String chosenReferenceValue = null; //modeactive is two filters should be applied to the externalRefs. //1. Language For each entity, group externalRef(s) by language (using reftype) and use the first nonempty set, using this sorting: en, es, it, nl. //2. Confidence Once the language is chosen, just take the externalRef having the higher confidence (and, of course, the language chosen). boolean modeactive=true; // if POCUS "reranker value" get it as externalreference otherwise do the language/highconfidence check for (ExternalRef exRObj : ((ExternalReferences) generalEntObj) .getExternalRef()) { if(exRObj.getSource().equalsIgnoreCase("POCUS")){ if (referencesElements < 1) { logDebug("Every entity must contain a 'references' element:not possible to add ExternalRef to null.", vars); continue; } // String resourceValue = exRObj.getResource(); String referenceValue = exRObj.getReference(); chosenReferenceValue = new String(referenceValue); modeactive=false; } } if(modeactive){ LinkedList<ExternalRef> exrEn = new LinkedList<ExternalRef>(); LinkedList<ExternalRef> exrEs = new LinkedList<ExternalRef>(); LinkedList<ExternalRef> exrIt = new LinkedList<ExternalRef>(); LinkedList<ExternalRef> exrNl = new LinkedList<ExternalRef>(); ExternalReferences obs = ((ExternalReferences) generalEntObj) ; for (ExternalRef exRObj : obs.getExternalRef()) { if(exRObj!=null) getAllLayersOfExternalReferences( modeactive, exrEn, exRObj, exrEs, exrIt, exrNl,vars); } if(exrEn.size()>0) chosenReferenceValue = new String(getHighConfidenceReferenceValue(exrEn)); else if(exrEs.size()>0) chosenReferenceValue = new String(getHighConfidenceReferenceValue(exrEs)); else if(exrIt.size()>0) chosenReferenceValue = new String(getHighConfidenceReferenceValue(exrIt)); else chosenReferenceValue = new String(getHighConfidenceReferenceValue(exrNl)); }else if(false){ //don't use it for now, it gets the last externalRef as the chosen one for (ExternalRef exRObj : ((ExternalReferences) generalEntObj) .getExternalRef()) { if (referencesElements < 1) { logDebug("Every entity must contain a 'references' element:not possible to add ExternalRef to null.", vars); continue; } String resourceValue = exRObj.getResource(); String referenceValue = exRObj.getReference(); // choose as referenceValue the one provided by 'vua-type-reranker' if present, otherwise take the first value if (firstTimeFlag) { chosenReferenceValue = new String(referenceValue); firstTimeFlag = false; } else if (resourceValue.matches("(?i).*type-reranker.*")) { chosenReferenceValue = new String(referenceValue); } } } URIImpl chosenReferenceURI = new URIImpl(chosenReferenceValue); if (charS != null&&vars.mentionListHash.get(charS)!=null&&vars.mentionListHash.get(charS).get(KS.REFERS_TO).size()==0){ vars.mentionListHash.get(charS).add(KS.REFERS_TO, chosenReferenceURI); //TODO mohammed if there already decided an externalRef don't add new one. deg += "|REFERS_TO:" + chosenReferenceValue; vars.entityMentions.get(charS).add(KS.REFERS_TO, chosenReferenceURI); }else{ if (charS != null&&vars.mentionListHash.get(charS)!=null) deg += "|REFERS_TO:" + vars.mentionListHash.get(charS).get(KS.REFERS_TO); } } } // end of if (generalEntObj instanceof ExternalReferences) { } // end of for (Object generalEntObj : entObj.getReferencesOrExternalReferences()) logDebug(deg,vars); if (referencesElements < 1) { logDebug("Every entity must contain a 'references' element", vars); } } } private static void getAllLayersOfExternalReferences(boolean modeactive, LinkedList<ExternalRef> exrEn, ExternalRef exRObj, LinkedList<ExternalRef> exrEs, LinkedList<ExternalRef> exrIt, LinkedList<ExternalRef> exrNl,processNAFVariables vars) { if(modeactive){ if(exRObj.getReftype()!=null){ switch(exRObj.getReftype()){ case "en": exrEn.addLast(exRObj); break; case "es": exrEs.addLast(exRObj); break; case "it": exrIt.addLast(exRObj); break; case "nl": exrNl.addLast(exRObj); break; } }else if(exRObj.getReference().contains("dbpedia")){ if(exRObj.getReference().contains("://dbpedia.org")){ exrEn.addLast(exRObj); }else if(exRObj.getReference().contains("://es.dbpedia.org")){ exrEs.addLast(exRObj); }else if(exRObj.getReference().contains("://it.dbpedia.org")){ exrIt.addLast(exRObj); }else { exrNl.addLast(exRObj); } }else{ logDebug("Every entity must contain a 'references' element with type or DBpedia reference: not possible to add ExternalRef to null.", vars); } } if(exRObj!=null&&exRObj.getExternalRef()!=null && exRObj.getExternalRef().size()>0){ for(ExternalRef ff :exRObj.getExternalRef()){ getAllLayersOfExternalReferences( modeactive, exrEn, ff, exrEs, exrIt, exrNl,vars); } }else return; } private static String getHighConfidenceReferenceValue( LinkedList<ExternalRef> exrl) { ExternalRef current=null; Double dt=0.0; for(ExternalRef tmp:exrl){ Double co=Double.parseDouble(tmp.getConfidence()); if(current==null){ current = tmp; dt=co; }else{ if(co>dt){ current = tmp; dt=co; } } } return current.getReference(); } private static void getTimeExpressionsMentions(TimeExpressions obj,processNAFVariables vars) { if (!checkHeaderTextTerms(vars)) { logError("Error: populating interrupted",vars); } else { logDebug("Start mapping the TimeExpressions mentions:",vars); } for (Timex3 tmxObj : ((TimeExpressions) obj).getTimex3()) { Span tmxSpan = tmxObj.getSpan(); String tmxTypeUC = tmxObj.getType().toUpperCase(); boolean keepTimeTypeProvidedByNaf = true; // patch for timex3 without <span> if ((tmxSpan == null) || (tmxSpan.getTarget().size() < 1)) { logDebug("skipping timex3 without span, id is " + tmxObj.getId(), vars); continue; } String deg = ""; Record m = Record.create(); m.add(RDF.TYPE, NWR.TIME_MENTION, NWR.TIME_OR_EVENT_MENTION, NWR.ENTITY_MENTION, KS.MENTION); deg += "|TYPE:TIME_MENTION,TIME_OR_EVENT_MENTION,ENTITY_MENTION,MENTION"; m.add(KS.MENTION_OF, vars.news_file_id); LinkedList<Wf> wordsL = fromSpanGetAllMentionsTmx(((Span) tmxSpan).getTarget(), vars); generateMIDAndSetIdWF(wordsL, m,vars); deg = "MentionId:" + m.getID() + deg; if (keepTimeTypeProvidedByNaf) { URI dynamicTypeUri = ValueFactoryImpl.getInstance().createURI(NWR.NAMESPACE, "timex3_" + tmxTypeUC.toLowerCase()); m.add(NWR.TIME_TYPE, dynamicTypeUri); deg += "|TIME_TYPE:" + dynamicTypeUri; logDebug("ROL1: <timex3> added new mention for id " + tmxObj.getId() + ", type " + dynamicTypeUri,vars); } else { if (vars.timex3TypeMapper.containsKey(tmxTypeUC) && vars.timex3TypeMapper.get(tmxTypeUC) != null) { m.add(NWR.TIME_TYPE, vars.timex3TypeMapper.get(tmxTypeUC)); deg += "|TIME_TYPE:" + vars.timex3TypeMapper.get(tmxTypeUC); logDebug("ROL1: <timex3> STRANGE added new mention for id " + tmxObj.getId() + ", type " + vars.timex3TypeMapper.get(tmxTypeUC),vars); } else { logDebug("xpath(//NAF/timeExpressions/timex3/@type), type(" + tmxTypeUC + "), No mapping.", vars); } } if (false&&tmxObj.getBeginPoint() != null) { //TODO m.add(NWR.BEGIN_POINT, tmxObj.getBeginPoint()); deg += "|BEGIN_POINT:" + tmxObj.getBeginPoint(); } if (false&&tmxObj.getEndPoint() != null) { m.add(NWR.END_POINT, tmxObj.getEndPoint()); deg += "|END_POINT:" + tmxObj.getEndPoint(); } if (tmxObj.getQuant() != null) { m.add(NWR.QUANT, tmxObj.getQuant()); deg += "|QUANT:" + tmxObj.getQuant(); } if (tmxObj.getFreq() != null) { m.add(NWR.FREQ, tmxObj.getFreq()); deg += "|FREQ:" + tmxObj.getFreq(); } if (tmxObj.getFunctionInDocument() != null) { m.add(NWR.FUNCTION_IN_DOCUMENT, tmxObj.getFunctionInDocument()); deg += "|FUNCTION_IN_DOCUMENT:" + tmxObj.getFunctionInDocument(); } if (tmxObj.getTemporalFunction() != null) { m.add(NWR.TEMPORAL_FUNCTION, tmxObj.getTemporalFunction()); deg += "|TEMPORAL_FUNCTION:" + tmxObj.getTemporalFunction(); } if (tmxObj.getValue() != null) { m.add(NWR.VALUE, tmxObj.getValue()); deg += "|VALUE:" + tmxObj.getValue(); } if (tmxObj.getValueFromFunction() != null) { m.add(NWR.VALUE_FROM_FUNCTION, tmxObj.getValueFromFunction()); deg += "|VALUE_FROM_FUNCTION:" + tmxObj.getValueFromFunction(); } if (tmxObj.getMod() != null) { m.add(NWR.MOD, tmxObj.getMod()); deg += "|MOD:" + tmxObj.getMod(); } if (tmxObj.getAnchorTimeID() != null) { m.add(NWR.ANCHOR_TIME, tmxObj.getAnchorTimeID()); deg += "|ANCHOR_TIME:" + tmxObj.getAnchorTimeID(); } logDebug(deg,vars); int addedNew = addOrMergeAMention(m,vars); if (addedNew==1){ vars.timeMention2++; vars.timeMention++; } String charS2 = m.getUnique(NIF.BEGIN_INDEX, Integer.class) + "," + m.getUnique(NIF.END_INDEX, Integer.class); vars.entityMentions.put(charS2,m); } } private static void getFactualityMentions(Factualitylayer obj,processNAFVariables vars) { if (!checkHeaderTextTerms(vars)) { logError("Error: populating interrupted",vars); } else { logDebug("Start mapping the Factuality mentions:",vars); } for (Factvalue fvObj : ((Factualitylayer) obj).getFactvalue()) { String deg = ""; Record m = Record.create(); m.add(RDF.TYPE, NWR.EVENT_MENTION, NWR.TIME_OR_EVENT_MENTION, NWR.ENTITY_MENTION, KS.MENTION); deg += "|TYPE:EVENT_MENTION,TIME_OR_EVENT_MENTION,ENTITY_MENTION,MENTION"; m.add(KS.MENTION_OF, vars.news_file_id); LinkedList<Target> tarlist = new LinkedList<Target>(); Target tmp = new Target(); tmp.setId(fvObj.getId()); tarlist.addLast(tmp); LinkedList<Wf> wordsL = fromSpanGetAllMentionsTmx(tarlist,vars); generateMIDAndSetIdWF(wordsL, m,vars); deg = "MentionId:" + m.getID() + deg; // fvObj.getPrediction(); //TODO we need to verify the mapping here // m.add(NWR.CERTAINTY, fvObj.getPrediction()); // m.add(NWR.FACTUALITY, fvObj.getPrediction()); if (fvObj.getConfidence() != null) { m.add(NWR.FACTUALITY_CONFIDENCE, fvObj.getConfidence()); deg += "|FACTUALITY_CONFIDENCE:" + fvObj.getConfidence(); } logDebug(deg,vars); int addedNew = addOrMergeAMention(m,vars); if (addedNew==1){ vars.factualityMentions2++; vars.factualityMentions++; } String charS2 = m.getUnique(NIF.BEGIN_INDEX, Integer.class) + "," + m.getUnique(NIF.END_INDEX, Integer.class); vars.entityMentions.put(charS2,m); } } private static void getFactualityMentionsV3(Factualities factualities,processNAFVariables vars) { if (!checkHeaderTextTerms(vars)) { logError("Error: populating interrupted",vars); } else { logDebug("Start mapping the Factualities mentions:",vars); } for (Factuality fvObj : factualities.getFactuality()) { String deg = ""; Record m = Record.create(); m.add(RDF.TYPE, NWR.EVENT_MENTION, NWR.TIME_OR_EVENT_MENTION, NWR.ENTITY_MENTION, KS.MENTION); deg += "|TYPE:EVENT_MENTION,TIME_OR_EVENT_MENTION,ENTITY_MENTION,MENTION"; m.add(KS.MENTION_OF, vars.news_file_id); LinkedList<Target> tarlist = new LinkedList<Target>(); for(Target t : fvObj.getSpan().getTarget()){ tarlist.addLast(t); } LinkedList<Wf> wordsL = fromSpanGetAllMentions(tarlist,vars); generateMIDAndSetIdWF(wordsL, m,vars); deg = "MentionId:" + m.getID() + deg; for (FactVal tts : fvObj.getFactVal()) { if(tts.getResource().equalsIgnoreCase("factbank")){ m.add(NWR.FACT_BANK, tts.getValue()); } } logDebug(deg,vars); int addedNew = addOrMergeAMention(m,vars); if (addedNew==1|addedNew==0){ vars.factualityMentions2++; vars.factualityMentions++; } String charS2 = m.getUnique(NIF.BEGIN_INDEX, Integer.class) + "," + m.getUnique(NIF.END_INDEX, Integer.class); vars.entityMentions.put(charS2,m); } } private static void getCLinksMentions(CausalRelations causalRelations,processNAFVariables vars) { if (!checkHeaderTextTerms(vars)) { logError("Error: populating interrupted",vars); } else { logDebug("Start mapping the CLINKS mentions:",vars); } for (Clink fvObj : causalRelations.getClink()) { String deg = ""; Record m = Record.create(); m.add(RDF.TYPE, NWR.CLINK,NWR.RELATION_MENTION, KS.MENTION); deg += "|TYPE:CLINK,RELATION_MENTION,MENTION"; m.add(KS.MENTION_OF, vars.news_file_id); LinkedList<Target> tarlist = new LinkedList<Target>(); List<Target> from = getSpanTermsOfPredicate(fvObj.getFrom(),vars); List<Target> to = getSpanTermsOfPredicate(fvObj.getTo(),vars); tarlist.addAll(from); tarlist.addAll(to); LinkedList<Wf> fromwl = fromSpanGetAllMentions(from,vars); Record mtest1 = Record.create(); generateMIDAndSetIdWF(fromwl, mtest1 ,vars); m.add(NWR.SOURCE, mtest1.getID()); LinkedList<Wf> towl = fromSpanGetAllMentions(to,vars); Record mtest2 = Record.create(); generateMIDAndSetIdWF(towl, mtest2 ,vars); m.add(NWR.TARGET, mtest2.getID()); LinkedList<Wf> wordsL = fromSpanGetAllMentions(tarlist,vars); generateMIDAndSetIdWF(wordsL, m,vars); deg = "MentionId:" + m.getID() + deg; logDebug(deg,vars); int addedNew = addOrMergeAMention(m,vars); if (addedNew==1){ vars.clinkMentions++; }else if (addedNew==1){ vars.clinkMentionsDiscarded++; } } } private static void getTLinksMentions(TemporalRelations temporalRelations,processNAFVariables vars) { if (!checkHeaderTextTerms(vars)) { logError("Error: populating interrupted",vars); } else { logDebug("Start mapping the TLINKS mentions:",vars); } if (temporalRelations == null) { return; } if (temporalRelations.getTlink() == null) { return; } for (Tlink fvObj : temporalRelations.getTlink()) { String deg = ""; Record m = Record.create(); m.add(RDF.TYPE, NWR.TLINK,NWR.RELATION_MENTION, KS.MENTION); deg += "|TYPE:TLINK,RELATION_MENTION,MENTION"; m.add(KS.MENTION_OF, vars.news_file_id); LinkedList<Target> tarlist = new LinkedList<Target>(); List<Target> from = new ArrayList<Target>(); List<Target> to = new ArrayList<Target>(); if(fvObj.getFromType().equalsIgnoreCase("event")){ from = getSpanTermsOfPredicate(fvObj.getFrom(),vars); } if(fvObj.getToType().equalsIgnoreCase("event")){ to = getSpanTermsOfPredicate(fvObj.getTo(),vars); } tarlist.addAll(from); tarlist.addAll(to); LinkedList<Wf> allEventWF = fromSpanGetAllMentions(tarlist,vars); LinkedList<Wf> allWFFrom = fromSpanGetAllMentions(from,vars); LinkedList<Wf> allWFTO = fromSpanGetAllMentions(to,vars); List<Wf> fromtmx = new ArrayList<Wf>(); List<Wf> totmx = new ArrayList<Wf>(); //here if the type is timex, get all its WFs if(fvObj.getFromType().equalsIgnoreCase("timex")){ fromtmx=getSpanOfTimex(fvObj.getFrom(),vars); allWFFrom.addAll(fromtmx); allEventWF.addAll(fromtmx); } if(fvObj.getToType().equalsIgnoreCase("timex")){ totmx = getSpanOfTimex(fvObj.getTo(),vars); allWFTO.addAll(totmx); allEventWF.addAll(totmx); } //reorder the lists allEventWF = reorderWFAscending(allEventWF,vars); allWFFrom = reorderWFAscending(allWFFrom,vars); allWFTO = reorderWFAscending(allWFTO,vars); if(fvObj.getFrom().equalsIgnoreCase("tmx0")){ Record mtest2 = Record.create(); generateMIDAndSetIdWF(allWFTO, mtest2 ,vars); int returned=addTlinkRelTypeToMention(NWR.TLINK_FROM_TMX0,vars.tLinkTypeMapper.get(fvObj.getRelType().toUpperCase()),mtest2,vars); if (returned==1) vars.tlinkMentionsEnriched++; else logDebug("Tlink FROM -> tmx0, not found the target mention id:" + fvObj.getTo(), vars); continue; } if(fvObj.getTo().equalsIgnoreCase("tmx0")){ Record mtest1 = Record.create(); generateMIDAndSetIdWF(allWFFrom, mtest1 ,vars); int returned=addTlinkRelTypeToMention(NWR.TLINK_TO_TMX0,vars.tLinkTypeMapper.get(fvObj.getRelType().toUpperCase()),mtest1,vars); if (returned==1) vars.tlinkMentionsEnriched++; else logDebug("Tlink TO -> tmx0, not found the source mention id:" + fvObj.getFrom(), vars); continue; } if(allWFFrom.size()>0){ Record mtest1 = Record.create(); generateMIDAndSetIdWF(allWFFrom, mtest1 ,vars); m.add(NWR.SOURCE, mtest1.getID()); } if(allWFTO.size()>0){ Record mtest2 = Record.create(); generateMIDAndSetIdWF(allWFTO, mtest2 ,vars); m.add(NWR.TARGET, mtest2.getID()); } m.add(NWR.REL_TYPE, vars.tLinkTypeMapper.get(fvObj.getRelType().toUpperCase())); generateMIDAndSetIdWF(allEventWF, m,vars); deg = "MentionId:" + m.getID() + deg; logDebug(deg,vars); int addedNew = addOrMergeAMention(m,vars); if (addedNew==1){ vars.tlinkMentions++; }else if (addedNew==-1){ vars.tlinkMentionsDiscarded++; } } } private static int addTlinkRelTypeToMention(URI key, URI value, Record mention, processNAFVariables vars) { String charS = mention.getUnique(NIF.BEGIN_INDEX, Integer.class) + "," + mention.getUnique(NIF.END_INDEX, Integer.class); if(vars.mentionListHash.containsKey(charS)){ vars.mentionListHash.get(charS).add(key, value); return 1; } return -1; } private static LinkedList<Wf> reorderWFAscending(LinkedList<Wf> list, processNAFVariables vars) { LinkedList<Wf> tmp = new LinkedList<Wf>(); int found = 0; for (Wf wftmp : vars.doc.getText().getWf()) { if (list.contains(wftmp)) { tmp.addLast(wftmp); found++; } if (found >= list.size()) { break; } } if (found < list.size()) { logDebug("reorderWFAscending method, inconsistency: returned list less than the input list", vars); } return tmp; } private static List<Wf> getSpanOfTimex(String tmxId, processNAFVariables vars) { List<Wf> tmp = new ArrayList<Wf>(); for(Timex3 tms:vars.doc.getTimeExpressions().getTimex3()){ if(tms.getId().equalsIgnoreCase(tmxId)){ for(Target t: tms.getSpan().getTarget()){ tmp.add((Wf) t.getId()); } break; } } return tmp; } private static List<Target> getSpanTermsOfPredicate(String predicateId, processNAFVariables vars) { for( Predicate pr:vars.doc.getSrl().getPredicate()){ if(pr.getId().equalsIgnoreCase(predicateId)){ return pr.getSpan().getTarget(); } } return null; } private static URIImpl getUriForSrlExternalRefResource(String type, String value) { String prefix = null; if (type.equalsIgnoreCase("PropBank")) { prefix = "http: } else if (type.equalsIgnoreCase("VerbNet")) { prefix = "http: } else if (type.equalsIgnoreCase("FrameNet")) { prefix = "http: } else if (type.equalsIgnoreCase("NomBank")) { prefix = "http: } else if (type.equalsIgnoreCase("ESO")) { prefix = "http://www.newsreader-project.eu/domain-ontology } if (prefix != null) { return new URIImpl(prefix + value); } else { return null; } } private static void getSRLMentions(processNAFVariables vars) { Srl obj = vars.doc.getSrl(); if (!checkHeaderTextTerms(vars)) { logError("Error: populating interrupted",vars); } else { logDebug("Start mapping the Srl mentions:",vars); } if ((obj == null) || (((Srl) obj).getPredicate() == null)) { logError("skipped missing xpath(//NAF/srl)",vars); return; } /* Iterate over the <predicate>s */ for (Predicate prdObj : ((Srl) obj).getPredicate()) { String deg = ""; Record mtmp = null; String predicateID = prdObj.getId(); boolean firstSpanFound = false; int predicatExtRef = 0; String eventMentionId = null; String predicateCharSpan = null; LinkedList<Term> eventTermList = new LinkedList<Term>(); /* create an EVENT_MENTION for the <predicate> */ if (prdObj.getSpan() instanceof Span) { if (firstSpanFound) { logDebug("Srl should have one span only! ", vars); } if (!firstSpanFound) { firstSpanFound = true; } predicateCharSpan = getCharSpanFromSpan(prdObj.getSpan(),vars); mtmp = Record.create(); mtmp.add(RDF.TYPE, NWR.EVENT_MENTION, NWR.TIME_OR_EVENT_MENTION, NWR.ENTITY_MENTION, KS.MENTION); deg = "|TYPE:EVENT_MENTION,TIME_OR_EVENT_MENTION,ENTITY_MENTION,MENTION"; mtmp.add(KS.MENTION_OF, vars.news_file_id); for (Target tars : prdObj.getSpan().getTarget()) { tars.getId(); Term eventTerm = getTermfromTermId((Term) tars.getId(),vars); eventTermList.addLast(eventTerm); if (eventTerm.getLemma() != null) { mtmp.add(NWR.PRED, eventTerm.getLemma()); deg += "|PRED:" + eventTerm.getLemma(); } if (eventTerm.getPos() != null) { URI posVal = (eventTerm.getPos().equals("V") || eventTerm.getPos().equals("N")) ? vars.partOfSpeechMapper.get(eventTerm.getPos()) : vars.partOfSpeechMapper.get(""); mtmp.add(NWR.POS, posVal); deg += "|POS:" + posVal; } } generateTheMIdAndSetID(prdObj.getSpan(), mtmp,vars); deg = "MentionId:" + mtmp.getID() + deg; } /* * Assign the predicateAnchor attributes to the predicate Mention */ List<PredicateAnchor> prds= getAllRelativePredicateAnchors(prdObj.getId(),vars); for(PredicateAnchor tprd: prds){ if(tprd.getAnchorTime()!=null){ LinkedList<Wf> wfL = reorderWFAscending(fromSpanGetAllMentionsTmx(((Timex3)tprd.getAnchorTime()).getSpan().getTarget(), vars),vars); if(wfL.size()>0){ Record mtest1 = Record.create(); generateMIDAndSetIdWF(wfL, mtest1 ,vars); mtmp.add(NWR.ANCHOR_TIME, mtest1.getID()); } } if(tprd.getBeginPoint()!=null){ LinkedList<Wf> wfL = reorderWFAscending(fromSpanGetAllMentionsTmx(((Timex3)tprd.getBeginPoint()).getSpan().getTarget(), vars),vars); if(wfL.size()>0){ Record mtest1 = Record.create(); generateMIDAndSetIdWF(wfL, mtest1 ,vars); mtmp.add(NWR.BEGIN_POINT, mtest1.getID()); } } if(tprd.getEndPoint()!=null){ LinkedList<Wf> wfL = reorderWFAscending(fromSpanGetAllMentionsTmx(((Timex3)tprd.getEndPoint()).getSpan().getTarget(), vars),vars); if(wfL.size()>0){ Record mtest1 = Record.create(); generateMIDAndSetIdWF(wfL, mtest1 ,vars); mtmp.add(NWR.END_POINT, mtest1.getID()); } } } deg +="| ANCHOR_TIME:"+mtmp.get(NWR.ANCHOR_TIME)+" | BEGIN_POINT:"+mtmp.get(NWR.BEGIN_POINT)+" | END_POINT:"+mtmp.get(NWR.END_POINT); /* iterate over the sub-tags <externalReferences> or <role>s of the <predicate> */ for (Object prdGObj : prdObj.getExternalReferencesOrRole()) { /* process the <externalReferences> sub-tag: enrich the EVENT_MENTION related to <predicate> */ if (prdGObj instanceof ExternalReferences) { boolean eventTypeFound = false; if (predicatExtRef > 1) { logDebug("more than one external ref for predicate:" + predicateID + " size: " + predicatExtRef, vars); } predicatExtRef++; for (ExternalRef exrObj : ((ExternalReferences) prdGObj).getExternalRef()) { if (mtmp != null) { // check 'resource' and 'reference' attributes String resourceValue = exrObj.getResource(); String referenceValue = exrObj.getReference(); if (resourceValue != null) { // check cases different from resource="EventType" if (!resourceValue.equalsIgnoreCase("EventType")) { URI resourceMappedValue = vars.srlExternalRefResourceTypeMapper.get(resourceValue); URIImpl valueURI; if (resourceMappedValue != null) { valueURI = getUriForSrlExternalRefResource(resourceValue, referenceValue); } else { // force dynamic URIs resourceMappedValue = ValueFactoryImpl.getInstance() .createURI(NWR.NAMESPACE, resourceValue.toLowerCase() + "Ref"); valueURI = new URIImpl("http: + resourceValue.toLowerCase() + "/" + referenceValue); } mtmp.add(resourceMappedValue, valueURI); deg += "|" + resourceMappedValue + ":" + valueURI; } else { // resource="EventType" => check 'reference' attribute URI referenceMappedValue = null; if (referenceValue != null) { referenceMappedValue = vars.eventClassMapper.get(referenceValue); } if (referenceMappedValue == null) { // force this default value referenceMappedValue = NWR.EVENT_SPEECH_COGNITIVE; } mtmp.add(NWR.EVENT_CLASS, referenceMappedValue); deg += "|EVENT_CLASS:" + referenceMappedValue; eventTypeFound = true; } } else { // resourceValue == null) logDebug("xpath(//NAF/srl/predicate/externalReferences/externalRef@Resource(NULL)): predicateID(" + predicateID + ")", vars); } } else { logDebug("Mapping error - Mention null - xpath(NAF/srl/predicate/externalReferences/externalRef): predicateID(" + predicateID + ")", vars); } } if (!eventTypeFound) { mtmp.add(NWR.EVENT_CLASS, vars.eventClassMapper.get("contextual")); deg += "|EVENT_CLASS:" + vars.eventClassMapper.get("contextual"); eventTypeFound = true; } if (eventTypeFound) { logDebug(deg,vars); int addedNew = addOrMergeAMention(mtmp,vars); logDebug("ROL1: <srl> <predicate> adding new event mention for id " + predicateID + ", charSpan |" + predicateCharSpan + "|",vars); if (addedNew==1|addedNew==0){ vars.srlMention2++; vars.srlMention++; } String charS2 = mtmp.getUnique(NIF.BEGIN_INDEX, Integer.class) + "," + mtmp.getUnique(NIF.END_INDEX, Integer.class); vars.entityMentions.put(charS2,mtmp); eventMentionId = mtmp.getID().stringValue(); } else { // if eventType not found or no mapping for it // write error and discard this mention logDebug("Mention discarded for predicateID(" + predicateID + ") - ID(" + mtmp.getID().toString() + ")", vars); } } else /* process the <role> sub-tag rules: A) if the semantic role of <role> is temporal expression ("AM-TMP"), then two additional mentions are created: (1) a temporal-expression mention with span <role><span> (if not already extracted) (2) a TLINK between the event mention (<predicate><span>) and the temporal-expression mention (<role><span>) B) else if the <role> <span> COINCIDES EXACTLY with a previously extracted mention then create an single additional mention (a participation mention with span <predicate><span> + <role><span>) */ if (prdGObj instanceof Role) { boolean MenCreated = false; String charS = null; String deg2 = ""; LinkedList<Term> roleTermList = null; Span roleSpan = ((Role) prdGObj).getSpan(); String roleCharSpan = getCharSpanFromSpan(roleSpan,vars); boolean createTemporalexpressionMentionFlag = false; boolean createTlinkFlag = false; boolean createParticipationMentionFlag = false; String semRole = ((Role) prdGObj).getSemRole(); if ((semRole != null) && (semRole.equalsIgnoreCase("AM-TMP"))) { createTlinkFlag = true; createTemporalexpressionMentionFlag = true; logDebug(" ROL1: <srl> <role> found TLINK for |" + predicateCharSpan + "|" + roleCharSpan + "|",vars); } else { if (checkAlreadyAcceptedMention(roleCharSpan,vars)) { createParticipationMentionFlag = true; logDebug(" ROL1: <srl> <role> found already existent mention for |" + roleCharSpan + "|",vars); } } /* create a temporal-expression mention with span <role><span> if not already extracted */ if (createTemporalexpressionMentionFlag) { if (! checkAlreadyAcceptedMention(roleCharSpan,vars)) { Record roleM = Record.create(); roleM.add(RDF.TYPE, NWR.TIME_MENTION, NWR.TIME_OR_EVENT_MENTION, NWR.ENTITY_MENTION, KS.MENTION); roleM.add(KS.MENTION_OF, vars.news_file_id); // compute the Term list for the <role> roleTermList = new LinkedList<Term>(); for (Target rspnTar : ((Role) prdGObj).getSpan().getTarget()) { Term ttmp = getTermfromTermId((Term) rspnTar.getId(),vars); roleTermList.addLast(ttmp); } // generate and set ID of the mention generateTheMIdAndSetID(roleSpan, roleM,vars); // try to add the mention if(addOrMergeAMention(roleM,vars) == 1) { vars.timeMention2++; } logDebug(" ROL1: created temporal-expression mention for |" + roleCharSpan + "|",vars); } } /* create the new relation mention (either participation or TLINK) with the span of <predicate> + <role> TODO: - check the enrichment (externalReferences, TYPE, extent, ...) - check SYNTACTIC_HEAD */ if (createParticipationMentionFlag || createTlinkFlag) { Record relationM = Record.create(); /* set as NWR.SOURCE of the relation mention the id of the EVENT_MENTION related to <predicate> */ if (eventMentionId != null) { relationM.add(NWR.SOURCE, new URIImpl(eventMentionId)); deg2 += "|SOURCE:" + eventMentionId; } else { logDebug("//NAF/srl/predicate/role/ - a Role without Predicate roleID(" + ((Role) prdGObj).getId() + ")", vars); } /* set as NWR.TARGET of the relation mention the id of the role mention related to <role> */ { URI roleId = getMentionIDFromCharSpan(roleCharSpan,vars); relationM.add(NWR.TARGET, roleId); } /* set the RDF.TYPE */ if (createParticipationMentionFlag) { relationM.add(RDF.TYPE, NWR.PARTICIPATION, NWR.RELATION_MENTION, KS.MENTION); deg2 = "|TYPE:PARTICIPATION,RELATION_MENTION,MENTION|" + deg2; relationM.add(NWR.THEMATIC_ROLE, ((Role) prdGObj).getSemRole()); deg2 += "|THEMATIC_ROLE:" + ((Role) prdGObj).getSemRole(); } else { relationM.add(RDF.TYPE, NWR.TLINK, NWR.RELATION_MENTION, KS.MENTION); deg2 = "|TYPE:TLINK,RELATION_MENTION,MENTION|" + deg2; } relationM.add(KS.MENTION_OF, vars.news_file_id); /* generate and set ID of the relation mention */ // compute the Term list for the <role> if (roleTermList == null) { roleTermList = new LinkedList<Term>(); for (Target rspnTar : ((Role) prdGObj).getSpan().getTarget()) { Term ttmp = getTermfromTermId((Term) rspnTar.getId(),vars); roleTermList.addLast(ttmp); } } generateTheMIdAndSetID_forParticipationMention(eventTermList, roleTermList, relationM,vars); deg2 = "MentionId:" + relationM.getID() + deg2; boolean create = false; /* always add the relation mention (do not check if a previously accepted mention with the span of <role> exists) */ int addedNew = -1; MenCreated = true; charS = relationM.getUnique(NIF.BEGIN_INDEX, Integer.class) + "," + relationM.getUnique(NIF.END_INDEX, Integer.class); if (createParticipationMentionFlag) { logDebug(" ROL1: <srl> <predicate> <role> adding new participation mention for |" + charS + "|",vars); } else { logDebug(" ROL1: <srl> <predicate> <role> adding new TLINK mention for |" + charS + "|",vars); } /* try to add the relation mention */ addedNew = addOrMergeAMention(relationM,vars); if (addedNew==1){ vars.rolewithEntity++; vars.rolewithEntity2++; vars.roleMentions++; } else { // if with entity and conflict or enriched, counted as discarded if(create){ vars.rolewithoutEntity++; } } /* add the information from <externalReferences> sub-tag (the relation mention is always created) */ for (ExternalReferences roleGOBJ : ((Role) prdGObj).getExternalReferences()) { for (ExternalRef rexRefObj : roleGOBJ.getExternalRef()) { // check 'resource' and 'reference' attributes String resourceValue = rexRefObj.getResource(); String referenceValue = rexRefObj.getReference(); if (resourceValue != null) { URI resourceMappedValue = vars.srlExternalRefResourceTypeMapper.get(resourceValue); URIImpl valueURI; if (resourceMappedValue != null) { valueURI = getUriForSrlExternalRefResource(resourceValue, referenceValue); } else { // force dynamic URIs resourceMappedValue = ValueFactoryImpl.getInstance() .createURI(NWR.NAMESPACE, resourceValue.toLowerCase() + "Ref"); valueURI = new URIImpl("http: + resourceValue.toLowerCase() + "/" + referenceValue); } if (charS != null) { vars.mentionListHash.get(charS).add(resourceMappedValue, valueURI); } deg2 += "|" + resourceMappedValue + ":" + valueURI; } else { // resourceValue == null) logDebug("xpath(//NAF/srl/predicate/role/externalReferences/externalRef@Resource(NULL)): RoleID(" + ((Role) prdGObj).getId() + ")", vars); } } } // end of adding info from <externalReferences> within <role> } logDebug(deg2,vars); } // end of <role> processing } // end of iteration over <externalReferences> or <role>s of the <predicate> } // end of iteration over <predicate> } private static List<PredicateAnchor> getAllRelativePredicateAnchors(String id, processNAFVariables vars) { List<PredicateAnchor> tmp= new ArrayList<PredicateAnchor>(); for( PredicateAnchor pas:vars.doc.getTemporalRelations().getPredicateAnchor()){ for(Span t: pas.getSpan()){ for(Target tm: t.getTarget()){ if(((Predicate)tm.getId()).getId().equalsIgnoreCase(id)){ tmp.add(pas); break; } } } } return tmp; } private static void getNAFHEADERMentions(NafHeader obj,processNAFVariables vars) { logDebug("Start reading the naf metadata:",vars); String deg = ""; Public publicProp = ((NafHeader) obj).getPublic(); initURIIDS(publicProp,vars); Record newsFile = Record.create(); Record nafFile = Record.create(); vars.nafFile2 = nafFile; vars.newsFile2 = newsFile; newsFile.setID(vars.news_file_id); nafFile.setID(vars.NAF_file_id); deg += "news_file_id:" + vars.news_file_id; newsFile.add(RDF.TYPE, NWR.NEWS); deg += "\nNAF_file_id:" + vars.NAF_file_id; nafFile.add(RDF.TYPE, NWR.NAFDOCUMENT); nafFile.add(NWR.ANNOTATION_OF, newsFile.getID()); newsFile.add(NWR.ANNOTATED_WITH, nafFile.getID()); if (vars.doc.getVersion() != null) { nafFile.add(NWR.VERSION, vars.doc.getVersion()); deg += "\nVERSION:" + vars.doc.getVersion(); } /* set DCTERMS.SOURCE according to the News URI */ URIImpl sourceURL; if (vars.PREFIX.matches("(?i)http: // LexisNexis news String preStr = "http: String postStr = "&csi=138620&perma=true"; String srcUrlstr = new String(preStr + publicProp.getPublicId() + postStr); sourceURL = new URIImpl(srcUrlstr); } else { // non-LexisNexis news sourceURL = (URIImpl)vars.news_file_id; } newsFile.add(DCTERMS.SOURCE, sourceURL); if (publicProp.getPublicId() != null) { nafFile.add(DCTERMS.IDENTIFIER, publicProp.getPublicId());// NAF/nafHeader/public@publicId deg += "|IDENTIFIER:" + publicProp.getPublicId(); } if (vars.doc.getXmlLang() != null) { newsFile.add(DCTERMS.LANGUAGE, Data.languageCodeToURI(vars.doc.getXmlLang())); deg += "|LANGUAGE:" + Data.languageCodeToURI(vars.doc.getXmlLang()); } else { logWarn("Language not catched:" + vars.doc.getXmlLang(),vars); } FileDesc fileDesc = null; if (((NafHeader) obj).getFileDesc() != null) { fileDesc = ((NafHeader) obj).getFileDesc(); if (fileDesc.getTitle() != null) { newsFile.add(DCTERMS.TITLE, fileDesc.getTitle()); deg += "|TITLE:" + fileDesc.getTitle(); } if (fileDesc.getAuthor() != null) { newsFile.add(DCTERMS.CREATOR, fileDesc.getAuthor()); deg += "|Author:" + fileDesc.getAuthor(); } if (fileDesc.getCreationtime() != null) { newsFile.add(DCTERMS.CREATED, fileDesc.getCreationtime()); deg += "|Creationtime:" + fileDesc.getCreationtime(); } if (fileDesc.getSection() != null) { newsFile.add(NWR.SECTION, fileDesc.getSection()); deg += "|SECTION:" + fileDesc.getSection(); } if (fileDesc.getMagazine() != null) { newsFile.add(NWR.MAGAZINE, fileDesc.getMagazine()); deg += "|MAGAZINE:" + fileDesc.getMagazine(); } if (fileDesc.getLocation() != null) { newsFile.add(NWR.LOCATION, fileDesc.getLocation()); deg += "|LOCATION:" + fileDesc.getLocation(); } if (fileDesc.getPublisher() != null) { newsFile.add(NWR.PUBLISHER, fileDesc.getPublisher()); deg += "|PUBLISHER:" + fileDesc.getPublisher(); } if (fileDesc.getFilename() != null) { newsFile.add(NWR.ORIGINAL_FILE_NAME, fileDesc.getFilename()); deg += "|Filename:" + fileDesc.getFilename(); } if (fileDesc.getFiletype() != null) { newsFile.add(NWR.ORIGINAL_FILE_FORMAT, fileDesc.getFiletype()); deg += "|Filetype:" + fileDesc.getFiletype(); } if (fileDesc.getPages() != null) { newsFile.add(NWR.ORIGINAL_PAGES, fileDesc.getPages()); deg += "|Pages:" + fileDesc.getPages(); } } else { logWarn("FileDesc: null",vars); } for (LinguisticProcessors lpObj : ((NafHeader) obj).getLinguisticProcessors()) { deg += "\n"; if (lpObj.getLayer() != null) { if (vars.nafLayerMapper.containsKey(lpObj.getLayer()) && vars.nafLayerMapper.get(lpObj.getLayer()) != null) { nafFile.add(NWR.LAYER, vars.nafLayerMapper.get(lpObj.getLayer())); deg += "LAYER:" + vars.nafLayerMapper.get(lpObj.getLayer()); } else { logDebug("xpath(//NAF/nafHeader/linguisticProcessors/@layer[" + lpObj.getLayer() + "]), unknown layer.", vars); } } for (Lp lpO : lpObj.getLp()) { deg += "\n"; Record r3 = Record.create(); if (lpO.getName() != null) { r3.add(DCTERMS.TITLE, lpO.getName()); deg += "TITLE:" + lpO.getName(); } if (lpO.getVersion() != null) { r3.add(NWR.VERSION, lpO.getVersion()); deg += "|VERSION:" + lpO.getVersion(); } String namuri = java.net.URLEncoder.encode(lpO.getName()); String uri = vars.PREFIX + (vars.PREFIX.endsWith("/") ? "" : "/") + "lp/" + namuri + "/" + lpO.getVersion(); URI rId = new URIImpl(uri); r3.setID(rId); nafFile.add(NWR.MODULES, r3); deg += "|CREATOR:" + r3; } } logDebug(deg,vars); } private static void getCoreferencesMentions(Coreferences obj,processNAFVariables vars) { if (!checkHeaderTextTerms(vars)) { logError("Error: populating interrupted",vars); } else { logDebug("Start mapping the Coreferences mentions:",vars); } String deg = "\n"; /* process the <coref> tag */ for (Coref corefObj : ((Coreferences) obj).getCoref()) { deg = ""; if (corefObj.getSpan().size() < 1) { logDebug("Every coref must contain a 'span' element inside 'references'", vars); } /* if type exists and =="event" then create a new mention for each span; otherwise create a new mention for each span only if at least one span includes (or is) a previously extracted mention. */ boolean addMentionsFlag = false; String corefType = corefObj.getType(); List<Object> typesOfIncludedMention = null; boolean eventM = false; if (corefType != null && corefType.equalsIgnoreCase("event")) { // create new mentions addMentionsFlag = true; eventM = true; } else { // check if at least one span includes (or is) a previously extracted mention for (Span corefSpan : corefObj.getSpan()) { String corefCharSpan = getCharSpanFromSpan(corefSpan,vars); Object[] retArray = checkSpanIncludesAnAlreadyAcceptedMention(corefCharSpan,vars); int inclFlag = ((Integer) retArray[0]).intValue(); if ((inclFlag == 1) || (inclFlag == 2)) { addMentionsFlag = true; String includedMentionCharSpan = (String)retArray[1]; typesOfIncludedMention = getMentionTypeFromCharSpan(includedMentionCharSpan,vars); logDebug("ROL1: <coref> id " + corefObj.getId() + ": found included mention for |" + corefCharSpan + "|, included mention |" + includedMentionCharSpan + "|, inclFlag " + inclFlag + ", types " + getTypeasString(typesOfIncludedMention),vars); break; } } } if (addMentionsFlag) { for (Span corefSpan : corefObj.getSpan()) { String corefCharSpan = getCharSpanFromSpan(corefSpan,vars); if (checkAlreadyAcceptedMention(corefCharSpan,vars)) { logDebug("ROL1: <coref> id " + corefObj.getId() + ": skipping already existent mention with charSpan |" + corefCharSpan + "|",vars); continue; } deg = ""; Record m = Record.create(); m.add(KS.MENTION_OF, vars.news_file_id); deg += "MENTION_OF:" + vars.news_file_id; if (corefObj.getSpan().size() > 1) { m.add(NWR.LOCAL_COREF_ID, corefObj.getId()); deg += "|LOCAL_COREF_ID:" + corefObj.getId(); } if (eventM) { m.add(RDF.TYPE, NWR.EVENT_MENTION, NWR.TIME_OR_EVENT_MENTION, NWR.ENTITY_MENTION, KS.MENTION); deg = "|TYPE:EVENT_MENTION,TIME_OR_EVENT_MENTION,ENTITY_MENTION,ENTITY_MENTION" + deg; eventM = true; } else { m.add(RDF.TYPE, NWR.OBJECT_MENTION, NWR.ENTITY_MENTION, KS.MENTION); deg = "TYPE:,OBJECT_MENTION,ENTITY_MENTION,ENTITY_MENTION|" + deg; // add types of includedMention if (typesOfIncludedMention != null) { m.add(RDF.TYPE, typesOfIncludedMention); } } logDebug("ROL1: <coref> id " + corefObj.getId() + ": adding new mention with charSpan |" + corefCharSpan + "|, and type " + m.get(RDF.TYPE),vars); if (corefSpan.getTarget().size() < 1) { logDebug("Every span in an entity must contain at least one target inside", vars); } for (Target spTar : corefSpan.getTarget()) { if (eventM) { Term eventTerm = getTermfromTermId((Term) spTar.getId(),vars); m.add(NWR.PRED, eventTerm.getLemma()); deg += "|PRED:" + eventTerm.getLemma(); if (eventTerm.getPos() != null) { URI posVal = (eventTerm.getPos().equals("V") || eventTerm.getPos().equals("N")) ? vars.partOfSpeechMapper.get(eventTerm.getPos()) : vars.partOfSpeechMapper.get(""); m.add(NWR.POS, posVal); deg += "|POS:" + posVal; } else { logDebug("//NAF/coreferences/coref/span/target/@id/@getPOS[null], id(" + eventTerm.getId() + ")", vars); } } if (!eventM && spTar.getHead() != null && spTar.getHead().equals("yes")) { if (spTar.getId() != null) { m.add(NWR.SYNTACTIC_HEAD, spTar.getId()); deg += "|SYNTACTIC_HEAD:" + spTar.getId(); } else { logDebug("//NAF/coreferences/coref/span/target[@head='yes']/@id[null], id(" + spTar.getId() + ")", vars); } } } generateTheMIdAndSetID(corefSpan, m,vars); deg = "MentionId:" + m.getID() + deg; logDebug(deg,vars); int addedNew = addOrMergeAMention(m,vars); if (!eventM){ // eventM == false if(addedNew==1){ vars.corefMention2++; vars.no_mapping++; vars.corefMentionNotEvent++; vars.corefMention++; // logWarn("xpath(//NAF/coreferences/coref/) add a new object mention, missing type."); } } else { // eventM == true if(addedNew==1){ vars.srlMention2++; vars.corefMentionEvent++; vars.corefMention++; } } String charS2 = m.getUnique(NIF.BEGIN_INDEX, Integer.class) + "," + m.getUnique(NIF.END_INDEX, Integer.class); vars.entityMentions.put(charS2,m); } } else { logDebug("ROL1: <coref> id " + corefObj.getId() + ": entirely skipped, NO included mentions",vars); } } } private static LinkedList<Term> mergeTwoTermLists(LinkedList<Term> eventTermList, LinkedList<Term> roleTermList,processNAFVariables vars) { LinkedList<Term> merged = new LinkedList<Term>(); /* first the eventTermList (from <predicate>) then roleTermList (from <role>) */ for (Term evn : eventTermList) { merged.addLast(evn); } for (Term rol : roleTermList) { merged.addLast(rol); } logDebug("Two lists merged: eventTermListSize(" + eventTermList.size() + ") + roleTermListSize(" + roleTermList.size() + ") = mergedListSize(" + merged.size() + ").",vars); return merged; } // given a charSpan (e.g. "321,325") check if there is an already accepted mention with such span private static boolean checkAlreadyAcceptedMention(String charSpan,processNAFVariables vars) { return vars.mentionListHash.containsKey(charSpan); } // given a charSpan (e.g. "321,325") check if it includes an already accepted mention; // return an array of 3 Objects: (Integer)inclFlag, (String)outCharSpan where // 0, null if there are no already-accepted mentions included in the charSpan // 1, charSpan if an already-accepted mention coincides with the charSpan // 2, chSpanOfIncludedMention if an already-accepted mention is stricly included in the charSpan private static Object[] checkSpanIncludesAnAlreadyAcceptedMention(String charSpan,processNAFVariables vars) { Object[] retArray = new Object[2]; // check if an already-accepted mention coincides if (checkAlreadyAcceptedMention(charSpan,vars)) { retArray[0] = new Integer(1); retArray[1] = charSpan; return retArray; } // check if an already-accepted mention is strictly included String[] fields = charSpan.split(","); int spanBeginC = Integer.parseInt(fields[0]); int spanEndC = Integer.parseInt(fields[1]); Enumeration keys = vars.mentionListHash.keys(); String[] kfields; int kBeginC; int kEndC; while( keys.hasMoreElements() ) { String key = (String) keys.nextElement(); kfields = key.split(","); kBeginC = Integer.parseInt(kfields[0]); kEndC = Integer.parseInt(kfields[1]); if ((kBeginC >= spanBeginC) && (kEndC <= spanEndC)) { retArray[0] = new Integer(2); retArray[1] = key; return retArray; } } // no already-accepted mentions included retArray[0] = new Integer(0); retArray[1] = null; return retArray; } // given a Span object return its charSpan (e.g. "321,325") private static String getCharSpanFromSpan(Span sp,processNAFVariables vars) { LinkedList<Wf> wordsL = fromSpanGetAllMentions(sp.getTarget(),vars); String begin = wordsL.getFirst().getOffset(); Wf lastW = wordsL.getLast(); int end = Integer.parseInt(lastW.getOffset()) + Integer.parseInt(lastW.getLength()); String charSpan = begin + "," + Integer.toString(end); return charSpan; } // given a charSpan (e.g. "321,325") get the ID of the mention with such span if exists, otherwise return null private static URI getMentionIDFromCharSpan(String charSpan,processNAFVariables vars) { if (vars.mentionListHash.containsKey(charSpan)) { return vars.mentionListHash.get(charSpan).getID(); } else { return null; } } // given a charSpan (e.g. "321,325") get the type of the mention with such span if exists, otherwise return null private static List<Object> getMentionTypeFromCharSpan(String charSpan,processNAFVariables vars) { if (vars.mentionListHash.containsKey(charSpan)) { return vars.mentionListHash.get(charSpan).get(RDF.TYPE); } else { return null; } } /* return: 1 if input mention "m" was added as a new mention 0 if a previously accepted mention with the same span of input mention m was enriched <0 in case of problems (e.g. due to a conflict with previously accepted mention); input mention m was not added */ private static Integer addOrMergeAMention(Record m,processNAFVariables vars) { String charS = m.getUnique(NIF.BEGIN_INDEX, Integer.class) + "," + m.getUnique(NIF.END_INDEX, Integer.class); if (vars.mentionListHash.containsKey(charS)) { /* there is a previously accepted mention with the same span: try to enrich it */ boolean chk = checkClassCompatibility(vars.mentionListHash.get(charS), m); if (!chk) { /* there is conflict between the input mention and the previously accepted mention with the same span: check if the new mention can replace the old one, otherwise report the error */ if (checkMentionReplaceability(vars.mentionListHash.get(charS), m)){ // replace the old mention with the new one vars.mentionListHash.put(charS, m); logDebug("Replacement with Mention: " + m.getID() + ", class(" + getTypeasString(m.get(RDF.TYPE)) + ")", vars); return 0; } String types =getTypeasString(m.get(RDF.TYPE)); if(types.contains(NWR.PARTICIPATION.stringValue())){ logDebug("Participation collision error, mentionID(" + m.getID() + ") class1(" + getTypeasString(m.get(RDF.TYPE)) + "), class-pre-xtracted(" + getTypeasString(vars.mentionListHash.get(charS).get(RDF.TYPE)) + ")", vars); }else{ logDebug("Generic collision error, mentionID(" + m.getID() + ") class1(" + getTypeasString(m.get(RDF.TYPE)) + "), class-pre-xtracted(" + getTypeasString(vars.mentionListHash.get(charS).get(RDF.TYPE)) + ")", vars); } return -1; } else { /* there is compatibility between the input mention and the previously accepted mention with the same span: enrich old mention with properties from the new one (except participation mentions) */ String types =getTypeasString(m.get(RDF.TYPE)); if(types.contains(NWR.PARTICIPATION.stringValue())){//Rule: no enrichment for participation logDebug("Refused enrichment with participation mention, mentionID(" + m.getID() + ")", vars); return -1; } // enrich mention ListIterator<URI> mit = m.getProperties().listIterator(); while (mit.hasNext()) { URI mittmp = mit.next(); for (Object pit : m.get(mittmp)) { vars.mentionListHash.get(charS).add(mittmp, pit); } } logDebug("Mention enrichment: " + m.getID() + ", class(" + getTypeasString(m.get(RDF.TYPE)) + ")", vars); return 0; } } else { /* the mention is new (there is no previously accepted mention with the same span) */ vars.mentionListHash.put(charS, m); logDebug("Created Mention: " + m.getID(),vars); return 1; } } // apply to all the mentions the following changes: // - add the "extent" attribute as NIF.ANCHOR_OF private static void fixMentions(processNAFVariables vars) { Enumeration keys = vars.mentionListHash.keys(); while( keys.hasMoreElements() ) { String key = (String) keys.nextElement(); Record m = (Record) vars.mentionListHash.get(key); // get charStartIndex and charEndIndex from the mention charSpan (= the key) String[] csList = key.split(","); int cStart = Integer.parseInt(csList[0]); int cEnd = Integer.parseInt(csList[1]); String extentStr = vars.rawText.substring(cStart, cEnd); m.add(NIF.ANCHOR_OF, extentStr); } } private static String getTypeasString(List<Object> list) { String tmp=""; for(Object ll :list){ tmp+=ll.toString()+","; } tmp+="\""; return tmp.replace(",\"",""); } private static boolean checkClassCompatibility(Record m, Record m2) { List<Object> types = m.get(RDF.TYPE); List<Object> types1 = m2.get(RDF.TYPE); for (Object tytmp : types) { if (!types1.contains(tytmp)) { return false; } } return true; } private static boolean checkMentionReplaceability(Record oldM, Record newM) { /* return true oldM can be replaced with newM; this happens if oldM is a generic OBJECT_MENTION (= without ENTITY_TYPE) and newM is more specific (an OBJECT_MENTION with ENTITY_TYPE, or a TIME_MENTION, or EVENT_MENTION) */ List<Object> typesOld = oldM.get(RDF.TYPE); List<Object> typesNew = newM.get(RDF.TYPE); boolean isGenericOldM = (typesOld.contains(NWR.OBJECT_MENTION) && (oldM.get(NWR.ENTITY_TYPE) == null||oldM.get(NWR.ENTITY_TYPE).size() == 0)); boolean isSpecificNewM = ((typesNew.contains(NWR.OBJECT_MENTION) && (newM.get(NWR.ENTITY_TYPE) != null && oldM.get(NWR.ENTITY_TYPE).size() > 0)) || typesNew.contains(NWR.TIME_MENTION) || typesNew.contains(NWR.EVENT_MENTION)); /* logWarn("ROL3: checkMentionReplaceability: " + getTypeasString(typesOld) + "| " + getTypeasString(typesNew)); logWarn("ROL3: isGenericOldM " + isGenericOldM + "| isSpecificNewM " + isSpecificNewM); */ if (isGenericOldM && isSpecificNewM) { return true; } else { return false; } } private static void initURIIDS(Public publicProp,processNAFVariables vars) { if (publicProp.getPublicId() == null) { logError("Corrupted Naf file: PublicId in the Naf header is missed",vars); System.exit(0); } vars.nafPublicId = publicProp.getPublicId(); String uri = publicProp.getUri(); //TODO remove it @mohammed Sept2014PREFIX //uri = PREFIX+uri; vars.news_file_id = new URIImpl(uri); String nafuri = uri + ".naf"; vars.NAF_file_id = new URIImpl(nafuri); logDebug("news_file_id: " + uri,vars); logDebug("NAF_file_id: " + nafuri,vars); // set the PREFIX given the news uri try { URL nurl = new URL(uri); Path p = Paths.get(nurl.getPath()); vars.PREFIX = nurl.getProtocol() + "://" + nurl.getAuthority() + "/" + p.subpath(0,2); } catch (Exception me) { vars.PREFIX = vars.news_file_id.getNamespace(); } logDebug("PREFIX: " + vars.PREFIX,vars); } static void generateMIDAndSetIdWF(LinkedList<Wf> wordsL, Record m,processNAFVariables vars) { int begin = Integer.parseInt(wordsL.getFirst().getOffset()); int end = (Integer.parseInt(wordsL.getLast().getOffset()) + Integer.parseInt(wordsL .getLast().getLength())); m.add(NIF.BEGIN_INDEX, begin); m.add(NIF.END_INDEX, end); String tmpid = vars.news_file_id + "#char=" + begin + "," + end; URI mId = new URIImpl(tmpid); m.setID(mId); } private static void logError(String error,processNAFVariables vars) { if (vars.logErrorActive) { vars.logger.error(vars.filePath.getName() + " " + error); } if (!vars.storePartialInforInCaseOfError) { System.exit(-1); } } private static void logDebug(String error,processNAFVariables vars) { if (vars.logDebugActive) { vars.logger.debug(error); } } private static void logWarn(String error,processNAFVariables vars) { vars.logger.warn(vars.filePath.getName() + " "+error); } private static boolean checkHeaderTextTerms(processNAFVariables vars) { if (vars.globalTerms == null) { logWarn("Error: No term(s) has been catched!",vars); return false; } if (vars.globalText == null) { logWarn("Error: No text(s) has been catched!",vars); return false; } return true; } public static Logger getLogger(processNAFVariables vars) { return vars.logger; } public static void setLogger(final Logger logger,processNAFVariables vars) { vars.logger = logger; } private static void generateTheMIdAndSetID(Span spansObj, Record m,processNAFVariables vars) { LinkedList<Wf> wordsL = fromSpanGetAllMentions(((Span) spansObj).getTarget(),vars); int begin = Integer.parseInt(wordsL.getFirst().getOffset()); int end = (Integer.parseInt(wordsL.getLast().getOffset()) + Integer.parseInt(wordsL .getLast().getLength())); m.add(NIF.BEGIN_INDEX, begin); m.add(NIF.END_INDEX, end); String muri = vars.news_file_id + "#char=" + begin + "," + end; URI mId = new URIImpl(muri); m.setID(mId); } /* similar to generateTheMIdAndSetID() but specific for ParticipationMention */ private static void generateTheMIdAndSetID_forParticipationMention(LinkedList<Term> eventTermList, LinkedList<Term> roleTermList, Record m,processNAFVariables vars) { LinkedList<Wf> eventWordList = getTheWFListByThereTermsFromTargetList(eventTermList,vars); LinkedList<Wf> roleWordList = getTheWFListByThereTermsFromTargetList(roleTermList,vars); int charStartOfEvent = Integer.parseInt(eventWordList.getFirst().getOffset()); int charEndOfEvent = Integer.parseInt(eventWordList.getLast().getOffset()) + Integer.parseInt(eventWordList.getLast().getLength()); int charStartOfRole = Integer.parseInt(roleWordList.getFirst().getOffset()); int charEndOfRole = Integer.parseInt(roleWordList.getLast().getOffset()) + Integer.parseInt(roleWordList.getLast().getLength()); int beginIndex, endIndex; if (charStartOfEvent < charStartOfRole) { beginIndex = charStartOfEvent; endIndex = charEndOfRole; } else { beginIndex = charStartOfRole; endIndex = charEndOfEvent; } m.add(NIF.BEGIN_INDEX, beginIndex); m.add(NIF.END_INDEX, endIndex); String muri = vars.news_file_id + "#char=" + beginIndex + "," + endIndex; URI mId = new URIImpl(muri); m.setID(mId); } /* similar to generateTheMIdAndSetID() but specific for ParticipationMention */ private static String getExtentOfParticipationMention(LinkedList<Term> eventTermList, LinkedList<Term> roleTermList,processNAFVariables vars) { LinkedList<Wf> eventWordList = getTheWFListByThereTermsFromTargetList(eventTermList,vars); LinkedList<Wf> roleWordList = getTheWFListByThereTermsFromTargetList(roleTermList,vars); LinkedList<Wf> mergedWordList = new LinkedList<Wf>(); int charStartOfEvent = Integer.parseInt(eventWordList.getFirst().getOffset()); int charStartOfRole = Integer.parseInt(roleWordList.getFirst().getOffset()); LinkedList<Wf> firstWL, secondWL; if (charStartOfEvent <= charStartOfRole) { firstWL = eventWordList; secondWL = roleWordList; } else { firstWL = roleWordList; secondWL = eventWordList; } for (Wf w : firstWL) { if (! mergedWordList.contains(w)) {mergedWordList.add(w);} } for (Wf w : secondWL) { if (! mergedWordList.contains(w)) {mergedWordList.add(w);} } StringBuffer extent = new StringBuffer(); for (Wf w : mergedWordList) { extent.append(w.getvalue() + " "); } String sExtent = extent.toString(); return sExtent.substring(0, sExtent.length() - 1); } /* return true if another mention exists with the same span */ private static boolean checkDuplicate(String muri,processNAFVariables vars) { boolean re = false; for(String keys:vars.entityMentions.keySet()){ if (keys.equals(muri)) { //if (mtmp.getID().stringValue().equals(muri)) { re = true; break; } } return re; } private static Term getTermfromTermId(Term termId,processNAFVariables vars) { if (vars.globalTerms != null) { if (vars.globalTerms.getTerm().contains(termId)) return vars.globalTerms.getTerm().get(vars.globalTerms.getTerm().indexOf(termId)); } else { Terms ltmp = vars.doc.getTerms(); if (((Terms) ltmp).getTerm().contains(termId)) return vars.globalTerms.getTerm().get(vars.globalTerms.getTerm().indexOf(termId)); } logWarn("Term is not found, searched TermId(" + termId.getId() + ")",vars); return null; } private static LinkedList<Wf> fromSpanGetAllMentionsTmx(List<Target> list,processNAFVariables vars) { LinkedList<Wf> returned = new LinkedList<Wf>(); LinkedList<Wf> wordsIDL = new LinkedList<Wf>(); for (Target ltmp : list) { wordsIDL.addLast((Wf) ltmp.getId()); } if (vars.globalText != null) { int found = 0; for (Wf wftmp : vars.globalText.getWf()) { if (wordsIDL.contains(wftmp)) { returned.addLast(wftmp); found++; } if (found >= wordsIDL.size()) { break; } } } else { Text prop = vars.doc.getText(); int found = 0; for (Wf wftmp : prop.getWf()) { if (wordsIDL.contains(wftmp)) { returned.addLast(wftmp); found++; } if (found >= wordsIDL.size()) { break; } } } return returned; } private static LinkedList<Wf> getTheWFListByThereTermsFromTargetList(LinkedList<Term> targetTermList,processNAFVariables vars) { LinkedList<Wf> returned = new LinkedList<Wf>(); LinkedList<Wf> wordsIDL = new LinkedList<Wf>(); boolean spanTermFound = false; if (vars.globalTerms != null) { for (Term termtmp : vars.globalTerms.getTerm()) { if (targetTermList.contains(termtmp)) { Iterator<Object> spansl = termtmp .getSentimentOrSpanOrExternalReferencesOrComponent().iterator(); while (spansl.hasNext()) { Object spantmp = spansl.next(); if (spantmp instanceof Span) { spanTermFound = true; for (Target targtmp : ((Span) spantmp).getTarget()) { wordsIDL.addLast((Wf) targtmp.getId()); } } } } } } else { Terms prop = vars.doc.getTerms(); for (Term termtmp : prop.getTerm()) { if (targetTermList.contains(termtmp)) { Iterator<Object> spansl = termtmp .getSentimentOrSpanOrExternalReferencesOrComponent() .iterator(); while (spansl.hasNext()) { Object spantmp = spansl.next(); if (spantmp instanceof Span) { spanTermFound = true; for (Target targtmp : ((Span) spantmp).getTarget()) { wordsIDL.addLast((Wf) targtmp.getId()); } } } } } } /* if (!spanTermFound) { logWarn("Inconsistence NAF file(#TS): Every term must contain a span element",vars); }*/ if (vars.globalText != null) { int found = 0; for (Wf wftmp : vars.globalText.getWf()) { if (wordsIDL.contains(wftmp)) { returned.addLast(wftmp); found++; } if (found >= wordsIDL.size()) { break; } } if (found < wordsIDL.size()) { logWarn("Inconsistence NAF file(#SW): Wf(s) arenot found when loading term ",vars); } } else { Text prop = vars.doc.getText(); int found = 0; for (Wf wftmp : prop.getWf()) { if (wordsIDL.contains(wftmp)) { returned.addLast(wftmp); found++; } if (found >= wordsIDL.size()) { break; } } if (found < wordsIDL.size()) { logWarn("Inconsistence NAF file(#SW): Wf(s) arenot found when loading term ",vars); } } return returned; } private static LinkedList<Wf> fromSpanGetAllMentions(List<Target> list,processNAFVariables vars) { LinkedList<Term> targetTermList = new LinkedList<Term>(); Iterator<Target> targetList = list.iterator(); while (targetList.hasNext()) { Target tarm = targetList.next(); targetTermList.add((Term)tarm.getId()); } LinkedList<Wf> corrispondingWf = getTheWFListByThereTermsFromTargetList(targetTermList,vars); return corrispondingWf; } public static void readNAFFile(File naf,processNAFVariables vars) { try { JAXBContext jc = JAXBContext.newInstance("eu.fbk.knowledgestore.populator.naf.model"); Unmarshaller unmarshaller = jc.createUnmarshaller(); byte[] bytes = ByteStreams.toByteArray(IO.read(naf.getAbsolutePath())); vars.doc = (NAF) unmarshaller.unmarshal(new InputStreamReader(new ByteArrayInputStream(bytes), "UTF-8")); } catch (UnsupportedEncodingException e) { logError(e.getMessage(),vars); } catch (FileNotFoundException e) { logError(e.getMessage(),vars); } catch (IOException e) { logError(e.getMessage(),vars); } catch (JAXBException e) { logError(e.getMessage(),vars); } } static void calculateMemory() { int mb = 1024 * 1024; // Getting the runtime reference from system Runtime runtime = Runtime.getRuntime(); System.err.println(" // Print used memory System.err.println("Used Memory:" + (runtime.totalMemory() - runtime.freeMemory()) / mb); // Print free memory System.err.println("Free Memory:" + runtime.freeMemory() / mb); // Print total available memory System.err.println("Total Memory:" + runtime.totalMemory() / mb); // Print Maximum available memory System.err.println("Max Memory:" + runtime.maxMemory() / mb); } }
package nl.tudelft.lifetiles.graph.model; import java.util.HashSet; import java.util.Set; import java.util.TreeSet; import nl.tudelft.lifetiles.core.util.Logging; import nl.tudelft.lifetiles.core.util.Settings; import nl.tudelft.lifetiles.core.util.Timer; import nl.tudelft.lifetiles.graph.traverser.EmptySegmentTraverser; import nl.tudelft.lifetiles.graph.traverser.MutationIndicationTraverser; import nl.tudelft.lifetiles.graph.traverser.ReferencePositionTraverser; import nl.tudelft.lifetiles.graph.traverser.UnifiedPositionTraverser; import nl.tudelft.lifetiles.sequence.model.Sequence; import nl.tudelft.lifetiles.sequence.model.SequenceSegment; /** * The Tile holds the graph and will be transformed to this modelgraph so * that the graph can be drawn on the screen. * */ public class GraphContainer { /** * The setting key for empty segments. */ private static final String SETTING_EMPTY = "empty_segments"; /** * The setting key for mutation indication. */ private static final String SETTING_MUTATION = "mutations"; /** * The Current graph that this model is holding. */ private final Graph<SequenceSegment> graph; /** * The Current graph that this model is holding in bucket cache form. */ private final BucketCache segmentBuckets; /** * The set of currently visible sequencesegments. */ private Set<SequenceSegment> visibles; /** * The set of visible sequences. */ private Set<Sequence> visibleSequences; /** * The amount of vertices to be placed in one bucket. */ private static final int NUM_VERTICES_BUCKET = Integer.parseInt(Settings .get("num_vertices_bucket")); /** * create a new Tile. * * @param graph * The initial graph * @param reference * Reference currently active in the graph controller. */ public GraphContainer(final Graph<SequenceSegment> graph, final Sequence reference) { this.graph = graph; for (SequenceSegment segment : this.graph.getAllVertices()) { segment.setReferenceStart(1); segment.setReferenceEnd(Long.MAX_VALUE); segment.setMutation(null); } alignGraph(); if (reference != null) { findMutations(reference); } segmentBuckets = new BucketCache(graph.getAllVertices().size() / NUM_VERTICES_BUCKET, this.graph); visibles = graph.getAllVertices(); } /** * Align the graph. */ private void alignGraph() { UnifiedPositionTraverser.unifyGraph(graph); if (Settings.getBoolean(SETTING_EMPTY)) { EmptySegmentTraverser.addEmptySegmentsGraph(graph); } } /** * Find the mutations on the graph. * * @param reference * Reference of the graph which is used to indicate mutations. */ private void findMutations(final Sequence reference) { if (!Settings.getBoolean(SETTING_MUTATION)) { return; } ReferencePositionTraverser.referenceMapGraph(graph, reference); MutationIndicationTraverser.indicateGraphMutations(graph, reference); } /** * Change the graph by selecting the sequences to draw. * * @param visibleSequences * the sequences to display */ public final void setVisible(final Set<Sequence> visibleSequences) { Timer timer = Timer.getAndStart(); // Find out which vertices are visible now Set<SequenceSegment> vertices = new TreeSet<SequenceSegment>(); for (SequenceSegment segment: graph.getAllVertices()) { //copy the set of sequences because retainAll modifies the original set Set<Sequence> intersect; intersect = new HashSet<Sequence>(segment.getSources()); //check if any of the visible sequences are in this nodes sources if (visibleSequences != null) { intersect.retainAll(visibleSequences); } if (!intersect.isEmpty()) { vertices.add(segment); } } visibles = vertices; this.visibleSequences = visibleSequences; timer.stopAndLog("Creating visible graph"); } /** * Get the visible segments that this model is holding. * * @param start * starting bucket position * @param end * the last bucket position * @return graph */ public final Set<SequenceSegment> getVisibleSegments(final int start, final int end) { Set<SequenceSegment> copy = new TreeSet<SequenceSegment>(); for (SequenceSegment seg : segmentBuckets.getSegments(start, end)) { try { copy.add(seg.clone()); } catch (CloneNotSupportedException e) { Logging.exception(e); } } // Keep only the sequencesegments that are visible copy.retainAll(visibles); // Set the sources so they only contain the visible sequences if (visibleSequences != null) { for (SequenceSegment vertex : copy) { vertex.getSources().retainAll(visibleSequences); } } return copy; } /** * Returns the bucketCache to check the current position. * * @return the bucketCache of the graph. */ public final BucketCache getBucketCache() { return segmentBuckets; } }
package com.cisco.oss.foundation.cluster.mongo; import com.cisco.oss.foundation.cluster.utils.MasterSlaveConfigurationUtil; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.Pair; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.allanbank.mongodb.Credential.Builder; import com.allanbank.mongodb.MongoClientConfiguration; import com.allanbank.mongodb.MongoCollection; import com.allanbank.mongodb.MongoDatabase; import com.allanbank.mongodb.MongoFactory; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; public enum MongoClient { INSTANCE; private static final Logger LOGGER = LoggerFactory.getLogger(MongoClient.class); private Logger logger = null; private static final String DATA_CENTER_COLLECTION = "dataCenter"; private static final int DB_RETRY_DELAY = 10; private static final String MASTER_SLAVE_COLLECTION = "masterSlave"; public AtomicBoolean IS_DB_UP = new AtomicBoolean(false); private MongoDatabase database; private MongoCollection dataCenter; private MongoCollection masterSlave; private static String mongoUserName = ""; private static String mongoPassword = ""; private static boolean isAuthenticationEnabled = false; MongoClient() { logger = LoggerFactory.getLogger(MongoClient.class); try { database = connect(); } catch (MissingMongoConfigException e) { throw e; } catch (Exception e) { infiniteConnect(); } dataCenter = database.getCollection(DATA_CENTER_COLLECTION); masterSlave = database.getCollection(MASTER_SLAVE_COLLECTION); } /** * call this method first if you want to enable authenticated mongo db access * @param user the db user * @param password teh db pasword */ public static void enableAuthentication(String user, String password){ if(StringUtils.isBlank(user)){ throw new IllegalArgumentException("mongo user can't be null or empty"); } if(StringUtils.isBlank(password)){ throw new IllegalArgumentException("mongo password can't be null or empty"); } isAuthenticationEnabled = true; mongoUserName = user; mongoPassword = password; } private MongoDatabase connect(){ MongoClientConfiguration config = new MongoClientConfiguration(); List<Pair<String, Integer>> mongodbServers = MasterSlaveConfigurationUtil.getMongodbServers(); for (Pair<String, Integer> mongodbServer : mongodbServers) { config.addServer(mongodbServer.getLeft() + ":" + mongodbServer.getRight()); } config.setMaxConnectionCount(10); String dbName = MasterSlaveConfigurationUtil.getMongodbName(); if (isAuthenticationEnabled) { Builder credentials = new Builder(); credentials.userName(mongoUserName); credentials.password(mongoPassword.toCharArray()); credentials.setDatabase(dbName); config.addCredential(credentials); } com.allanbank.mongodb.MongoClient mongoClient = MongoFactory.createClient(config); database = mongoClient.getDatabase(dbName); //Check Authentication try { database.getCollection(DATA_CENTER_COLLECTION).count(); IS_DB_UP.set(true); } catch (Exception e) { //will raise an error if authentication fails or if server is down String message = "Can't connect to '" + dbName + "' mongoDB. Please check connection and configuration. MongoDB error message: " + e.toString(); // logger.error(message, e); throw new RuntimeException(message); } return database; } private void infiniteConnect() { Thread reConnectThread = new Thread(new Runnable() { @Override public void run() { while (!IS_DB_UP.get()) { try { connect(); IS_DB_UP.set(true); logger.info("dc reconnect is successful"); } catch (Exception e) { logger.warn("db reconnect failed. retrying in {} seconds. error: {}", DB_RETRY_DELAY, e); try { TimeUnit.SECONDS.sleep(DB_RETRY_DELAY); } catch (InterruptedException e1) { //ignore } } } } }, "Infinite-Reconnect"); reConnectThread.start(); reConnectThread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(Thread t, Throwable e) { LOGGER.error("Uncaught Exception in thread: {}. Exception is: {}", t.getName(), e); } }); } /** * @return the data center mongo collection */ public MongoCollection getDataCenterCollection() { return dataCenter; } /** * @return the master slave collection */ public MongoCollection getMasterSlaveCollection() { return masterSlave; } }
package org.codehaus.modello.plugin.java.javasource; import java.util.ArrayList; import java.util.Enumeration; import java.util.Iterator; import java.util.List; import java.util.Vector; /** * A representation of the Java Source code for a Java Class. This is * a useful utility when creating in memory source code. * This package was modelled after the Java Reflection API * as much as possible to reduce the learning curve. * * @author <a href="mailto:kvisco@intalio.com">Keith Visco</a> * @author <a href="mailto:skopp@riege.de">Martin Skopp</a> * @version $Revision$ $Date$ */ public class JClass extends JStructure { /** * The list of constructors for this JClass */ private Vector _constructors = null; /** * The list of member variables (fields) of this JClass */ private JNamedMap _fields = null; private Vector _innerClasses = null; /** * The list of methods of this JClass */ private Vector _methods = null; /** * The superclass for this JClass */ private String _superClass = null; /** * The source code for static initialization **/ private JSourceCode _staticInitializer = new JSourceCode(); public JClass( String name ) throws IllegalArgumentException { super( name ); _constructors = new Vector(); _fields = new JNamedMap(); _methods = new Vector(); _innerClasses = new Vector(); //-- initialize default Java doc getJDocComment().appendComment( "Class " + getLocalName() + "." ); } //-- JClass public void addConstructor( JConstructor constructor ) throws IllegalArgumentException { if ( constructor == null ) throw new IllegalArgumentException( "Constructors cannot be null" ); if ( constructor.getDeclaringClass() == this ) { /** check signatures (add later) **/ if ( !_constructors.contains( constructor ) ) { _constructors.addElement( constructor ); } } else { String err = "The given JConstructor was not created "; err += "by this JClass"; throw new IllegalArgumentException( err ); } } public void addField( JField jField ) throws IllegalArgumentException { if ( jField == null ) { throw new IllegalArgumentException( "Class members cannot be null" ); } String name = jField.getName(); if ( _fields.get( name ) != null ) { String err = "duplicate name found: " + name; throw new IllegalArgumentException( err ); } _fields.put( name, jField ); } //-- addField public void addMember( JMember jMember ) throws IllegalArgumentException { if ( jMember instanceof JField ) addField( (JField) jMember ); else if ( jMember instanceof JMethod ) addMethod( (JMethod) jMember ); else { String error = null; if ( jMember == null ) { error = "the argument 'jMember' must not be null."; } else { error = "Cannot add JMember '" + jMember.getClass().getName() + "' to JClass, unrecognized type."; } throw new IllegalArgumentException( error ); } } //-- addMember public void addMethod( JMethod jMethod ) { addMethod( jMethod, true ); } public void addMethod( JMethod jMethod, boolean importReturnType ) throws IllegalArgumentException { if ( jMethod == null ) { throw new IllegalArgumentException( "Class methods cannot be null" ); } //-- check method name and signatures *add later* //-- keep method list sorted for esthetics when printing //-- START SORT :-) boolean added = false; // short modifierVal = 0; JModifiers modifiers = jMethod.getModifiers(); if ( modifiers.isAbstract() ) { getModifiers().setAbstract( true ); } for ( int i = 0; i < _methods.size(); i++ ) { JMethod tmp = (JMethod) _methods.elementAt( i ); //-- first compare modifiers if ( tmp.getModifiers().isPrivate() ) { if ( !modifiers.isPrivate() ) { _methods.insertElementAt( jMethod, i ); added = true; break; } } //-- compare names if ( jMethod.getName().compareTo( tmp.getName() ) < 0 ) { _methods.insertElementAt( jMethod, i ); added = true; break; } } //-- END SORT if ( !added ) _methods.addElement( jMethod ); } //-- addMethod public void addMethods( JMethod[] jMethods ) throws IllegalArgumentException { for ( int i = 0; i < jMethods.length; i++ ) addMethod( jMethods[i] ); } //-- addMethods /** * Creates a new JConstructor and adds it to this * JClass. * * @return the newly created constructor */ public JConstructor createConstructor() { return createConstructor( null ); } //-- createConstructor /** * Creates a new JConstructor and adds it to this * JClass. * * @return the newly created constructor */ public JConstructor createConstructor( JParameter[] params ) { JConstructor cons = new JConstructor( this ); if ( params != null ) { for ( int i = 0; i < params.length; i++ ) cons.addParameter( params[i] ); } addConstructor( cons ); return cons; } //-- createConstructor /** * Creates and returns an inner-class for this JClass * * @param localname the name of the class (no package name) * @return the new JClass */ public JClass createInnerClass( String localname ) { if ( localname == null ) { String err = "argument 'localname' must not be null."; throw new IllegalArgumentException( err ); } if ( localname.indexOf( '.' ) >= 0 ) { String err = "The name of an inner-class must not contain a package name."; throw new IllegalArgumentException( err ); } String classname = getPackageName(); if ( classname != null ) { classname = classname + "." + localname; } else { classname = localname; } JClass innerClass = new JInnerClass( classname ); _innerClasses.addElement( innerClass ); return innerClass; } //-- createInnerClass /** * Returns the constructor at the specified index. * * @param index the index of the constructor to return * @return the JConstructor at the specified index. */ public JConstructor getConstructor( int index ) { return (JConstructor) _constructors.elementAt( index ); } //-- getConstructor /** * Returns the an array of the JConstructors contained within this JClass * * @return an array of JConstructor */ public JConstructor[] getConstructors() { int size = _constructors.size(); JConstructor[] jcArray = new JConstructor[size]; for ( int i = 0; i < _constructors.size(); i++ ) { jcArray[i] = (JConstructor) _constructors.elementAt( i ); } return jcArray; } //-- getConstructors /** * Returns the member with the given name, or null if no member * was found with the given name * @param name the name of the member to return * @return the member with the given name, or null if no member * was found with the given name **/ public JField getField( String name ) { return (JField) _fields.get( name ); } //-- getField /** * Returns an array of all the JFields of this JClass * @return an array of all the JFields of this JClass **/ public JField[] getFields() { int size = _fields.size(); JField[] farray = new JField[size]; for ( int i = 0; i < size; i++ ) { farray[i] = (JField) _fields.get( i ); } return farray; } //-- getFields /** * Returns an array of JClass (the inner classes) * contained within this JClass. * * @return an array of JClass contained within this JClass */ public JClass[] getInnerClasses() { int size = _innerClasses.size(); JClass[] carray = new JClass[size]; _innerClasses.copyInto( carray ); return carray; } //-- getInnerClasses; /** * Returns an array of all the JMethods of this JClass * * @return an array of all the JMethods of this JClass */ public JMethod[] getMethods() { int size = _methods.size(); JMethod[] marray = new JMethod[size]; for ( int i = 0; i < _methods.size(); i++ ) { marray[i] = (JMethod) _methods.elementAt( i ); } return marray; } //-- getMethods /** * Returns the first occurance of the method with the * given name, starting from the specified index. * * @param name the name of the method to look for * @param startIndex the starting index to begin the search * @return the method if found, otherwise null. */ public JMethod getMethod( String name, int startIndex ) { for ( int i = startIndex; i < _methods.size(); i++ ) { JMethod jMethod = (JMethod) _methods.elementAt( i ); if ( jMethod.getName().equals( name ) ) return jMethod; } return null; } //-- getMethod /** * Returns the JMethod located at the specified index * * @param index the index of the JMethod to return. * @return the JMethod */ public JMethod getMethod( int index ) { return (JMethod) _methods.elementAt( index ); } //-- getMethod /** * Returns the JSourceCode for the static initializer * of this JClass * * @return the JSourceCode for the static initializer * of this JClass */ public JSourceCode getStaticInitializationCode() { return _staticInitializer; } //-- getStaticInitializationCode /** * Gets the super Class that this class extends * @return superClass the super Class that this Class extends */ public String getSuperClass() { return _superClass; } //-- getSuperClass /** * Prints the source code for this JClass to the given JSourceWriter * * @param jsw the JSourceWriter to print to. [May not be null] */ public void print( JSourceWriter jsw ) { print( jsw, false ); } //-- print /** * Prints the source code for this JClass to the given JSourceWriter * * @param jsw the JSourceWriter to print to. [May not be null] */ public void print( JSourceWriter jsw, boolean classOnly ) { if ( jsw == null ) { throw new IllegalArgumentException( "argument 'jsw' should not be null." ); } StringBuffer buffer = new StringBuffer(); if ( !classOnly ) { printHeader( jsw ); printPackageDeclaration( jsw ); //-- get imports from inner-classes Vector removeImports = null; if ( _innerClasses.size() > 0 ) { removeImports = new Vector(); for ( int i = 0; i < _innerClasses.size(); i++ ) { JClass iClass = (JClass) _innerClasses.elementAt( i ); Enumeration e = iClass.getImports(); while ( e.hasMoreElements() ) { String classname = (String) e.nextElement(); if ( !hasImport( classname ) ) { addImport( classname ); removeImports.addElement( classname ); } } } } printImportDeclarations( jsw ); //-- remove imports from inner-classes, if necessary if ( removeImports != null ) { for ( int i = 0; i < removeImports.size(); i++ ) { removeImport( (String) removeImports.elementAt( i ) ); } } } //- Java Doc -/ getJDocComment().print( jsw ); //-- print class information //-- we need to add some JavaDoc API adding comments buffer.setLength( 0 ); JModifiers modifiers = getModifiers(); if ( modifiers.isPrivate() ) { buffer.append( "private " ); } else if ( modifiers.isPublic() ) { buffer.append( "public " ); } if ( modifiers.isAbstract() ) { buffer.append( "abstract " ); } buffer.append( "class " ); buffer.append( getLocalName() ); jsw.writeln( buffer.toString() ); buffer.setLength( 0 ); jsw.indent(); if ( _superClass != null ) { buffer.append( "extends " ); buffer.append( _superClass ); jsw.writeln( buffer.toString() ); buffer.setLength( 0 ); } if ( getInterfaceCount() > 0 ) { buffer.append( "implements " ); Enumeration e = getInterfaces(); while ( e.hasMoreElements() ) { buffer.append( e.nextElement() ); if ( e.hasMoreElements() ) buffer.append( ", " ); } jsw.writeln( buffer.toString() ); buffer.setLength( 0 ); } jsw.unindent(); jsw.writeln( '{' ); jsw.indent(); //-- declare members if ( _fields.size() > 0 ) { jsw.writeln(); jsw.writeln( " jsw.writeln( " //- Class/Member Variables -/" ); jsw.writeln( " jsw.writeln(); } for ( int i = 0; i < _fields.size(); i++ ) { JField jField = (JField) _fields.get( i ); //-- print Java comment JDocComment comment = jField.getComment(); if ( comment != null ) comment.print( jsw ); // -- print member jsw.write( jField.getModifiers().toString() ); jsw.write( ' ' ); JType type = jField.getType(); String typeName = type.toString(); //-- for esthetics use short name in some cases if ( typeName.equals( toString() ) ) { typeName = type.getLocalName(); } jsw.write( typeName ); jsw.write( ' ' ); jsw.write( jField.getName() ); String init = jField.getInitString(); if ( init != null ) { jsw.write( " = " ); jsw.write( init ); } jsw.writeln( ';' ); jsw.writeln(); } //- Static Initializer -/ if ( !_staticInitializer.isEmpty() ) { jsw.writeln(); jsw.writeln( "static" ); jsw.writeln( "{" ); jsw.writeln( _staticInitializer.toString() ); jsw.writeln( "};" ); jsw.writeln(); } //-- print constructors if ( _constructors.size() > 0 ) { jsw.writeln(); jsw.writeln( " jsw.writeln( " //- Constructors -/" ); jsw.writeln( " jsw.writeln(); } for ( int i = 0; i < _constructors.size(); i++ ) { JConstructor jConstructor = (JConstructor) _constructors.elementAt( i ); jConstructor.print( jsw ); jsw.writeln(); } //-- print methods if ( _methods.size() > 0 ) { jsw.writeln(); jsw.writeln( " jsw.writeln( " //- Methods -/" ); jsw.writeln( " jsw.writeln(); } for ( int i = 0; i < _methods.size(); i++ ) { JMethod jMethod = (JMethod) _methods.elementAt( i ); jMethod.print( jsw ); jsw.writeln(); } //-- print inner-classes if ( _innerClasses.size() > 0 ) { jsw.writeln(); jsw.writeln( " jsw.writeln( " //- Inner Classes -/" ); jsw.writeln( " jsw.writeln(); } for ( int i = 0; i < _innerClasses.size(); i++ ) { JClass jClass = (JClass) _innerClasses.elementAt( i ); jClass.print( jsw, true ); jsw.writeln(); } jsw.unindent(); for ( Iterator iterator = sourceCodeEntries.iterator(); iterator.hasNext(); ) { jsw.write( (String) iterator.next() ); } jsw.writeln(); jsw.unindent(); jsw.writeln( '}' ); jsw.flush(); } //-- printSource private List sourceCodeEntries = new ArrayList(); public void addSourceCode( String sourceCode ) { sourceCodeEntries.add( sourceCode ); } /** * Removes the given constructor from this JClass * * @param constructor the JConstructor to remove * @return true if the constructor was removed, otherwise false. */ public boolean removeConstructor( JConstructor constructor ) { return _constructors.removeElement( constructor ); } //-- removeConstructor /** * Removes the field with the given name from this JClass * * @param name the name of the field to remove **/ public JField removeField( String name ) { if ( name == null ) return null; JField field = (JField) _fields.remove( name ); //-- clean up imports //-- NOT YET IMPLEMENTED return field; } //-- removeField /** * Removes the given JField from this JClass * * @param jField, the JField to remove **/ public boolean removeField( JField jField ) { if ( jField == null ) return false; Object field = _fields.get( jField.getName() ); if ( field == jField ) { _fields.remove( jField.getName() ); return true; } //-- clean up imports //-- NOT YET IMPLEMENTED return false; } //-- removeField /** * Removes the given inner-class (JClass) from this JClass. * * @param jClass the JClass (inner-class) to remove. * @return true if the JClass was removed, otherwise false. */ public boolean removeInnerClass( JClass jClass ) { return _innerClasses.removeElement( jClass ); } //-- removeInnerClass /** * Sets the super Class that this class extends * @param superClass the super Class that this Class extends */ public void setSuperClass( String superClass ) { _superClass = superClass; } //-- setSuperClass /** * Test drive method...to be removed or commented out **/ public static void main( String[] args ) { JClass testClass = new JClass( "org.acme.Test" ); testClass.addImport( "java.util.Vector" ); testClass.addMember( new JField( JType.Int, "x" ) ); JClass jcString = new JClass( "String" ); JField field = null; field = new JField( JType.Int, "_z" ); field.getModifiers().setStatic( true ); testClass.addField( field ); testClass.getStaticInitializationCode().add( "_z = 75;" ); field = new JField( jcString, "myString" ); field.getModifiers().makePrivate(); testClass.addMember( field ); //-- create constructor JConstructor cons = testClass.createConstructor(); cons.getSourceCode().add( "this.x = 6;" ); JMethod jMethod = new JMethod( JType.Int, "getX" ); jMethod.setSourceCode( "return this.x;" ); testClass.addMethod( jMethod ); //-- create inner-class JClass innerClass = testClass.createInnerClass( "Foo" ); innerClass.addImport( "java.util.Hashtable" ); innerClass.addMember( new JField( JType.Int, "_type" ) ); field = new JField( jcString, "_name" ); field.getModifiers().makePrivate(); innerClass.addMember( field ); //-- create constructor cons = innerClass.createConstructor(); cons.getSourceCode().add( "_name = \"foo\";" ); jMethod = new JMethod( jcString, "getName" ); jMethod.setSourceCode( "return _name;" ); innerClass.addMethod( jMethod ); testClass.print(); } //-- main final class JInnerClass extends JClass { JInnerClass( String name ) { super( name ); } /** * Allows changing the package name of this JStructure * * @param packageName the package name to use */ public void setPackageName( String packageName ) { throw new IllegalStateException( "Cannot change the package of an inner-class" ); } //-- setPackageName } //-- JInnerClass } //-- JClass
package org.caleydo.view.pathway; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Set; import javax.media.opengl.GL2; import org.caleydo.core.data.IUniqueObject; import org.caleydo.core.data.collection.dimension.DataRepresentation; import org.caleydo.core.data.container.Average; import org.caleydo.core.data.container.ContainerStatistics; import org.caleydo.core.data.mapping.IDMappingManager; import org.caleydo.core.data.selection.EventBasedSelectionManager; import org.caleydo.core.data.selection.SelectionManager; import org.caleydo.core.data.selection.SelectionType; import org.caleydo.core.data.virtualarray.DimensionVirtualArray; import org.caleydo.core.data.virtualarray.RecordVirtualArray; import org.caleydo.core.data.virtualarray.VirtualArray; import org.caleydo.core.manager.GeneralManager; import org.caleydo.core.util.collection.Pair; import org.caleydo.core.util.mapping.color.ColorMapper; import org.caleydo.core.view.opengl.camera.ViewFrustum; import org.caleydo.core.view.opengl.canvas.EDetailLevel; import org.caleydo.core.view.opengl.picking.PickingType; import org.caleydo.datadomain.genetic.GeneticDataDomain; import org.caleydo.datadomain.pathway.graph.PathwayGraph; import org.caleydo.datadomain.pathway.graph.item.edge.PathwayRelationEdgeRep; import org.caleydo.datadomain.pathway.graph.item.vertex.EPathwayVertexShape; import org.caleydo.datadomain.pathway.graph.item.vertex.EPathwayVertexType; import org.caleydo.datadomain.pathway.graph.item.vertex.PathwayVertex; import org.caleydo.datadomain.pathway.graph.item.vertex.PathwayVertexRep; import org.caleydo.datadomain.pathway.manager.PathwayItemManager; /** * OpenGL2 pathway manager. * * @author Marc Streit */ public class GLPathwayContentCreator { private GeneralManager generalManager; private static final float Z_OFFSET = 0.01f; private GLPathway glPathwayView; private int enzymeNodeDisplayListId = -1; private int compoundNodeDisplayListId = -1; private int framedEnzymeNodeDisplayListId = -1; private int framedCompoundNodeDisplayListId = -1; private int upscaledFilledEnzymeNodeDisplayListId = -1; private int upscaledFramedEnzymeNodeDisplayListID = -1; private boolean enableEdgeRendering = false; private boolean enableGeneMapping = true; private HashMap<PathwayGraph, Integer> hashPathway2VerticesDisplayListId; private HashMap<PathwayGraph, Integer> hashPathway2EdgesDisplayListId; private ColorMapper colorMapper; private SelectionManager internalSelectionManager; private ArrayList<Integer> selectedEdgeRepId; private IDMappingManager idMappingManager; private PathwayItemManager pathwayItemManager; private GeneticDataDomain geneticDataDomain; private DataRepresentation dimensionDataRepresentation = DataRepresentation.NORMALIZED; /** * Constructor. */ public GLPathwayContentCreator(ViewFrustum viewFrustum, GLPathway glPathwayView) { this.generalManager = GeneralManager.get(); this.glPathwayView = glPathwayView; idMappingManager = glPathwayView.getPathwayDataDomain().getGeneIDMappingManager(); colorMapper = glPathwayView.getDataDomain().getColorMapper(); hashPathway2VerticesDisplayListId = new HashMap<PathwayGraph, Integer>(); hashPathway2EdgesDisplayListId = new HashMap<PathwayGraph, Integer>(); selectedEdgeRepId = new ArrayList<Integer>(); pathwayItemManager = PathwayItemManager.get(); geneticDataDomain = (GeneticDataDomain) glPathwayView.getDataDomain(); } public void init(final GL2 gl, SelectionManager geneSelectionManager) { buildEnzymeNodeDisplayList(gl); buildCompoundNodeDisplayList(gl); buildFramedEnzymeNodeDisplayList(gl); buildFramedCompoundNodeDisplayList(gl); buildUpscaledEnzymeNodeDisplayList(gl); buildUpscaledFramedEnzymeNodeDisplayList(gl); this.internalSelectionManager = geneSelectionManager; } public void buildPathwayDisplayList(final GL2 gl, final IUniqueObject containingView, final PathwayGraph pathway) { if (pathway == null) return; int iVerticesDisplayListId = -1; int edgesDisplayListId = -1; if (hashPathway2VerticesDisplayListId.containsKey(pathway)) { // Replace current display list if a display list exists iVerticesDisplayListId = hashPathway2VerticesDisplayListId.get(pathway); } else { // Creating vertex display list for pathways iVerticesDisplayListId = gl.glGenLists(1); hashPathway2VerticesDisplayListId.put(pathway, iVerticesDisplayListId); } gl.glNewList(iVerticesDisplayListId, GL2.GL_COMPILE); extractVertices(gl, containingView, pathway); gl.glEndList(); if (hashPathway2EdgesDisplayListId.containsKey(pathway)) { // Replace current display list if a display list exists edgesDisplayListId = hashPathway2EdgesDisplayListId.get(pathway); } else { // Creating edge display list for pathways edgesDisplayListId = gl.glGenLists(1); hashPathway2EdgesDisplayListId.put(pathway, edgesDisplayListId); } gl.glNewList(edgesDisplayListId, GL2.GL_COMPILE); extractEdges(gl, pathway); gl.glEndList(); } public void performIdenticalNodeHighlighting(SelectionType selectionType) { if (internalSelectionManager == null) return; selectedEdgeRepId.clear(); ArrayList<Integer> iAlTmpSelectedGraphItemIds = new ArrayList<Integer>(); Set<Integer> tmpItemIDs; tmpItemIDs = internalSelectionManager.getElements(selectionType); if (tmpItemIDs != null) { iAlTmpSelectedGraphItemIds.addAll(tmpItemIDs); } if (iAlTmpSelectedGraphItemIds.size() == 0) return; // Copy selection IDs to array list object for (Integer graphItemID : iAlTmpSelectedGraphItemIds) { for (PathwayVertex vertex : pathwayItemManager.getPathwayVertexRep(graphItemID) .getPathwayVertices()) { for (PathwayVertexRep vertexRep : vertex.getPathwayVertexReps()) { if (tmpItemIDs.contains(vertexRep.getID())) { continue; } internalSelectionManager.addToType(selectionType, vertexRep.getID()); } } } } private void buildEnzymeNodeDisplayList(final GL2 gl) { enzymeNodeDisplayListId = gl.glGenLists(1); float nodeWidth = PathwayRenderStyle.ENZYME_NODE_WIDTH; float nodeHeight = PathwayRenderStyle.ENZYME_NODE_HEIGHT; gl.glNewList(enzymeNodeDisplayListId, GL2.GL_COMPILE); fillNodeDisplayList(gl, nodeWidth + 0.002f, nodeHeight); gl.glEndList(); } private void buildUpscaledEnzymeNodeDisplayList(final GL2 gl) { upscaledFilledEnzymeNodeDisplayListId = gl.glGenLists(1); float nodeWidth = PathwayRenderStyle.ENZYME_NODE_WIDTH; float nodeHeight = PathwayRenderStyle.ENZYME_NODE_HEIGHT; float scaleFactor = 3; nodeWidth *= scaleFactor; nodeHeight *= scaleFactor; gl.glNewList(upscaledFilledEnzymeNodeDisplayListId, GL2.GL_COMPILE); fillNodeDisplayList(gl, nodeWidth, nodeHeight); gl.glEndList(); } protected void buildUpscaledFramedEnzymeNodeDisplayList(final GL2 gl) { upscaledFramedEnzymeNodeDisplayListID = gl.glGenLists(1); float fNodeWidth = PathwayRenderStyle.ENZYME_NODE_WIDTH; float fNodeHeight = PathwayRenderStyle.ENZYME_NODE_HEIGHT; float scaleFactor = 1.4f; fNodeWidth *= scaleFactor; fNodeHeight *= scaleFactor; gl.glNewList(upscaledFramedEnzymeNodeDisplayListID, GL2.GL_COMPILE); fillNodeDisplayListFrame(gl, fNodeWidth, fNodeHeight); gl.glEndList(); } protected void buildFramedEnzymeNodeDisplayList(final GL2 gl) { framedEnzymeNodeDisplayListId = gl.glGenLists(1); float fNodeWidth = PathwayRenderStyle.ENZYME_NODE_WIDTH; float fNodeHeight = PathwayRenderStyle.ENZYME_NODE_HEIGHT; gl.glNewList(framedEnzymeNodeDisplayListId, GL2.GL_COMPILE); fillNodeDisplayListFrame(gl, fNodeWidth + 0.02f, fNodeHeight); gl.glEndList(); } protected void buildCompoundNodeDisplayList(final GL2 gl) { // Creating display list for node cube objects compoundNodeDisplayListId = gl.glGenLists(1); float nodeWidth = PathwayRenderStyle.COMPOUND_NODE_WIDTH; float nodeHeight = PathwayRenderStyle.COMPOUND_NODE_HEIGHT; gl.glNewList(compoundNodeDisplayListId, GL2.GL_COMPILE); fillNodeDisplayList(gl, nodeWidth, nodeHeight); gl.glEndList(); } protected void buildFramedCompoundNodeDisplayList(final GL2 gl) { // Creating display list for node cube objects framedCompoundNodeDisplayListId = gl.glGenLists(1); float nodeWidth = PathwayRenderStyle.COMPOUND_NODE_WIDTH; float nodeHeight = PathwayRenderStyle.COMPOUND_NODE_HEIGHT; gl.glNewList(framedCompoundNodeDisplayListId, GL2.GL_COMPILE); fillNodeDisplayListFrame(gl, nodeWidth, nodeHeight); gl.glEndList(); } private void fillNodeDisplayList(final GL2 gl, float nodeWidth, float nodeHeight) { gl.glBegin(GL2.GL_QUADS); gl.glNormal3f(0.0f, 0.0f, 1.0f); gl.glVertex3f(0, 0, Z_OFFSET); gl.glVertex3f(nodeWidth, 0, Z_OFFSET); gl.glVertex3f(nodeWidth, -nodeHeight, Z_OFFSET); gl.glVertex3f(0, -nodeHeight, Z_OFFSET); gl.glEnd(); } protected void fillNodeDisplayListFrame(final GL2 gl, float nodeWidth, float nodeHeight) { gl.glLineWidth(3); gl.glBegin(GL2.GL_LINE_LOOP); gl.glVertex3f(0, 0, Z_OFFSET + 0.03f); gl.glVertex3f(nodeWidth, 0, Z_OFFSET + 0.03f); gl.glVertex3f(nodeWidth, -nodeHeight, Z_OFFSET + 0.03f); gl.glVertex3f(0, -nodeHeight, Z_OFFSET + 0.03f); gl.glEnd(); } private void extractVertices(final GL2 gl, final IUniqueObject containingView, PathwayGraph pathwayToExtract) { for (PathwayVertexRep vertexRep : pathwayToExtract.vertexSet()) { if (vertexRep == null) { continue; } createVertex(gl, containingView, vertexRep, pathwayToExtract); } } private void extractEdges(final GL2 gl, PathwayGraph pathwayToExtract) { // while (pathwayToExtract.edgeSet()) { // edgeRep = edgeIterator.next(); // if (edgeRep != null) { // if (enableEdgeRendering) { // createEdge(gl, edgeRep, pathwayToExtract); // // Render edge if it is contained in the minimum spanning tree // // of the neighborhoods // else if (selectedEdgeRepId.contains(edgeRep.getID())) { // createEdge(gl, edgeRep, pathwayToExtract); } private void createVertex(final GL2 gl, final IUniqueObject containingView, PathwayVertexRep vertexRep, PathwayGraph containingPathway) { float[] tmpNodeColor = null; gl.glPushName(generalManager .getViewManager() .getPickingManager() .getPickingID(containingView.getID(), PickingType.PATHWAY_ELEMENT_SELECTION.name(), vertexRep.getID())); EPathwayVertexShape shape = vertexRep.getShapeType(); if (shape.equals(EPathwayVertexShape.poly)) renderPolyVertex(gl, vertexRep); float canvasXPos = vertexRep.getCenterX() * PathwayRenderStyle.SCALING_FACTOR_X; float canvasYPos = vertexRep.getCenterY() * PathwayRenderStyle.SCALING_FACTOR_Y; float nodeWidth = vertexRep.getWidth() * PathwayRenderStyle.SCALING_FACTOR_X; float nodeHeight = vertexRep.getHeight() * PathwayRenderStyle.SCALING_FACTOR_Y; gl.glTranslatef(canvasXPos, -canvasYPos, 0); EPathwayVertexType vertexType = vertexRep.getType(); switch (vertexType) { // Pathway link case map: // Ignore KEGG title node if (vertexRep.getName().contains("TITLE")) { gl.glTranslatef(-canvasXPos, canvasYPos, 0); gl.glPopName(); return; } tmpNodeColor = new float[] { 0f, 0f, 0f, 0.25f }; gl.glColor4fv(tmpNodeColor, 0); fillNodeDisplayList(gl, nodeWidth, nodeHeight); // Handle selection highlighting of element if (internalSelectionManager.checkStatus(SelectionType.SELECTION, vertexRep.getID())) { tmpNodeColor = SelectionType.SELECTION.getColor(); gl.glColor4fv(tmpNodeColor, 0); fillNodeDisplayListFrame(gl, nodeWidth, nodeHeight); } else if (internalSelectionManager.checkStatus(SelectionType.MOUSE_OVER, vertexRep.getID())) { tmpNodeColor = SelectionType.MOUSE_OVER.getColor(); gl.glColor4fv(tmpNodeColor, 0); fillNodeDisplayListFrame(gl, nodeWidth, nodeHeight); } break; case compound: EventBasedSelectionManager metabolicSelectionManager = glPathwayView .getMetaboliteSelectionManager(); // Handle selection highlighting of element if (internalSelectionManager.checkStatus(SelectionType.SELECTION, vertexRep.getID()) || metabolicSelectionManager.checkStatus(SelectionType.SELECTION, vertexRep.getName().hashCode())) { tmpNodeColor = SelectionType.SELECTION.getColor(); gl.glColor4fv(tmpNodeColor, 0); gl.glCallList(framedCompoundNodeDisplayListId); } else if (internalSelectionManager.checkStatus(SelectionType.MOUSE_OVER, vertexRep.getID()) || metabolicSelectionManager.checkStatus(SelectionType.MOUSE_OVER, vertexRep.getName().hashCode())) { tmpNodeColor = SelectionType.MOUSE_OVER.getColor(); gl.glColor4fv(tmpNodeColor, 0); gl.glCallList(framedCompoundNodeDisplayListId); } tmpNodeColor = PathwayRenderStyle.COMPOUND_NODE_COLOR; gl.glColor4fv(tmpNodeColor, 0); gl.glCallList(compoundNodeDisplayListId); break; case group: // gl.glColor4f(1, 1, 0, 1); // fillNodeDisplayList(gl, nodeWidth, nodeHeight); break; case gene: case enzyme: // new kegg data assign enzymes without mapping to "undefined" // which we represent as other case other: gl.glLineWidth(1); if (enableGeneMapping) { Average average = getExpressionAverage(vertexRep); if (average != null) tmpNodeColor = colorMapper.getColor((float) average .getArithmeticMean()); if (tmpNodeColor != null) { if (glPathwayView.getDetailLevel() == EDetailLevel.HIGH) { gl.glColor4f(tmpNodeColor[0], tmpNodeColor[1], tmpNodeColor[2], 0.7f); // gl.glEnable(GL2.GL_BLEND); gl.glBlendFunc(GL2.GL_SRC_ALPHA, GL2.GL_ONE_MINUS_SRC_ALPHA); gl.glCallList(enzymeNodeDisplayListId); // gl.glEnable(GL2.GL_DEPTH_TEST); // max std dev is 0.5 -> thus we multiply it with 2 Float stdDev = PathwayRenderStyle.ENZYME_NODE_HEIGHT * (float) average.getStandardDeviation() * 5.0f; float x = PathwayRenderStyle.ENZYME_NODE_WIDTH + 0.000f; float y = -PathwayRenderStyle.ENZYME_NODE_HEIGHT + 0.002f; if (!stdDev.isNaN()) { // opaque background gl.glColor4f(1, 1, 1, 1f); gl.glBegin(GL2.GL_QUADS); gl.glVertex3f(x, y - .001f, Z_OFFSET); gl.glVertex3f(x + PathwayRenderStyle.STD_DEV_BAR_WIDTH, y - .001f, Z_OFFSET); gl.glVertex3f(x + PathwayRenderStyle.STD_DEV_BAR_WIDTH, 0 + .001f, Z_OFFSET); gl.glVertex3f(x, 0 + 0.001f, Z_OFFSET); gl.glEnd(); gl.glColor4fv(PathwayRenderStyle.STD_DEV_COLOR, 0); gl.glBegin(GL2.GL_QUADS); gl.glVertex3f(x, y, Z_OFFSET + 0.01f); gl.glVertex3f(x + PathwayRenderStyle.STD_DEV_BAR_WIDTH, y, Z_OFFSET + 0.01f); gl.glVertex3f(x + PathwayRenderStyle.STD_DEV_BAR_WIDTH, y + stdDev, Z_OFFSET + 0.01f); gl.glVertex3f(x, y + stdDev, Z_OFFSET + 0.01f); gl.glEnd(); // frame gl.glColor4f(0, 0, 0, 1f); gl.glBegin(GL2.GL_LINE_LOOP); gl.glVertex3f(x, y - .001f, Z_OFFSET + 0.02f); gl.glVertex3f(x + PathwayRenderStyle.STD_DEV_BAR_WIDTH, y - .001f, Z_OFFSET + 0.02f); gl.glVertex3f(x + PathwayRenderStyle.STD_DEV_BAR_WIDTH, 0 + .001f, Z_OFFSET + 0.02f); gl.glVertex3f(x, 0 + 0.001f, Z_OFFSET + 0.02f); gl.glEnd(); } // Handle selection highlighting of element if (internalSelectionManager.checkStatus(SelectionType.SELECTION, vertexRep.getID())) { tmpNodeColor = SelectionType.SELECTION.getColor(); gl.glColor4fv(tmpNodeColor, 0); gl.glCallList(framedEnzymeNodeDisplayListId); } else if (internalSelectionManager.checkStatus( SelectionType.MOUSE_OVER, vertexRep.getID())) { tmpNodeColor = SelectionType.MOUSE_OVER.getColor(); gl.glColor4fv(tmpNodeColor, 0); gl.glCallList(framedEnzymeNodeDisplayListId); } } else { // Upscaled version of pathway node needed for e.g. // VisBricks gl.glCallList(upscaledFilledEnzymeNodeDisplayListId); // Handle selection highlighting of element if (internalSelectionManager.checkStatus(SelectionType.SELECTION, vertexRep.getID())) { tmpNodeColor = SelectionType.SELECTION.getColor(); gl.glColor4fv(tmpNodeColor, 0); gl.glCallList(upscaledFilledEnzymeNodeDisplayListId); } else if (internalSelectionManager.checkStatus( SelectionType.MOUSE_OVER, vertexRep.getID())) { tmpNodeColor = SelectionType.MOUSE_OVER.getColor(); gl.glColor4fv(tmpNodeColor, 0); gl.glCallList(upscaledFilledEnzymeNodeDisplayListId); } } } else { // render a black glyph in the corder of the // rectangle in order to indicate that we either do // not have mapping or data // transparent node for picking gl.glColor4f(0, 0, 0, 0); gl.glCallList(enzymeNodeDisplayListId); tmpNodeColor = PathwayRenderStyle.ENZYME_NODE_COLOR; gl.glColor4f(tmpNodeColor[0], tmpNodeColor[1], tmpNodeColor[2], 0.7f); gl.glCallList(compoundNodeDisplayListId); // Handle selection highlighting of element if (internalSelectionManager.checkStatus(SelectionType.SELECTION, vertexRep.getID())) { tmpNodeColor = SelectionType.SELECTION.getColor(); gl.glColor4fv(tmpNodeColor, 0); gl.glCallList(framedEnzymeNodeDisplayListId); } else if (internalSelectionManager.checkStatus( SelectionType.MOUSE_OVER, vertexRep.getID())) { tmpNodeColor = SelectionType.MOUSE_OVER.getColor(); gl.glColor4fv(tmpNodeColor, 0); gl.glCallList(framedEnzymeNodeDisplayListId); } } } else { // Handle selection highlighting of element if (internalSelectionManager.checkStatus(SelectionType.SELECTION, vertexRep.getID())) { tmpNodeColor = SelectionType.SELECTION.getColor(); } else if (internalSelectionManager.checkStatus(SelectionType.MOUSE_OVER, vertexRep.getID())) { tmpNodeColor = SelectionType.MOUSE_OVER.getColor(); } else if (internalSelectionManager.checkStatus(SelectionType.NORMAL, vertexRep.getID())) { tmpNodeColor = PathwayRenderStyle.ENZYME_NODE_COLOR; } else { tmpNodeColor = new float[] { 0, 0, 0, 0 }; } gl.glColor4fv(tmpNodeColor, 0); gl.glCallList(framedEnzymeNodeDisplayListId); if (!internalSelectionManager.checkStatus(SelectionType.DESELECTED, vertexRep.getID())) { // Transparent node for picking gl.glColor4f(0, 0, 0, 0); gl.glCallList(enzymeNodeDisplayListId); } } break; } gl.glTranslatef(-canvasXPos, canvasYPos, 0); gl.glPopName(); } private void renderPolyVertex(GL2 gl, PathwayVertexRep vertexRep) { float[] tmpNodeColor = null; ArrayList<Pair<Short, Short>> coords = vertexRep.getCoords(); gl.glLineWidth(3); if (enableGeneMapping) { Average average = getExpressionAverage(vertexRep); tmpNodeColor = colorMapper.getColor((float) average.getArithmeticMean()); gl.glLineWidth(4); if (tmpNodeColor != null) { gl.glColor3fv(tmpNodeColor, 0); if (glPathwayView.getDetailLevel() == EDetailLevel.HIGH) { gl.glBegin(GL2.GL_LINE_STRIP); for (int pointIndex = 0; pointIndex < coords.size(); pointIndex++) { gl.glVertex3f(coords.get(pointIndex).getFirst() * PathwayRenderStyle.SCALING_FACTOR_X, -coords.get(pointIndex) .getSecond() * PathwayRenderStyle.SCALING_FACTOR_Y, Z_OFFSET); } gl.glEnd(); // Transparent node for picking gl.glColor4f(0, 0, 0, 0); gl.glBegin(GL2.GL_POLYGON); for (int pointIndex = 0; pointIndex < coords.size(); pointIndex++) { gl.glVertex3f(coords.get(pointIndex).getFirst() * PathwayRenderStyle.SCALING_FACTOR_X, -coords.get(pointIndex) .getSecond() * PathwayRenderStyle.SCALING_FACTOR_Y, Z_OFFSET); } gl.glEnd(); } else { gl.glBegin(GL2.GL_POLYGON); for (int pointIndex = 0; pointIndex < coords.size(); pointIndex++) { gl.glVertex3f(coords.get(pointIndex).getFirst() * PathwayRenderStyle.SCALING_FACTOR_X, -coords.get(pointIndex) .getSecond() * PathwayRenderStyle.SCALING_FACTOR_Y, Z_OFFSET); } gl.glEnd(); // Handle selection highlighting of element if (internalSelectionManager.checkStatus(SelectionType.SELECTION, vertexRep.getID())) { tmpNodeColor = SelectionType.SELECTION.getColor(); gl.glLineWidth(3); gl.glColor4fv(tmpNodeColor, 0); gl.glBegin(GL2.GL_LINE_STRIP); for (int pointIndex = 0; pointIndex < coords.size(); pointIndex++) { gl.glVertex3f(coords.get(pointIndex).getFirst() * PathwayRenderStyle.SCALING_FACTOR_X, -coords.get(pointIndex).getSecond() * PathwayRenderStyle.SCALING_FACTOR_Y, Z_OFFSET); } gl.glEnd(); } else if (internalSelectionManager.checkStatus(SelectionType.MOUSE_OVER, vertexRep.getID())) { tmpNodeColor = SelectionType.MOUSE_OVER.getColor(); gl.glLineWidth(3); gl.glColor4fv(tmpNodeColor, 0); gl.glBegin(GL2.GL_LINE_STRIP); for (int pointIndex = 0; pointIndex < coords.size(); pointIndex++) { gl.glVertex3f(coords.get(pointIndex).getFirst() * PathwayRenderStyle.SCALING_FACTOR_X, -coords.get(pointIndex).getSecond() * PathwayRenderStyle.SCALING_FACTOR_Y, Z_OFFSET); } gl.glEnd(); } } } } else { // Handle selection highlighting of element if (internalSelectionManager.checkStatus(SelectionType.SELECTION, vertexRep.getID())) { tmpNodeColor = SelectionType.SELECTION.getColor(); } else if (internalSelectionManager.checkStatus(SelectionType.MOUSE_OVER, vertexRep.getID())) { tmpNodeColor = SelectionType.MOUSE_OVER.getColor(); } // else if (internalSelectionManager.checkStatus( // SelectionType.NORMAL, vertexRep.getID())) { // tmpNodeColor = PathwayRenderStyle.ENZYME_NODE_COLOR; else { tmpNodeColor = PathwayRenderStyle.ENZYME_NODE_COLOR; // tmpNodeColor = new float[] { 0, 0, 0, 0 }; } gl.glColor4fv(tmpNodeColor, 0); gl.glLineWidth(3); gl.glBegin(GL2.GL_LINE_STRIP); for (int pointIndex = 0; pointIndex < coords.size(); pointIndex++) { gl.glVertex3f(coords.get(pointIndex).getFirst() * PathwayRenderStyle.SCALING_FACTOR_X, -coords.get(pointIndex) .getSecond() * PathwayRenderStyle.SCALING_FACTOR_Y, Z_OFFSET); } gl.glEnd(); if (!internalSelectionManager.checkStatus(SelectionType.DESELECTED, vertexRep.getID())) { // Transparent node for picking gl.glColor4f(0, 0, 0, 0); gl.glBegin(GL2.GL_POLYGON); for (int pointIndex = 0; pointIndex < coords.size(); pointIndex++) { gl.glVertex3f(coords.get(pointIndex).getFirst() * PathwayRenderStyle.SCALING_FACTOR_X, -coords.get(pointIndex) .getSecond() * PathwayRenderStyle.SCALING_FACTOR_Y, Z_OFFSET); } gl.glEnd(); } } } private void createEdge(final GL2 gl, PathwayRelationEdgeRep edgeRep, PathwayGraph containingPathway) { // List<IGraphItem> listGraphItemsIn = edgeRep // .getAllItemsByProp(EGraphItemProperty.INCOMING); // List<IGraphItem> listGraphItemsOut = edgeRep // .getAllItemsByProp(EGraphItemProperty.OUTGOING); // if (listGraphItemsIn.isEmpty() || listGraphItemsOut.isEmpty()) // return; // float[] tmpColor; // float fReactionLineOffset = 0; // // Check if edge is a reaction // if (edgeRep instanceof PathwayReactionEdgeGraphItemRep) { // tmpColor = PathwayRenderStyle.REACTION_EDGE_COLOR; // fReactionLineOffset = 0.01f; // // Check if edge is a relation // else if (edgeRep instanceof PathwayRelationEdgeGraphItemRep) { // tmpColor = PathwayRenderStyle.RELATION_EDGE_COLOR; // } else { // tmpColor = new float[] { 0, 0, 0, 0 }; // gl.glLineWidth(4); // gl.glColor4fv(tmpColor, 0); // gl.glBegin(GL2.GL_LINES); // Iterator<IGraphItem> iterSourceGraphItem = // listGraphItemsIn.iterator(); // Iterator<IGraphItem> iterTargetGraphItem = // listGraphItemsOut.iterator(); // PathwayVertexGraphItemRep tmpSourceGraphItem; // PathwayVertexGraphItemRep tmpTargetGraphItem; // while (iterSourceGraphItem.hasNext()) { // tmpSourceGraphItem = (PathwayVertexGraphItemRep) // iterSourceGraphItem.next(); // while (iterTargetGraphItem.hasNext()) { // tmpTargetGraphItem = (PathwayVertexGraphItemRep) iterTargetGraphItem // .next(); // gl.glVertex3f(tmpSourceGraphItem.getXOrigin() // * PathwayRenderStyle.SCALING_FACTOR_X + fReactionLineOffset, // -tmpSourceGraphItem.getYOrigin() // * PathwayRenderStyle.SCALING_FACTOR_Y // + fReactionLineOffset, 0.02f); // gl.glVertex3f(tmpTargetGraphItem.getXOrigin() // * PathwayRenderStyle.SCALING_FACTOR_X + fReactionLineOffset, // -tmpTargetGraphItem.getYOrigin() // * PathwayRenderStyle.SCALING_FACTOR_Y // + fReactionLineOffset, 0.02f); // gl.glEnd(); } public void renderPathway(final GL2 gl, final PathwayGraph pathway, boolean bRenderLabels) { if (enableEdgeRendering || !selectedEdgeRepId.isEmpty()) { int tmpEdgesDisplayListID = hashPathway2EdgesDisplayListId.get(pathway); gl.glCallList(tmpEdgesDisplayListID); } Integer tmpVerticesDisplayListID = hashPathway2VerticesDisplayListId.get(pathway); if (tmpVerticesDisplayListID != null) { gl.glCallList(tmpVerticesDisplayListID); // if (bRenderLabels && bEnableAnnotation) // renderLabels(gl, iPathwayID); } } private Average getExpressionAverage(PathwayVertexRep vertexRep) { int davidID = pathwayItemManager.getDavidIdByPathwayVertex((PathwayVertex) vertexRep .getPathwayVertices().get(0)); if (davidID == -1 || davidID == 0) return null; else { Set<Integer> selectedSamples = glPathwayView.getSampleSelectionManager() .getElements(SelectionType.SELECTION); List<Integer> selectedSamplesArray = new ArrayList<Integer>(); selectedSamplesArray.addAll(selectedSamples); // if no sample is currently selected, we add all samples for // calculating the average if (selectedSamplesArray.size() == 0) { if (!geneticDataDomain.isGeneRecord()) selectedSamplesArray.addAll(glPathwayView.getDataContainer() .getRecordPerspective().getVirtualArray().getIDs()); else selectedSamplesArray.addAll(glPathwayView.getDataContainer() .getDimensionPerspective().getVirtualArray().getIDs()); } VirtualArray<?, ?, ?> selectedSamplesVA; if (!geneticDataDomain.isGeneRecord()) selectedSamplesVA = new RecordVirtualArray(glPathwayView .getSampleSelectionManager().getIDType(), selectedSamplesArray); else selectedSamplesVA = new DimensionVirtualArray(glPathwayView .getSampleSelectionManager().getIDType(), selectedSamplesArray); Set<Integer> expressionIndices = idMappingManager.<Integer, Integer> getIDAsSet( glPathwayView.getPathwayDataDomain().getDavidIDType(), glPathwayView .getGeneSelectionManager().getIDType(), davidID); if (expressionIndices == null) return null; // FIXME multi mappings not properly handled - only the first is // taken for (Integer expressionIndex : expressionIndices) { Average average = ContainerStatistics.calculateAverage(selectedSamplesVA, geneticDataDomain.getTable(), expressionIndex); return average; } } return null; } public void enableEdgeRendering(final boolean bEnableEdgeRendering) { this.enableEdgeRendering = bEnableEdgeRendering; } public void enableGeneMapping(final boolean bEnableGeneMappging) { this.enableGeneMapping = bEnableGeneMappging; } public void enableNeighborhood(final boolean bEnableNeighborhood) { } public void switchDataRepresentation() { if (dimensionDataRepresentation.equals(DataRepresentation.NORMALIZED)) { if (!geneticDataDomain.getTable().containsFoldChangeRepresentation()) geneticDataDomain.getTable().createFoldChangeRepresentation(); dimensionDataRepresentation = DataRepresentation.FOLD_CHANGE_NORMALIZED; } else dimensionDataRepresentation = DataRepresentation.NORMALIZED; } }
package org.eclipse.mylar.internal.tasks.ui; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.List; import org.eclipse.core.runtime.jobs.IJobChangeEvent; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.core.runtime.jobs.JobChangeAdapter; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.mylar.context.core.MylarStatusHandler; import org.eclipse.mylar.internal.tasks.ui.editors.CategoryEditorInput; import org.eclipse.mylar.internal.tasks.ui.editors.MylarTaskEditor; import org.eclipse.mylar.internal.tasks.ui.editors.TaskEditorInput; import org.eclipse.mylar.internal.tasks.ui.views.TaskRepositoriesView; import org.eclipse.mylar.tasks.core.AbstractQueryHit; import org.eclipse.mylar.tasks.core.AbstractRepositoryQuery; import org.eclipse.mylar.tasks.core.AbstractRepositoryTask; import org.eclipse.mylar.tasks.core.AbstractTaskContainer; import org.eclipse.mylar.tasks.core.DateRangeActivityDelegate; import org.eclipse.mylar.tasks.core.ITask; import org.eclipse.mylar.tasks.core.ITaskListElement; import org.eclipse.mylar.tasks.core.Task; import org.eclipse.mylar.tasks.core.TaskCategory; import org.eclipse.mylar.tasks.core.TaskRepository; import org.eclipse.mylar.tasks.ui.AbstractRepositoryConnector; import org.eclipse.mylar.tasks.ui.TasksUiPlugin; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IEditorReference; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.browser.IWebBrowser; import org.eclipse.ui.browser.IWorkbenchBrowserSupport; import org.eclipse.ui.internal.browser.WebBrowserPreference; import org.eclipse.ui.internal.browser.WorkbenchBrowserSupport; /** * @author Mik Kersten */ public class TaskUiUtil { /** * TODO: move */ public static Image getImageForPriority(Task.PriorityLevel priorityLevel) { if (priorityLevel == null) { return null; } switch (priorityLevel) { case P1: return TaskListImages.getImage(TaskListImages.PRIORITY_1); case P2: return TaskListImages.getImage(TaskListImages.PRIORITY_2); case P3: return TaskListImages.getImage(TaskListImages.PRIORITY_3); case P4: return TaskListImages.getImage(TaskListImages.PRIORITY_4); case P5: return TaskListImages.getImage(TaskListImages.PRIORITY_5); default: return null; } } public static void closeEditorInActivePage(ITask task) { IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); if (window == null) { return; } IWorkbenchPage page = window.getActivePage(); if (page == null) { return; } IEditorInput input = new TaskEditorInput(task, false); IEditorPart editor = page.findEditor(input); if (editor != null) { page.closeEditor(editor, false); } } /** * Either pass in a repository and id, or fullUrl, or all of them */ public static boolean openRepositoryTask(String repositoryUrl, String taskId, String fullUrl) { boolean opened = false; String handle = AbstractRepositoryTask.getHandle(repositoryUrl, taskId); ITask task = TasksUiPlugin.getTaskListManager().getTaskList().getTask(handle); if (task == null) { // search for it for (ITask currTask : TasksUiPlugin.getTaskListManager().getTaskList().getAllTasks()) { if (currTask instanceof AbstractRepositoryTask) { String currUrl = ((AbstractRepositoryTask) currTask).getUrl(); if (currUrl != null && currUrl.equals(fullUrl)) { task = currTask; break; } } } } if (task != null) { TaskUiUtil.refreshAndOpenTaskListElement(task); opened = true; } else { AbstractRepositoryConnector connector = TasksUiPlugin.getRepositoryManager().getRepositoryForTaskUrl( fullUrl); if (connector != null) { connector.openRemoteTask(repositoryUrl, taskId); opened = true; } } if (!opened) { TaskUiUtil.openUrl(fullUrl); opened = true; } return opened; } public static void refreshAndOpenTaskListElement(ITaskListElement element) { if (element instanceof ITask || element instanceof AbstractQueryHit || element instanceof DateRangeActivityDelegate) { final ITask task; if (element instanceof AbstractQueryHit) { task = ((AbstractQueryHit) element).getOrCreateCorrespondingTask(); } else if (element instanceof DateRangeActivityDelegate) { task = ((DateRangeActivityDelegate) element).getCorrespondingTask(); } else { task = (ITask) element; } if (task instanceof AbstractRepositoryTask) { final AbstractRepositoryTask repositoryTask = (AbstractRepositoryTask) task; String repositoryKind = repositoryTask.getRepositoryKind(); final AbstractRepositoryConnector connector = TasksUiPlugin.getRepositoryManager() .getRepositoryConnector(repositoryKind); TaskRepository repository = TasksUiPlugin.getRepositoryManager().getRepository(repositoryKind, repositoryTask.getRepositoryUrl()); if (repository == null || !repository.hasCredentials()) { MessageDialog.openInformation(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), TasksUiPlugin.TITLE_DIALOG, "Repository missing or does not have credentials set, verify via " + TaskRepositoriesView.NAME + "."); return; } if (connector != null) if (repositoryTask.getTaskData() != null) { TaskUiUtil.openEditor(task, false, false); connector.synchronize(repositoryTask, false, null); } else { Job refreshJob = connector.synchronize(repositoryTask, true, new JobChangeAdapter() { public void done(IJobChangeEvent event) { TaskUiUtil.openEditor(task, false); } }); if (refreshJob == null) { TaskUiUtil.openEditor(task, false); } } } else { TaskUiUtil.openEditor(task, false); } } else if (element instanceof TaskCategory) { TaskUiUtil.openEditor((AbstractTaskContainer) element); } else if (element instanceof AbstractRepositoryQuery) { AbstractRepositoryQuery query = (AbstractRepositoryQuery) element; AbstractRepositoryConnector client = TasksUiPlugin.getRepositoryManager().getRepositoryConnector( query.getRepositoryKind()); client.openEditQueryDialog(query); } } public static void openEditor(final ITask task, boolean newTask) { openEditor(task, true, newTask); } // private static void openEditorThenSync(final AbstractRepositoryConnector connector, final ITask task) { // final IEditorInput editorInput = new TaskEditorInput(task, false); // PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { // public void run() { // IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); // if(openEditor(editorInput, TaskListPreferenceConstants.TASK_EDITOR_ID, page) != null) { // connector.synchronize((AbstractRepositoryTask) task, false, null); /** * Set asyncExec false for testing purposes. */ public static void openEditor(final ITask task, boolean asyncExec, boolean newTask) { final IEditorInput editorInput = new TaskEditorInput(task, newTask); if (asyncExec) { PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { public void run() { IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); openEditor(editorInput, TaskListPreferenceConstants.TASK_EDITOR_ID, page); } }); } else { IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); openEditor(editorInput, TaskListPreferenceConstants.TASK_EDITOR_ID, page); } } public static IEditorPart openEditor(IEditorInput input, String editorId, IWorkbenchPage page) { try { return page.openEditor(input, editorId); } catch (PartInitException e) { MylarStatusHandler.fail(e, "Open for editor failed: " + input + ", id: " + editorId, true); } return null; } public static void openEditor(AbstractTaskContainer category) { final IEditorInput input = new CategoryEditorInput(category); PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { public void run() { IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); openEditor(input, TaskListPreferenceConstants.CATEGORY_EDITOR_ID, page); } }); } public static void openUrl(String url) { try { if (WebBrowserPreference.getBrowserChoice() == WebBrowserPreference.EXTERNAL) { try { IWorkbenchBrowserSupport support = PlatformUI.getWorkbench().getBrowserSupport(); support.getExternalBrowser().openURL(new URL(url)); } catch (Exception e) { MylarStatusHandler.fail(e, "could not open task url", true); } } else { IWebBrowser browser = null; int flags = 0; if (WorkbenchBrowserSupport.getInstance().isInternalWebBrowserAvailable()) { flags = WorkbenchBrowserSupport.AS_EDITOR | WorkbenchBrowserSupport.LOCATION_BAR | WorkbenchBrowserSupport.NAVIGATION_BAR; } else { flags = WorkbenchBrowserSupport.AS_EXTERNAL | WorkbenchBrowserSupport.LOCATION_BAR | WorkbenchBrowserSupport.NAVIGATION_BAR; } String title = "Browser"; browser = WorkbenchBrowserSupport.getInstance().createBrowser(flags, TasksUiPlugin.PLUGIN_ID + title, null, null); browser.openURL(new URL(url)); } } catch (PartInitException e) { MessageDialog.openError(Display.getDefault().getActiveShell(), "Browser init error", "Browser could not be initiated"); } catch (MalformedURLException e) { MessageDialog.openError(Display.getDefault().getActiveShell(), "URL not found", "URL Could not be opened"); } } public static List<MylarTaskEditor> getActiveRepositoryTaskEditors() { List<MylarTaskEditor> repositoryTaskEditors = new ArrayList<MylarTaskEditor>(); IWorkbenchWindow[] windows = PlatformUI.getWorkbench().getWorkbenchWindows(); for (IWorkbenchWindow window : windows) { IEditorReference[] editorReferences = window.getActivePage().getEditorReferences(); for (int i = 0; i < editorReferences.length; i++) { IEditorPart editor = editorReferences[i].getEditor(false); if (editor instanceof MylarTaskEditor) { MylarTaskEditor taskEditor = (MylarTaskEditor) editor; if (taskEditor.getEditorInput() instanceof TaskEditorInput) { TaskEditorInput input = (TaskEditorInput) taskEditor.getEditorInput(); if (input.getTask() instanceof AbstractRepositoryTask) { repositoryTaskEditors.add((MylarTaskEditor) editor); } } } } } return repositoryTaskEditors; } }
package org.javarosa.core.model.storage; import java.util.Vector; import javax.microedition.rms.InvalidRecordIDException; import javax.microedition.rms.RecordEnumeration; import javax.microedition.rms.RecordStoreException; import javax.microedition.rms.RecordStoreNotOpenException; import org.javarosa.core.model.FormDef; import org.javarosa.core.model.IDataReference; import org.javarosa.core.model.utils.PrototypeFactory; import org.javarosa.core.services.storage.utilities.RMSUtility; /** * The RMS persistent storage utility for FormDef * objects. * * @author Clayton Sims */ public class FormDefRMSUtility extends RMSUtility { private PrototypeFactory referenceFactory; /** * Creates a new RMS utility with the given name * @param name A unique identifier for this RMS utility */ public FormDefRMSUtility(String name) { super(name, RMSUtility.RMS_TYPE_META_DATA); } /** * @return The name to be used for this RMS Utility */ public static String getUtilityName() { return "FormDef RMS Utility"; } /** * Writes the given formdefinition to RMS * @param form The definition of the form to be written */ public void writeToRMS(FormDef form) { super.writeToRMS(form, new FormDefMetaData(form)); } /** * Writes the given block of bytes to RMS * @param ba The set of bytes to be written */ public void writeToRMS(byte[] ba) { super.writeBytesToRMS(ba, new FormDefMetaData()); } /** * Returns the size of the given record in the RMS * * @param recordId The id of the record whose size is to be returned * @return The size, in bytes, of the record with the given index */ public int getSize(int recordId) { FormDefMetaData xformMetaData = getMetaDataFromId(recordId); return xformMetaData.getSize(); } /** * Gets the name of given record in the RMS * * @param recordId The id of the record whose name is to be returned * @return The name of the record with the given index */ public String getName(int recordId) { FormDefMetaData xformMetaData = getMetaDataFromId(recordId); return xformMetaData.getName(); } /** * Gets the meta data object for the record with the given Id * * @param recordId The id of the record whose meta data is to be returned * @return The meta data of the record with the given Id */ private FormDefMetaData getMetaDataFromId(int recordId) { FormDefMetaData formMetaData = new FormDefMetaData(); this.retrieveMetaDataFromRMS(recordId, formMetaData); return formMetaData; } /** * @return a list of form names that are stored in this RMS */ public Vector getListOfFormNames() { Vector listOfNames = new Vector(); try { RecordEnumeration recordEnum = recordStore.enumerateRecords(null, null, false); while (recordEnum.hasNextElement()) { int i = recordEnum.nextRecordId(); listOfNames.addElement(this.getName(i)); } } catch (RecordStoreNotOpenException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (RecordStoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } return listOfNames; } /** * Gets a list of form names that correspond to the records present in this RMS * which have the ids given. * * @param formIDs A vector of formIds * @return A vector of strings which are the names of each record in this RMS * with an id that exists in the provided vector of ids. */ public Vector getListOfFormNames(Vector formIDs) { Vector listOfNames = new Vector(); try { RecordEnumeration recordEnum = recordStore.enumerateRecords(null, null, false); while (recordEnum.hasNextElement()) { int i = recordEnum.nextRecordId(); listOfNames.addElement(this.getName(i)); formIDs.addElement(new Integer(i)); } } catch (RecordStoreNotOpenException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (RecordStoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } return listOfNames; } public int getIDfromName(String name) { // TODO Check if this is still needed / valid - considering two forms // can have same name int id = -1; this.open(); FormDefMetaData xformMetaData = new FormDefMetaData(); try { RecordEnumeration recEnum = recordStore.enumerateRecords(null, null, false); while (recEnum.hasNextElement()) { id = recEnum.nextRecordId(); this.retrieveMetaDataFromRMS(id, xformMetaData); if (xformMetaData.getName().equals(name)) { break; } id = -1; } } catch (Exception ex) { ex.printStackTrace(); } return id; } /** * @return a list of MetaData for the form data objects stored in this RMS */ public Vector getFormMetaDataList() { Vector metaDataList = new Vector(); try { RecordEnumeration metaEnum = metaDataRMS.enumerateMetaData(); while (metaEnum.hasNextElement()) { int i = metaEnum.nextRecordId(); metaDataList.addElement(getMetaDataFromId(i)); } } catch (InvalidRecordIDException e) { // TODO Auto-generated catch block e.printStackTrace(); } return metaDataList; } public PrototypeFactory getReferenceFactory() { if(referenceFactory == null) { referenceFactory = new PrototypeFactory(); } return referenceFactory; } public void addReferencePrototype(IDataReference reference) { getReferenceFactory().addNewPrototype(reference.getClass().getName(), reference.getClass()); } public void clearReferenceFactory() { referenceFactory = null; } }
package org.spoofax.interpreter.core; import org.spoofax.interpreter.terms.IStrategoAppl; import org.spoofax.interpreter.terms.IStrategoConstructor; import org.spoofax.interpreter.terms.IStrategoInt; import org.spoofax.interpreter.terms.IStrategoList; import org.spoofax.interpreter.terms.IStrategoReal; import org.spoofax.interpreter.terms.IStrategoString; import org.spoofax.interpreter.terms.IStrategoTerm; import javax.annotation.Nullable; import java.util.Arrays; import java.util.Collections; import java.util.List; /** * Functions for working with terms. */ public final class Tools { // Subterms /** * Gets the string subterm at the given index in the given term. * * @param t the term * @param i the index within the term's subterms * @return the string subterm; or {@code null} when the subterm is not a string term * @throws IndexOutOfBoundsException the index is out of bounds */ @Nullable public static IStrategoString stringAt(IStrategoTerm t, int i) { IStrategoTerm subterm = t.getSubterm(i); return subterm instanceof IStrategoString ? (IStrategoString)subterm : null; } /** * Gets the constructor application subterm at the given index in the given term. * * @param t the term * @param i the index within the term's subterms * @return the constructor application subterm; or {@code null} when the subterm is not a constructor application term * @throws IndexOutOfBoundsException the index is out of bounds */ @Nullable public static IStrategoAppl applAt(IStrategoTerm t, int i) { IStrategoTerm subterm = t.getSubterm(i); return subterm instanceof IStrategoAppl ? (IStrategoAppl)subterm : null; } /** * Gets the int subterm at the given index in the given term. * * @param t the term * @param i the index within the term's subterms * @return the int subterm; or {@code null} when the subterm is not an int term * @throws IndexOutOfBoundsException the index is out of bounds */ @Nullable public static IStrategoInt intAt(IStrategoTerm t, int i) { IStrategoTerm subterm = t.getSubterm(i); return subterm instanceof IStrategoInt ? (IStrategoInt)subterm : null; } /** * Gets the list subterm at the given index in the given term. * * @param t the term * @param i the index within the term's subterms * @return the list subterm; or {@code null} when the subterm is not a list term * @throws IndexOutOfBoundsException the index is out of bounds */ @Nullable public static IStrategoList listAt(IStrategoTerm t, int i) { IStrategoTerm subterm = t.getSubterm(i); return subterm instanceof IStrategoList ? (IStrategoList)subterm : null; } /** * Gets the real subterm at the given index in the given term. * * @param t the term * @param i the index within the term's subterms * @return the real subterm; or {@code null} when the subterm is not a real term * @throws IndexOutOfBoundsException the index is out of bounds */ @Nullable public static IStrategoReal realAt(IStrategoTerm t, int i) { IStrategoTerm subterm = t.getSubterm(i); return subterm instanceof IStrategoReal ? (IStrategoReal)subterm : null; } /** * Gets the subterm at the given index in the given term. * * Note that this function will not throw an exception when the term is cast to the wrong type. * Instead, you will get a {@link ClassCastException} somewhere else. * * @param t the term * @param i the index within the term's subterms * @return the subterm * @throws IndexOutOfBoundsException the index is out of bounds */ @SuppressWarnings("unchecked") // casting is inherently unsafe, but doesn't warrant a warning here public static<T extends IStrategoTerm> T termAt(IStrategoTerm t, int i) { return (T) t.getSubterm(i); } // Constructors /** * Determines whether the given term is a {@code Cons(_, _)} term. * * @param t the constructor application term to check * @param env the term context in which to check * @return {@code true} when the term has the expected constructor in the given context; * otherwise, {@code false} */ public static boolean isCons(IStrategoAppl t, IContext env) { return env.getStrategoSignature().getCons().equals(t.getConstructor()); } /** * Determines whether the given constructor application term is a {@code Nil()} term. * * @param t the constructor application term to check * @param env the term context in which to check * @return {@code true} when the term has the expected constructor in the given context; * otherwise, {@code false} */ public static boolean isNil(IStrategoAppl t, IContext env) { return env.getStrategoSignature().getNil().equals(t.getConstructor()); } /** * Determines whether the given constructor application term is a {@code SDefT(_, _, _, _)} term. * * @param t the constructor application term to check * @param env the term context in which to check * @return {@code true} when the term has the expected constructor in the given context; * otherwise, {@code false} */ public static boolean isSDefT(IStrategoAppl t, IContext env) { return env.getStrategoSignature().getSDefT().equals(t.getConstructor()); } /** * Determines whether the given constructor application term is an {@code ExtSDef(_, _, _)} term. * * @param t the constructor application term to check * @param env the term context in which to check * @return {@code true} when the term has the expected constructor in the given context; * otherwise, {@code false} */ public static boolean isExtSDef(IStrategoAppl t, IContext env) { return env.getStrategoSignature().getExtSDef().equals(t.getConstructor()); } /** * Determines whether the given constructor application term is an {@code Anno(_, _)} term. * * @param t the constructor application term to check * @param env the term context in which to check * @return {@code true} when the term has the expected constructor in the given context; * otherwise, {@code false} */ public static boolean isAnno(IStrategoAppl t, IContext env) { return env.getStrategoSignature().getAnno().equals(t.getConstructor()); } /** * Determines whether the given constructor application term is an {@code Op(_, _)} term. * * @param t the constructor application term to check * @param env the term context in which to check * @return {@code true} when the term has the expected constructor in the given context; * otherwise, {@code false} */ public static boolean isOp(IStrategoAppl t, IContext env) { return env.getStrategoSignature().getOp().equals(t.getConstructor()); } /** * Determines whether the given constructor application term is a {@code Str(_)} term. * * @param t the constructor application term to check * @param env the term context in which to check * @return {@code true} when the term has the expected constructor in the given context; * otherwise, {@code false} */ public static boolean isStr(IStrategoAppl t, IContext env) { return env.getStrategoSignature().getStr().equals(t.getConstructor()); } /** * Determines whether the given constructor application term is a {@code Var(_)} term. * * @param t the constructor application term to check * @param env the term context in which to check * @return {@code true} when the term has the expected constructor in the given context; * otherwise, {@code false} */ public static boolean isVar(IStrategoAppl t, IContext env) { return env.getStrategoSignature().getVar().equals(t.getConstructor()); } /** * Determines whether the given constructor application term is an {@code Explode(_, _)} term. * * @param t the constructor application term to check * @param env the term context in which to check * @return {@code true} when the term has the expected constructor in the given context; * otherwise, {@code false} */ public static boolean isExplode(IStrategoAppl t, IContext env) { return env.getStrategoSignature().getExplode().equals(t.getConstructor()); } /** * Determines whether the given constructor application term is a {@code Wld()} term. * * @param t the constructor application term to check * @param env the term context in which to check * @return {@code true} when the term has the expected constructor in the given context; * otherwise, {@code false} */ public static boolean isWld(IStrategoAppl t, IContext env) { return env.getStrategoSignature().getWld().equals(t.getConstructor()); } /** * Determines whether the given constructor application term is an {@code As(_, _)} term. * * @param t the constructor application term to check * @param env the term context in which to check * @return {@code true} when the term has the expected constructor in the given context; * otherwise, {@code false} */ public static boolean isAs(IStrategoAppl t, IContext env) { return env.getStrategoSignature().getAs().equals(t.getConstructor()); } /** * Determines whether the given constructor application term is a {@code Real(_)} term. * * @param t the constructor application term to check * @param env the term context in which to check * @return {@code true} when the term has the expected constructor in the given context; * otherwise, {@code false} */ public static boolean isReal(IStrategoAppl t, IContext env) { return env.getStrategoSignature().getReal().equals(t.getConstructor()); } /** * Determines whether the given constructor application term is an {@code Int(_)} term. * * @param t the constructor application term to check * @param env the term context in which to check * @return {@code true} when the term has the expected constructor in the given context; * otherwise, {@code false} */ public static boolean isInt(IStrategoAppl t, IContext env) { return env.getStrategoSignature().getInt().equals(t.getConstructor()); } /** * Determines whether the given constructor application term is a {@code FunType(_, _)} term. * * @param t the constructor application term to check * @param env the term context in which to check * @return {@code true} when the term has the expected constructor in the given context; * otherwise, {@code false} */ public static boolean isFunType(IStrategoAppl t, IContext env) { return env.getStrategoSignature().getFunType().equals(t.getConstructor()); } /** * Determines whether the given constructor application term is a {@code ConstType(_)} term. * * @param t the constructor application term to check * @param env the term context in which to check * @return {@code true} when the term has the expected constructor in the given context; * otherwise, {@code false} */ public static boolean isConstType(IStrategoAppl t, IContext env) { return env.getStrategoSignature().getConstType().equals(t.getConstructor()); } /** * Determines whether the given constructor application term has a constructor with the specified name. * * @param t the constructor application term to check * @param ctorName the expected constructor name * @return {@code true} when the term has the expected constructor name; * otherwise, {@code false} */ public static boolean hasConstructor(IStrategoAppl t, String ctorName) { return t.getConstructor().getName().equals(ctorName); } /** * Determines whether the given constructor application term has a constructor with the specified name. * and arity * * @param t the constructor application term to check * @param ctorName the expected constructor name * @param arity the expected constructor arity * @return {@code true} when the term has the expected constructor name and arity; * otherwise, {@code false} */ public static boolean hasConstructor(IStrategoAppl t, String ctorName, int arity) { final IStrategoConstructor constructor = t.getConstructor(); return constructor.getName().equals(ctorName) && constructor.getArity() == arity; } /** * Extracts the constructor name of the given term. * * @param t the term whose constructor name to extract * @return the constructor name; or {@code null} when the term has no constructor */ @Nullable public static String constructorName(IStrategoTerm t) { return t instanceof IStrategoAppl ? ((IStrategoAppl)t).getConstructor().getName() : null; } // Term Types /** * Determines whether the given term is a String term. * * @param t the term to check * @return {@code true} when the term is a String term; otherwise, {@code false} */ public static boolean isTermString(IStrategoTerm t) { return t.getTermType() == IStrategoTerm.STRING; } /** * Determines whether the given term is a List term. * * @param t the term to check * @return {@code true} when the term is a List term; otherwise, {@code false} */ public static boolean isTermList(IStrategoTerm t) { return t.getTermType() == IStrategoTerm.LIST; } /** * Determines whether the given term is an Int term. * * @param t the term to check * @return {@code true} when the term is an Int term; otherwise, {@code false} */ public static boolean isTermInt(IStrategoTerm t) { return t.getTermType() == IStrategoTerm.INT; } /** * Determines whether the given term is a Real term. * * @param t the term to check * @return {@code true} when the term is a Real term; otherwise, {@code false} */ public static boolean isTermReal(IStrategoTerm t) { return t.getTermType() == IStrategoTerm.REAL; } /** * Determines whether the given term is a constructor application term. * * @param t the term to check * @return {@code true} when the term is a constructor application term; otherwise, {@code false} */ public static boolean isTermAppl(IStrategoTerm t) { return t.getTermType() == IStrategoTerm.APPL; } /** * Determines whether the given term is a Tuple term. * * @param t the term to check * @return {@code true} when the term is a tuple term; otherwise, {@code false} */ public static boolean isTermTuple(IStrategoTerm t) { return t.getTermType() == IStrategoTerm.TUPLE; } // Java Types /** * Returns the given term as a Java integer. * * @param term the term * @return the Java string * @throws ClassCastException the term is not an Int term */ public static int asJavaInt(IStrategoTerm term) { return ((IStrategoInt) term).intValue(); } /** @deprecated Use {@link #asJavaInt} instead. */ @Deprecated public static int javaInt(IStrategoTerm term) { return ((IStrategoInt) term).intValue(); } /** * Gets the Java integer at the given index in the given term. * * @param t the term * @param i the index within the term's subterms * @return the Java integer * @throws ClassCastException the term is not an Int term * @throws IndexOutOfBoundsException the index is out of bounds */ public static int javaIntAt(IStrategoTerm t, int i) { IStrategoInt result = termAt(t, i); return result.intValue(); } /** * Returns the given term as a Java double. * * @param term the term * @return the Java double * @throws ClassCastException the term is not a Real term */ public static double asJavaDouble(IStrategoTerm term) { return ((IStrategoReal) term).realValue(); } /** * Gets the Java double at the given index in the given term. * * @param t the term * @param i the index within the term's subterms * @return the Java integer * @throws ClassCastException the term is not a Real term * @throws IndexOutOfBoundsException the index is out of bounds */ public static double javaDoubleAt(IStrategoTerm t, int i) { IStrategoReal result = termAt(t, i); return result.realValue(); } /** * Returns the given term as a Java string. * * @param term the term * @return the Java string * @throws ClassCastException the term is not a String term */ public static String asJavaString(IStrategoTerm term) { return ((IStrategoString) term).stringValue(); } /** @deprecated Use {@link #asJavaString} instead. */ @Deprecated public static String javaString(IStrategoTerm t) { return ((IStrategoString) t).stringValue(); } /** * Gets the Java string at the given index in the given term. * * @param t the term * @param i the index within the term's subterms * @return the Java string * @throws ClassCastException the term is not a String term * @throws IndexOutOfBoundsException the index is out of bounds */ public static String javaStringAt(IStrategoTerm t, int i) { IStrategoString result = termAt(t, i); return asJavaString(result); } /** * Returns the given term as a Java list. * * @param term the term * @return the Java unmodifiable list * @throws ClassCastException the term is not a List term */ public static List<IStrategoTerm> asJavaList(IStrategoTerm term) { IStrategoList listTerm = (IStrategoList)term; // To ensure a ClassCastException // TODO: Get the term's immutable subterm list instead return Collections.unmodifiableList(Arrays.asList(listTerm.getAllSubterms())); } /** * Gets the Java list at the given index in the given term. * * @param term the term * @param index the index within the term's subterms * @return the Java unmodifiable list * @throws ClassCastException the term is not a List term * @throws IndexOutOfBoundsException the index is out of bounds */ public static List<IStrategoTerm> javaListAt(IStrategoTerm term, int index) { IStrategoList result = termAt(term, index); return asJavaList(result); } }
package com.mindcoders.phial.internal.overlay; import android.content.Context; import android.support.annotation.DrawableRes; import android.support.annotation.VisibleForTesting; import android.view.MotionEvent; import android.view.View; import android.widget.LinearLayout; import com.mindcoders.phial.Page; import com.mindcoders.phial.R; import com.mindcoders.phial.Screen; import com.mindcoders.phial.TargetScreen; import com.mindcoders.phial.internal.util.Precondition; import com.mindcoders.phial.internal.util.ViewUtil; import com.mindcoders.phial.internal.util.support.ResourcesCompat; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; class OverlayView extends LinearLayout { private static final long CLICK_MAX_DURATION_MS = 300L; private final HandleButton btnHandle; interface OnPageSelectedListener { void onFirstPageSelected(Page page, int position); void onPageSelectionChanged(Page page, int position); void onNothingSelected(); } interface OnHandleMoveListener { void onMoveStart(float x, float y); void onMove(float dx, float dy); void onMoveEnd(); } private final int btnSize; private final SelectedPageStorage selectedPageStorage; private final List<Page> pages = new ArrayList<>(); private final Map<Page, View> pageViewMap = new HashMap<>(); private OnPageSelectedListener onPageSelectedListener; private OnHandleMoveListener onHandleMoveListener; /** * True if page buttons are shown */ private boolean isExpanded; private Page selectedPage; @VisibleForTesting OverlayView(Context context) { super(context); Precondition.calledFromTools(this); btnSize = 64; btnHandle = createButton(R.drawable.ic_handle); selectedPageStorage = null; } OverlayView( Context context, int btnSize, SelectedPageStorage selectedPageStorage ) { super(context); this.btnSize = btnSize; this.selectedPageStorage = selectedPageStorage; setOrientation(HORIZONTAL); btnHandle = createButton(R.drawable.ic_handle); btnHandle.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { toggle(); } }); btnHandle.setOnTouchListener(handleOnTouchListener); LinearLayout.LayoutParams params = new LayoutParams(btnSize, btnSize); addView(btnHandle, params); } public void updateVisiblePages(Screen screen) { String selectedPageId = selectedPageStorage.getSelectedPage(); boolean shiftSelectedPage = false; for (Page page : pages) { if (shiftSelectedPage) { selectedPageStorage.setSelectedPage(page.getId()); shiftSelectedPage = false; } boolean screenMatches = false; for (TargetScreen targetScreen : page.getTargetScreens()) { if (screen.matches(targetScreen)) { screenMatches = true; break; } } boolean shouldShowPage = screenMatches || page.getTargetScreens().isEmpty(); if (shouldShowPage && !pageViewMap.containsKey(page)) { addPageButton(page); } else if (!shouldShowPage && pageViewMap.containsKey(page)) { removeView(pageViewMap.remove(page)); if (page.getId().equals(selectedPageId)) { shiftSelectedPage = true; selectedPageStorage.removeSelectedPageId(); } } } } public void addPages(List<Page> pages) { this.pages.addAll(pages); for (Page page : this.pages) { addPageButton(page); } } public void setOnPageSelectedListener(OnPageSelectedListener onPageSelectedListener) { this.onPageSelectedListener = onPageSelectedListener; } public void setOnHandleMoveListener(OnHandleMoveListener onHandleMoveListener) { this.onHandleMoveListener = onHandleMoveListener; } public void show() { if (pages.size() > 0 && !isExpanded) { isExpanded = true; setPageButtonsVisible(true); selectedPage = getPreviouslySelectedPage(); onPageSelectedListener.onFirstPageSelected(selectedPage, pages.indexOf(selectedPage)); setPageButtonsColors(true); } } public void hide() { if (pages.size() > 0 && isExpanded) { isExpanded = false; setPageButtonsVisible(false); selectedPage = null; onPageSelectedListener.onNothingSelected(); setPageButtonsColors(false); } } private void toggle() { if (isExpanded) { hide(); } else { show(); } } private void setPageButtonsVisible(boolean visible) { for (int i = 0; i < getChildCount() - 1; i++) { View v = getChildAt(i); v.setVisibility(visible ? View.VISIBLE : View.GONE); } } private void setPageButtonsColors(boolean isExpanded) { if (isExpanded) { View activeButton = pageViewMap.get(selectedPage); for (int i = 0; i < getChildCount() - 1; i++) { View btn = getChildAt(i); btn.setSelected(activeButton == btn); } } } private Page getPreviouslySelectedPage() { String id = selectedPageStorage.getSelectedPage(); for (Page page : pages) { if (page.getId().equals(id)) { return page; } } return pages.get(0); } private void addPageButton(final Page page) { final HandleButton button = createButton(page.getIconResourceId()); LinearLayout.LayoutParams params = new LayoutParams(btnSize, btnSize); addView(button, 0, params); button.setVisibility(View.GONE); button.setTag(page.getId()); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (onPageSelectedListener != null) { if (selectedPage == null) { selectedPage = page; onPageSelectedListener.onFirstPageSelected(page, pages.indexOf(page)); } else if (selectedPage != page) { selectedPage = page; onPageSelectedListener.onPageSelectionChanged(page, pages.indexOf(page)); selectedPageStorage.setSelectedPage(page.getId()); setPageButtonsColors(isExpanded); } else { selectedPage = null; onPageSelectedListener.onNothingSelected(); setPageButtonsVisible(false); isExpanded = false; } } } }); pageViewMap.put(page, button); } private HandleButton createButton(@DrawableRes int iconResId) { final int bgColor = ResourcesCompat.getColor(getResources(), R.color.phial_button_background, getContext().getTheme()); final int fgColor = ResourcesCompat.getColor(getResources(), R.color.phial_button_foreground, getContext().getTheme()); return new HandleButton(getContext(), iconResId, bgColor, fgColor); } private final OnTouchListener handleOnTouchListener = new OnTouchListener() { private float initialTouchX, initialTouchY; private long startTimeMS; @Override public boolean onTouch(View v, MotionEvent event) { if (selectedPage != null) { return false; } switch (event.getAction()) { case MotionEvent.ACTION_DOWN: initialTouchX = event.getRawX(); initialTouchY = event.getRawY(); startTimeMS = event.getEventTime(); onHandleMoveListener.onMoveStart(initialTouchX, initialTouchY); break; case MotionEvent.ACTION_MOVE: onHandleMoveListener.onMove(event.getRawX() - initialTouchX, event.getRawY() - initialTouchY); break; case MotionEvent.ACTION_UP: onHandleMoveListener.onMoveEnd(); final long downTimeMS = event.getEventTime() - startTimeMS; final boolean wasClicked = downTimeMS < CLICK_MAX_DURATION_MS && ViewUtil.distance(initialTouchX, initialTouchY, event.getRawX(), event.getRawY()) < btnSize / 2; if (wasClicked) { v.performClick(); } break; default: return true; } return true; } }; }
package sk.henrichg.phoneprofilesplus; import android.app.Activity; import android.app.KeyguardManager; import android.app.Service; import android.content.Context; import android.content.Intent; import android.os.IBinder; import android.util.Log; public class KeyguardService extends Service { static final String KEYGUARD_LOCK = "phoneProfilesPlus.keyguardLock"; private KeyguardManager keyguardManager; private KeyguardManager.KeyguardLock keyguardLock; @SuppressWarnings("deprecation") @Override public void onCreate() { keyguardManager = (KeyguardManager)getApplicationContext().getSystemService(Activity.KEYGUARD_SERVICE); keyguardLock = keyguardManager.newKeyguardLock(KEYGUARD_LOCK); } @SuppressWarnings("deprecation") @Override public void onDestroy() { Log.e("---- KeyguardService", "onDeastroy"); Keyguard.reenable(keyguardLock); } @SuppressWarnings("deprecation") @Override public int onStartCommand(Intent intent, int flags, int startId) { Context context = getApplicationContext(); if (!GlobalData.getApplicationStarted(context)) { Keyguard.reenable(keyguardLock); stopSelf(); return START_NOT_STICKY; } boolean secureKeyguard; if (android.os.Build.VERSION.SDK_INT >= 16) secureKeyguard = keyguardManager.isKeyguardSecure(); else secureKeyguard = keyguardManager.inKeyguardRestrictedInputMode(); GlobalData.logE("$$$ KeyguardService.onStartCommand","secureKeyguard="+secureKeyguard); if (!secureKeyguard) { GlobalData.logE("$$$ KeyguardService.onStartCommand xxx","getLockscreenDisabled="+GlobalData.getLockscreenDisabled(context)); // zapnutie/vypnutie lockscreenu //getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD); if (GlobalData.getLockscreenDisabled(context)) { GlobalData.logE("$$$ KeyguardService.onStartCommand","Keyguard.disable(), START_STICKY"); //Keyguard.reenable(keyguardLock); Keyguard.disable(keyguardLock); return START_STICKY; } else { GlobalData.logE("$$$ KeyguardService.onStartCommand","Keyguard.reenable(), stopSelf(), START_NOT_STICKY"); Keyguard.reenable(keyguardLock); stopSelf(); return START_NOT_STICKY; } } GlobalData.logE("$$$ KeyguardService.onStartCommand"," secureKeyguard, stopSelf(), START_NOT_STICKY"); stopSelf(); return START_NOT_STICKY; } @Override public IBinder onBind(Intent intent) { return null; } }
package fr.pizzeria.admin.web.filter; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; 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.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession;
package com.intellij.openapi.progress.impl; import com.google.common.collect.ConcurrentHashMultiset; import com.intellij.concurrency.JobScheduler; import com.intellij.diagnostic.ThreadDumper; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.application.ex.ApplicationEx; import com.intellij.openapi.application.ex.ApplicationUtil; import com.intellij.openapi.diagnostic.Attachment; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.progress.*; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.Ref; import com.intellij.openapi.util.ThrowableComputable; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.wm.ex.ProgressIndicatorEx; import com.intellij.util.ExceptionUtil; import com.intellij.util.ObjectUtils; import com.intellij.util.concurrency.AppExecutorUtil; import com.intellij.util.containers.ConcurrentLongObjectMap; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.SmartHashSet; import org.jetbrains.annotations.*; import javax.swing.*; import java.util.*; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.locks.LockSupport; public class CoreProgressManager extends ProgressManager implements Disposable { private static final Logger LOG = Logger.getInstance(CoreProgressManager.class); static final int CHECK_CANCELED_DELAY_MILLIS = 10; private final AtomicInteger myUnsafeProgressCount = new AtomicInteger(0); public static final boolean ENABLED = !"disabled".equals(System.getProperty("idea.ProcessCanceledException")); private static CheckCanceledHook ourCheckCanceledHook; private ScheduledFuture<?> myCheckCancelledFuture; // guarded by threadsUnderIndicator // indicator -> threads which are running under this indicator. // THashMap is avoided here because of tombstones overhead private static final Map<ProgressIndicator, Set<Thread>> threadsUnderIndicator = new HashMap<>(); // guarded by threadsUnderIndicator // the active indicator for the thread id private static final ConcurrentLongObjectMap<ProgressIndicator> currentIndicators = ContainerUtil.createConcurrentLongObjectMap(); // top-level indicators for the thread id private static final ConcurrentLongObjectMap<ProgressIndicator> threadTopLevelIndicators = ContainerUtil.createConcurrentLongObjectMap(); // threads which are running under canceled indicator // THashSet is avoided here because of possible tombstones overhead static final Set<Thread> threadsUnderCanceledIndicator = new HashSet<>(); // guarded by threadsUnderIndicator @NotNull private static volatile CheckCanceledBehavior ourCheckCanceledBehavior = CheckCanceledBehavior.NONE; private enum CheckCanceledBehavior { NONE, ONLY_HOOKS, INDICATOR_PLUS_HOOKS } /** active (i.e. which have {@link #executeProcessUnderProgress(Runnable, ProgressIndicator)} method running) indicators * which are not inherited from {@link StandardProgressIndicator}. * for them an extra processing thread (see {@link #myCheckCancelledFuture}) has to be run * to call their non-standard {@link ProgressIndicator#checkCanceled()} method periodically. */ // multiset here (instead of a set) is for simplifying add/remove indicators on process-with-progress start/end with possibly identical indicators. private static final Collection<ProgressIndicator> nonStandardIndicators = ConcurrentHashMultiset.create(); /** true if running in non-cancelable section started with * {@link #executeNonCancelableSection(Runnable)} in this thread */ private static final ThreadLocal<Boolean> isInNonCancelableSection = new ThreadLocal<>(); // do not supply initial value to conserve memory // must be under threadsUnderIndicator lock private void startBackgroundNonStandardIndicatorsPing() { if (myCheckCancelledFuture == null) { myCheckCancelledFuture = JobScheduler.getScheduler().scheduleWithFixedDelay(() -> { for (ProgressIndicator indicator : nonStandardIndicators) { try { indicator.checkCanceled(); } catch (ProcessCanceledException e) { indicatorCanceled(indicator); } } }, 0, CHECK_CANCELED_DELAY_MILLIS, TimeUnit.MILLISECONDS); } } // must be under threadsUnderIndicator lock private void stopBackgroundNonStandardIndicatorsPing() { if (myCheckCancelledFuture != null) { myCheckCancelledFuture.cancel(true); myCheckCancelledFuture = null; } } @Override public void dispose() { synchronized (threadsUnderIndicator) { stopBackgroundNonStandardIndicatorsPing(); } } List<ProgressIndicator> getCurrentIndicators() { synchronized (threadsUnderIndicator) { return new ArrayList<>(threadsUnderIndicator.keySet()); } } @ApiStatus.Internal public static boolean runCheckCanceledHooks(@Nullable ProgressIndicator indicator) { CheckCanceledHook hook = ourCheckCanceledHook; return hook != null && hook.runHook(indicator); } @Override protected void doCheckCanceled() throws ProcessCanceledException { CheckCanceledBehavior behavior = ourCheckCanceledBehavior; if (behavior == CheckCanceledBehavior.NONE) return; final ProgressIndicator progress = getProgressIndicator(); if (progress != null && behavior == CheckCanceledBehavior.INDICATOR_PLUS_HOOKS) { progress.checkCanceled(); } else { runCheckCanceledHooks(progress); } } @Override public boolean hasProgressIndicator() { return getProgressIndicator() != null; } @Override public boolean hasUnsafeProgressIndicator() { return myUnsafeProgressCount.get() > 0; } @Override public boolean hasModalProgressIndicator() { synchronized (threadsUnderIndicator) { return ContainerUtil.or(threadsUnderIndicator.keySet(), i -> i.isModal()); } } // run in current thread @Override public void runProcess(@NotNull final Runnable process, @Nullable ProgressIndicator progress) { executeProcessUnderProgress(() -> { try { try { if (progress != null && !progress.isRunning()) { progress.start(); } } catch (RuntimeException e) { throw e; } catch (Throwable e) { throw new RuntimeException(e); } process.run(); } finally { if (progress != null && progress.isRunning()) { progress.stop(); if (progress instanceof ProgressIndicatorEx) { ((ProgressIndicatorEx)progress).processFinish(); } } } }, progress); } // run in the current thread (?) @Override public void executeNonCancelableSection(@NotNull Runnable runnable) { if (isInNonCancelableSection()) { runnable.run(); } else { try { isInNonCancelableSection.set(Boolean.TRUE); executeProcessUnderProgress(runnable, NonCancelableIndicator.INSTANCE); } finally { isInNonCancelableSection.remove(); } } } // FROM EDT: bg OR calling if can't @Override public <T, E extends Exception> T computeInNonCancelableSection(@NotNull ThrowableComputable<T, E> computable) throws E { final Ref<T> result = Ref.create(); final Ref<Exception> exception = Ref.create(); executeNonCancelableSection(() -> { try { result.set(computable.compute()); } catch (Exception t) { exception.set(t); } }); Throwable t = exception.get(); if (t != null) { ExceptionUtil.rethrowUnchecked(t); @SuppressWarnings("unchecked") E e = (E)t; throw e; } return result.get(); } @Override public boolean runProcessWithProgressSynchronously(@NotNull Runnable process, @NotNull @Nls String progressTitle, boolean canBeCanceled, @Nullable Project project) { return runProcessWithProgressSynchronously(process, progressTitle, canBeCanceled, project, null); } // FROM EDT->UI: bg OR calling if can't @Override public <T, E extends Exception> T runProcessWithProgressSynchronously(@NotNull final ThrowableComputable<T, E> process, @NotNull @Nls String progressTitle, boolean canBeCanceled, @Nullable Project project) throws E { final AtomicReference<T> result = new AtomicReference<>(); final AtomicReference<Throwable> exception = new AtomicReference<>(); runProcessWithProgressSynchronously(new Task.Modal(project, progressTitle, canBeCanceled) { @Override public void run(@NotNull ProgressIndicator indicator) { try { T compute = process.compute(); result.set(compute); } catch (Throwable t) { exception.set(t); } } }, null); Throwable t = exception.get(); if (t != null) { ExceptionUtil.rethrowUnchecked(t); @SuppressWarnings("unchecked") E e = (E)t; throw e; } return result.get(); } // FROM EDT: bg OR calling if can't @Override public boolean runProcessWithProgressSynchronously(@NotNull final Runnable process, @NotNull @Nls String progressTitle, boolean canBeCanceled, @Nullable Project project, @Nullable JComponent parentComponent) { Task.Modal task = new Task.Modal(project, progressTitle, canBeCanceled) { @Override public void run(@NotNull ProgressIndicator indicator) { process.run(); } }; return runProcessWithProgressSynchronously(task, parentComponent); } // bg; runnables on UI/EDT? @Override public void runProcessWithProgressAsynchronously(@NotNull Project project, @NotNull @Nls String progressTitle, @NotNull Runnable process, @Nullable Runnable successRunnable, @Nullable Runnable canceledRunnable) { runProcessWithProgressAsynchronously(project, progressTitle, process, successRunnable, canceledRunnable, PerformInBackgroundOption.DEAF); } // bg; runnables on UI/EDT? @Override public void runProcessWithProgressAsynchronously(@NotNull Project project, @NotNull @Nls String progressTitle, @NotNull final Runnable process, @Nullable final Runnable successRunnable, @Nullable final Runnable canceledRunnable, @NotNull PerformInBackgroundOption option) { runProcessWithProgressAsynchronously(new Task.Backgroundable(project, progressTitle, true, option) { @Override public void run(@NotNull final ProgressIndicator indicator) { process.run(); } @Override public void onCancel() { if (canceledRunnable != null) { canceledRunnable.run(); } } @Override public void onSuccess() { if (successRunnable != null) { successRunnable.run(); } } }); } // from any: bg or current if can't @Override public void run(@NotNull final Task task) { if (task.isHeadless()) { if (SwingUtilities.isEventDispatchThread()) { runProcessWithProgressSynchronously(task, null); } else { runProcessWithProgressInCurrentThread(task, new EmptyProgressIndicator(), ModalityState.defaultModalityState()); } } else if (task.isModal()) { runSynchronously(task.asModal()); } else { final Task.Backgroundable backgroundable = task.asBackgroundable(); if (backgroundable.isConditionalModal() && !backgroundable.shouldStartInBackground()) { runSynchronously(task); } else { runAsynchronously(backgroundable); } } } // from any: bg or edt if can't private void runSynchronously(@NotNull final Task task) { runProcessWithProgressSynchronously(task, null); } // from any: bg private void runAsynchronously(@NotNull final Task.Backgroundable task) { if (ApplicationManager.getApplication().isDispatchThread()) { runProcessWithProgressAsynchronously(task); } else { ApplicationManager.getApplication().invokeLater(() -> { Project project = task.getProject(); if (project != null && project.isDisposed()) { LOG.info("Task canceled because of project disposal: " + task); finishTask(task, true, null); return; } runProcessWithProgressAsynchronously(task); }, ModalityState.defaultModalityState()); } } // from any: bg @NotNull public Future<?> runProcessWithProgressAsynchronously(@NotNull Task.Backgroundable task) { return runProcessWithProgressAsynchronously(task, new EmptyProgressIndicator(), null); } // from any: bg @NotNull public Future<?> runProcessWithProgressAsynchronously(@NotNull final Task.Backgroundable task, @NotNull final ProgressIndicator progressIndicator, @Nullable final Runnable continuation) { return runProcessWithProgressAsynchronously(task, progressIndicator, continuation, progressIndicator.getModalityState()); } @Deprecated @NotNull protected TaskRunnable createTaskRunnable(@NotNull Task task, @NotNull ProgressIndicator indicator, @Nullable Runnable continuation) { return new TaskRunnable(task, indicator, continuation); } private static class IndicatorDisposable implements Disposable { @NotNull private final ProgressIndicator myIndicator; IndicatorDisposable(@NotNull ProgressIndicator indicator) { myIndicator = indicator; } @Override public void dispose() { // do nothing if already disposed Disposer.dispose((Disposable)myIndicator, false); } } // from any: bg, task.finish on "UI/EDT" @NotNull public Future<?> runProcessWithProgressAsynchronously(@NotNull final Task.Backgroundable task, @NotNull final ProgressIndicator progressIndicator, @Nullable final Runnable continuation, @NotNull final ModalityState modalityState) { IndicatorDisposable indicatorDisposable; if (progressIndicator instanceof Disposable) { // use IndicatorDisposable instead of progressIndicator to // avoid re-registering progressIndicator if it was registered on some other parent before indicatorDisposable = new IndicatorDisposable(progressIndicator); Disposer.register(ApplicationManager.getApplication(), indicatorDisposable); } else { indicatorDisposable = null; } return runProcessWithProgressAsync(task, CompletableFuture.completedFuture(progressIndicator), continuation, indicatorDisposable, modalityState); } @NotNull protected Future<?> runProcessWithProgressAsync(@NotNull Task.Backgroundable task, @NotNull CompletableFuture<? extends ProgressIndicator> progressIndicator, @Nullable Runnable continuation, @Nullable IndicatorDisposable indicatorDisposable, @Nullable ModalityState modalityState) { // TODO ->> notify create runnable AtomicLong elapsed = new AtomicLong(); return new ProgressRunner<>((progress) -> { final long start = System.currentTimeMillis(); try { new TaskRunnable(task, progress, continuation).run(); } finally { elapsed.set(System.currentTimeMillis() - start); } return null; }).onThread(ProgressRunner.ThreadToUse.POOLED) .withProgress(progressIndicator) .submit() .whenComplete((result, err) -> { if (!result.isCanceled()) { notifyTaskFinished(task, elapsed.get()); } ModalityState modality; if (modalityState != null) { modality = modalityState; } else { try { modality = progressIndicator.get().getModalityState(); } catch (Throwable e) { modality = ModalityState.NON_MODAL; } } ApplicationUtil.invokeLaterSomewhere(() -> { finishTask(task, result.isCanceled(), result.getThrowable() instanceof ProcessCanceledException ? null : result.getThrowable()); if (indicatorDisposable != null) { Disposer.dispose(indicatorDisposable); } }, task.whereToRunCallbacks(), modality); }); } void notifyTaskFinished(@NotNull Task.Backgroundable task, long elapsed) { } // ASSERT IS EDT->UI bg or calling if cant // NEW: no assert; bg or calling ... public boolean runProcessWithProgressSynchronously(@NotNull final Task task, @Nullable final JComponent parentComponent) { final Ref<Throwable> exceptionRef = new Ref<>(); TaskContainer taskContainer = new TaskContainer(task) { @Override public void run() { try { createTaskRunnable(task, getProgressIndicator(), null).run(); } catch (ProcessCanceledException e) { throw e; } catch (Throwable e) { exceptionRef.set(e); } } }; ApplicationEx application = (ApplicationEx)ApplicationManager.getApplication(); boolean result = application.runProcessWithProgressSynchronously(taskContainer, task.getTitle(), task.isCancellable(), task.getProject(), parentComponent, task.getCancelText()); ApplicationUtil.invokeAndWaitSomewhere(() -> finishTask(task, !result, exceptionRef.get()), task.whereToRunCallbacks()); return result; } // in current thread public void runProcessWithProgressInCurrentThread(@NotNull final Task task, @NotNull final ProgressIndicator progressIndicator, @NotNull final ModalityState modalityState) { if (progressIndicator instanceof Disposable) { Disposer.register(ApplicationManager.getApplication(), (Disposable)progressIndicator); } final Runnable process = createTaskRunnable(task, progressIndicator, null); boolean processCanceled = false; Throwable exception = null; try { runProcess(process, progressIndicator); } catch (ProcessCanceledException e) { processCanceled = true; } catch (Throwable e) { exception = e; } final boolean finalCanceled = processCanceled || progressIndicator.isCanceled(); final Throwable finalException = exception; ApplicationUtil.invokeAndWaitSomewhere(() -> finishTask(task, finalCanceled, finalException), task.whereToRunCallbacks(), modalityState); } protected void finishTask(@NotNull Task task, boolean canceled, @Nullable Throwable error) { try { if (error != null) { task.onThrowable(error); } else if (canceled) { task.onCancel(); } else { task.onSuccess(); } } finally { task.onFinished(); } } @Override public void runProcessWithProgressAsynchronously(@NotNull Task.Backgroundable task, @NotNull ProgressIndicator progressIndicator) { runProcessWithProgressAsynchronously(task, progressIndicator, null); } @Override public ProgressIndicator getProgressIndicator() { return getCurrentIndicator(Thread.currentThread()); } // run in current thread @Override public void executeProcessUnderProgress(@NotNull Runnable process, ProgressIndicator progress) throws ProcessCanceledException { if (progress == null) myUnsafeProgressCount.incrementAndGet(); try { ProgressIndicator oldIndicator = null; boolean set = progress != null && progress != (oldIndicator = getProgressIndicator()); if (set) { Thread currentThread = Thread.currentThread(); long threadId = currentThread.getId(); setCurrentIndicator(threadId, progress); try { registerIndicatorAndRun(progress, currentThread, oldIndicator, process); } finally { setCurrentIndicator(threadId, oldIndicator); } } else { process.run(); } } finally { if (progress == null) myUnsafeProgressCount.decrementAndGet(); } } @Override public boolean runInReadActionWithWriteActionPriority(@NotNull Runnable action, @Nullable ProgressIndicator indicator) { ApplicationManager.getApplication().runReadAction(action); return true; } // this thread private void registerIndicatorAndRun(@NotNull ProgressIndicator indicator, @NotNull Thread currentThread, ProgressIndicator oldIndicator, @NotNull Runnable process) { List<Set<Thread>> threadsUnderThisIndicator = new ArrayList<>(); synchronized (threadsUnderIndicator) { boolean oneOfTheIndicatorsIsCanceled = false; for (ProgressIndicator thisIndicator = indicator; thisIndicator != null; thisIndicator = thisIndicator instanceof WrappedProgressIndicator ? ((WrappedProgressIndicator)thisIndicator).getOriginalProgressIndicator() : null) { Set<Thread> underIndicator = threadsUnderIndicator.computeIfAbsent(thisIndicator, __ -> new SmartHashSet<>()); boolean alreadyUnder = !underIndicator.add(currentThread); threadsUnderThisIndicator.add(alreadyUnder ? null : underIndicator); boolean isStandard = thisIndicator instanceof StandardProgressIndicator; if (!isStandard) { nonStandardIndicators.add(thisIndicator); startBackgroundNonStandardIndicatorsPing(); } oneOfTheIndicatorsIsCanceled |= thisIndicator.isCanceled(); } if (oneOfTheIndicatorsIsCanceled) { threadsUnderCanceledIndicator.add(currentThread); } else { threadsUnderCanceledIndicator.remove(currentThread); } updateShouldCheckCanceled(); } try { process.run(); } finally { synchronized (threadsUnderIndicator) { ProgressIndicator thisIndicator = null; // order doesn't matter for (int i = 0; i < threadsUnderThisIndicator.size(); i++) { thisIndicator = i == 0 ? indicator : ((WrappedProgressIndicator)thisIndicator).getOriginalProgressIndicator(); Set<Thread> underIndicator = threadsUnderThisIndicator.get(i); boolean removed = underIndicator != null && underIndicator.remove(currentThread); if (removed && underIndicator.isEmpty()) { threadsUnderIndicator.remove(thisIndicator); } boolean isStandard = thisIndicator instanceof StandardProgressIndicator; if (!isStandard) { nonStandardIndicators.remove(thisIndicator); if (nonStandardIndicators.isEmpty()) { stopBackgroundNonStandardIndicatorsPing(); } } // by this time oldIndicator may have been canceled if (oldIndicator != null && oldIndicator.isCanceled()) { threadsUnderCanceledIndicator.add(currentThread); } else { threadsUnderCanceledIndicator.remove(currentThread); } } updateShouldCheckCanceled(); } } } @SuppressWarnings("AssignmentToStaticFieldFromInstanceMethod") final void updateShouldCheckCanceled() { synchronized (threadsUnderIndicator) { CheckCanceledHook hook = createCheckCanceledHook(); boolean hasCanceledIndicator = !threadsUnderCanceledIndicator.isEmpty(); ourCheckCanceledHook = hook; ourCheckCanceledBehavior = hook == null && !hasCanceledIndicator ? CheckCanceledBehavior.NONE : hasCanceledIndicator && ENABLED ? CheckCanceledBehavior.INDICATOR_PLUS_HOOKS : CheckCanceledBehavior.ONLY_HOOKS; } } @Nullable protected CheckCanceledHook createCheckCanceledHook() { return null; } @Override protected void indicatorCanceled(@NotNull ProgressIndicator indicator) { // mark threads running under this indicator as canceled synchronized (threadsUnderIndicator) { Set<Thread> threads = threadsUnderIndicator.get(indicator); if (threads != null) { for (Thread thread : threads) { boolean underCancelledIndicator = false; for (ProgressIndicator currentIndicator = getCurrentIndicator(thread); currentIndicator != null; currentIndicator = currentIndicator instanceof WrappedProgressIndicator ? ((WrappedProgressIndicator)currentIndicator).getOriginalProgressIndicator() : null) { if (currentIndicator == indicator) { underCancelledIndicator = true; break; } } if (underCancelledIndicator) { threadsUnderCanceledIndicator.add(thread); updateShouldCheckCanceled(); } } } } } @TestOnly public static boolean isCanceledThread(@NotNull Thread thread) { synchronized (threadsUnderIndicator) { return threadsUnderCanceledIndicator.contains(thread); } } @Override public boolean isInNonCancelableSection() { return isInNonCancelableSection.get() != null; } private static final long MAX_PRIORITIZATION_NANOS = TimeUnit.SECONDS.toNanos(12); private static final Thread[] NO_THREADS = new Thread[0]; private final Set<Thread> myPrioritizedThreads = ContainerUtil.newConcurrentSet(); private volatile Thread[] myEffectivePrioritizedThreads = NO_THREADS; private int myDeprioritizations = 0; private final Object myPrioritizationLock = ObjectUtils.sentinel("myPrioritizationLock"); private volatile long myPrioritizingStarted = 0; // this thread @Override public <T, E extends Throwable> T computePrioritized(@NotNull ThrowableComputable<T, E> computable) throws E { Thread thread = Thread.currentThread(); if (!Registry.is("ide.prioritize.threads") || isPrioritizedThread(thread)) { return computable.compute(); } synchronized (myPrioritizationLock) { if (myPrioritizedThreads.isEmpty()) { myPrioritizingStarted = System.nanoTime(); } myPrioritizedThreads.add(thread); updateEffectivePrioritized(); } try { return computable.compute(); } finally { synchronized (myPrioritizationLock) { myPrioritizedThreads.remove(thread); updateEffectivePrioritized(); } } } private void updateEffectivePrioritized() { Thread[] prev = myEffectivePrioritizedThreads; Thread[] current = myDeprioritizations > 0 || myPrioritizedThreads.isEmpty() ? NO_THREADS : myPrioritizedThreads.toArray(NO_THREADS); myEffectivePrioritizedThreads = current; if (prev.length == 0 && current.length > 0) { prioritizingStarted(); } else if (prev.length > 0 && current.length == 0) { prioritizingFinished(); } } protected void prioritizingStarted() {} protected void prioritizingFinished() {} @ApiStatus.Internal public boolean isPrioritizedThread(@NotNull Thread from) { return myPrioritizedThreads.contains(from); } @ApiStatus.Internal public void suppressPrioritizing() { synchronized (myPrioritizationLock) { if (++myDeprioritizations == 100 + ForkJoinPool.getCommonPoolParallelism() * 2) { Attachment attachment = new Attachment("threadDump.txt", ThreadDumper.dumpThreadsToString()); attachment.setIncluded(true); LOG.error("A suspiciously high nesting of suppressPrioritizing, forgot to call restorePrioritizing?", attachment); } updateEffectivePrioritized(); } } @ApiStatus.Internal public void restorePrioritizing() { synchronized (myPrioritizationLock) { if (--myDeprioritizations < 0) { myDeprioritizations = 0; LOG.error("Unmatched suppressPrioritizing/restorePrioritizing"); } updateEffectivePrioritized(); } } protected boolean sleepIfNeededToGivePriorityToAnotherThread() { if (!isCurrentThreadEffectivelyPrioritized() && checkLowPriorityReallyApplicable()) { LockSupport.parkNanos(1_000_000); avoidBlockingPrioritizingThread(); return true; } return false; } private boolean isCurrentThreadEffectivelyPrioritized() { Thread current = Thread.currentThread(); for (Thread prioritized : myEffectivePrioritizedThreads) { if (prioritized == current) { return true; } } return false; } private boolean checkLowPriorityReallyApplicable() { long time = System.nanoTime() - myPrioritizingStarted; if (time < 5_000_000) { return false; // don't sleep when activities are very short (e.g. empty processing of mouseMoved events) } if (avoidBlockingPrioritizingThread()) { return false; } if (ApplicationManager.getApplication().isDispatchThread()) { return false; // EDT always has high priority } if (time > MAX_PRIORITIZATION_NANOS) { // Don't wait forever in case someone forgot to stop prioritizing before waiting for other threads to complete // wait just for 12 seconds; this will be noticeable (and we'll get 2 thread dumps) but not fatal stopAllPrioritization(); return false; } return true; } private boolean avoidBlockingPrioritizingThread() { if (isAnyPrioritizedThreadBlocked()) { // the current thread could hold a lock that prioritized threads are waiting for suppressPrioritizing(); checkLaterThreadsAreUnblocked(); return true; } return false; } private void checkLaterThreadsAreUnblocked() { try { AppExecutorUtil.getAppScheduledExecutorService().schedule(() -> { if (isAnyPrioritizedThreadBlocked()) { checkLaterThreadsAreUnblocked(); } else { restorePrioritizing(); } }, 5, TimeUnit.MILLISECONDS); } catch (RejectedExecutionException ignore) { } } private void stopAllPrioritization() { synchronized (myPrioritizationLock) { myPrioritizedThreads.clear(); updateEffectivePrioritized(); } } private boolean isAnyPrioritizedThreadBlocked() { for (Thread thread : myEffectivePrioritizedThreads) { Thread.State state = thread.getState(); if (state == Thread.State.WAITING || state == Thread.State.TIMED_WAITING || state == Thread.State.BLOCKED) { return true; } } return false; } @NotNull public static ModalityState getCurrentThreadProgressModality() { ProgressIndicator indicator = threadTopLevelIndicators.get(Thread.currentThread().getId()); ModalityState modality = indicator == null ? null : indicator.getModalityState(); return modality != null ? modality : ModalityState.NON_MODAL; } private static void setCurrentIndicator(long threadId, ProgressIndicator indicator) { if (indicator == null) { currentIndicators.remove(threadId); threadTopLevelIndicators.remove(threadId); } else { currentIndicators.put(threadId, indicator); if (!threadTopLevelIndicators.containsKey(threadId)) { threadTopLevelIndicators.put(threadId, indicator); } } } private static ProgressIndicator getCurrentIndicator(@NotNull Thread thread) { return currentIndicators.get(thread.getId()); } protected abstract static class TaskContainer implements Runnable { private final Task myTask; protected TaskContainer(@NotNull Task task) { myTask = task; } @NotNull public Task getTask() { return myTask; } @Override public String toString() { return myTask.toString(); } } @Deprecated protected static class TaskRunnable extends TaskContainer { private final ProgressIndicator myIndicator; private final Runnable myContinuation; TaskRunnable(@NotNull Task task, @NotNull ProgressIndicator indicator, @Nullable Runnable continuation) { super(task); myIndicator = indicator; myContinuation = continuation; } @Override public void run() { try { getTask().run(myIndicator); } finally { try { if (myIndicator instanceof ProgressIndicatorEx) { ((ProgressIndicatorEx)myIndicator).finish(getTask()); } } finally { if (myContinuation != null) { myContinuation.run(); } } } } } @FunctionalInterface interface CheckCanceledHook { /** * @param indicator the indicator whose {@link ProgressIndicator#checkCanceled()} was called, or null if a non-progressive thread performed {@link ProgressManager#checkCanceled()} * @return true if the hook has done anything that might take some time. */ boolean runHook(@Nullable ProgressIndicator indicator); } public static void assertUnderProgress(@NotNull ProgressIndicator indicator) { synchronized (threadsUnderIndicator) { Set<Thread> threads = threadsUnderIndicator.get(indicator); if (threads == null || !threads.contains(Thread.currentThread())) { LOG.error("Must be executed under progress indicator: "+indicator+". Please see e.g. ProgressManager.runProcess()"); } } } }
package com.intellij.openapi.actionSystem.ex; import com.intellij.icons.AllIcons; import com.intellij.ide.DataManager; import com.intellij.ide.HelpTooltip; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.keymap.KeymapUtil; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.popup.JBPopup; import com.intellij.openapi.ui.popup.JBPopupFactory; import com.intellij.openapi.ui.popup.ListPopup; import com.intellij.openapi.util.Condition; import com.intellij.openapi.util.IconLoader; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.wm.IdeFocusManager; import com.intellij.openapi.wm.IdeFrame; import com.intellij.openapi.wm.WindowManager; import com.intellij.ui.UserActivityProviderComponent; import com.intellij.ui.scale.JBUIScale; import com.intellij.util.ui.*; import com.intellij.util.ui.accessibility.ScreenReader; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionAdapter; import java.awt.geom.Path2D; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; public abstract class ComboBoxAction extends AnAction implements CustomComponentAction { private static Icon myIcon = null; private static Icon myDisabledIcon = null; private static Icon myWin10ComboDropTriangleIcon = null; public static Icon getArrowIcon(boolean enabled) { if (UIUtil.isUnderWin10LookAndFeel()) { if (myWin10ComboDropTriangleIcon == null) { myWin10ComboDropTriangleIcon = IconLoader.findLafIcon("win10/comboDropTriangle", ComboBoxAction.class, true); } return myWin10ComboDropTriangleIcon; } if (myIcon != AllIcons.General.ArrowDown) { myIcon = AllIcons.General.ArrowDown; myDisabledIcon = IconLoader.getDisabledIcon(myIcon); } return enabled ? myIcon : myDisabledIcon; } private boolean mySmallVariant = true; private String myPopupTitle; private static final JBValue ICON_SIZE = new JBValue.Float(16); protected ComboBoxAction() { } @Override public void actionPerformed(@NotNull AnActionEvent e) { Project project = e.getProject(); if (project == null) return; JFrame frame = WindowManager.getInstance().getFrame(project); if (!(frame instanceof IdeFrame)) return; ListPopup popup = createActionPopup(e.getDataContext(), ((IdeFrame)frame).getComponent(), null); popup.showCenteredInCurrentWindow(project); } @NotNull private ListPopup createActionPopup(@NotNull DataContext context, @NotNull JComponent component, @Nullable Runnable disposeCallback) { DefaultActionGroup group = createPopupActionGroup(component, context); ListPopup popup = JBPopupFactory.getInstance().createActionGroupPopup( myPopupTitle, group, context, false, shouldShowDisabledActions(), false, disposeCallback, getMaxRows(), getPreselectCondition()); popup.setMinimumSize(new Dimension(getMinWidth(), getMinHeight())); return popup; } /** @deprecated use {@link ComboBoxAction#createCustomComponent(Presentation, String)} */ @Deprecated @NotNull @Override public JComponent createCustomComponent(@NotNull Presentation presentation) { return createCustomComponent(presentation, ActionPlaces.UNKNOWN); } @NotNull @Override public JComponent createCustomComponent(@NotNull Presentation presentation, @NotNull String place) { JPanel panel = new JPanel(new GridBagLayout()); ComboBoxButton button = createComboBoxButton(presentation); GridBagConstraints constraints = new GridBagConstraints( 0, 0, 1, 1, 1, 1, GridBagConstraints.CENTER, GridBagConstraints.BOTH, JBInsets.create(0, 3), 0, 0); panel.add(button, constraints); return panel; } protected ComboBoxButton createComboBoxButton(Presentation presentation) { return new ComboBoxButton(presentation); } public boolean isSmallVariant() { return mySmallVariant; } public void setSmallVariant(boolean smallVariant) { mySmallVariant = smallVariant; } public void setPopupTitle(String popupTitle) { myPopupTitle = popupTitle; } protected boolean shouldShowDisabledActions() { return false; } @NotNull protected abstract DefaultActionGroup createPopupActionGroup(JComponent button); @NotNull protected DefaultActionGroup createPopupActionGroup(JComponent button, @NotNull DataContext dataContext) { return createPopupActionGroup(button); } protected int getMaxRows() { return 30; } protected int getMinHeight() { return 1; } protected int getMinWidth() { return 1; } protected class ComboBoxButton extends JButton implements UserActivityProviderComponent { private final Presentation myPresentation; private boolean myForcePressed = false; private PropertyChangeListener myButtonSynchronizer; private String myTooltipText; public ComboBoxButton(Presentation presentation) { myPresentation = presentation; setIcon(myPresentation.getIcon()); setText(myPresentation.getText()); setEnabled(myPresentation.isEnabled()); myTooltipText = myPresentation.getDescription(); updateTooltipText(); setModel(new MyButtonModel()); getModel().setEnabled(myPresentation.isEnabled()); setVisible(presentation.isVisible()); setHorizontalAlignment(LEFT); setFocusable(ScreenReader.isActive()); putClientProperty("styleCombo", ComboBoxAction.this); setMargin(JBUI.insets(0, 5, 0, 2)); if (isSmallVariant()) { setFont(JBUI.Fonts.toolbarSmallComboBoxFont()); } addMouseListener(new MouseAdapter() { @Override public void mousePressed(final MouseEvent e) { if (SwingUtilities.isLeftMouseButton(e)) { e.consume(); if (e.isShiftDown()) { doShiftClick(); } else { doClick(); } } } }); addMouseMotionListener(new MouseMotionAdapter() { @Override public void mouseDragged(MouseEvent e) { mouseMoved(MouseEventAdapter.convert(e, e.getComponent(), MouseEvent.MOUSE_MOVED, e.getWhen(), e.getModifiers() | e.getModifiersEx(), e.getX(), e.getY())); } }); } @Override protected void fireActionPerformed(ActionEvent event) { if (!myForcePressed) { IdeFocusManager.getGlobalInstance().doWhenFocusSettlesDown(() -> showPopup()); } } @NotNull private Runnable setForcePressed() { myForcePressed = true; repaint(); return () -> { // give the button a chance to handle action listener ApplicationManager.getApplication().invokeLater(() -> { myForcePressed = false; repaint(); }, ModalityState.any()); repaint(); fireStateChanged(); }; } @Nullable @Override public String getToolTipText() { return myForcePressed || Registry.is("ide.helptooltip.enabled") ? null : super.getToolTipText(); } public void showPopup() { JBPopup popup = createPopup(setForcePressed()); if (Registry.is("ide.helptooltip.enabled")) { HelpTooltip.setMasterPopup(this, popup); } popup.showUnderneathOf(this); } protected JBPopup createPopup(Runnable onDispose) { return createActionPopup(getDataContext(), this, onDispose); } protected DataContext getDataContext() { return DataManager.getInstance().getDataContext(this); } @Override public void removeNotify() { if (myButtonSynchronizer != null) { myPresentation.removePropertyChangeListener(myButtonSynchronizer); myButtonSynchronizer = null; } HelpTooltip.dispose(this); super.removeNotify(); } @Override public void addNotify() { super.addNotify(); if (myButtonSynchronizer == null) { myButtonSynchronizer = new MyButtonSynchronizer(); myPresentation.addPropertyChangeListener(myButtonSynchronizer); } updateTooltipText(); } private void updateTooltipText() { String tooltip = KeymapUtil.createTooltipText(myTooltipText, ComboBoxAction.this); if (Registry.is("ide.helptooltip.enabled") && StringUtil.isNotEmpty(tooltip)) { HelpTooltip.dispose(this); new HelpTooltip().setDescription(tooltip).installOn(this); } else { setToolTipText(!tooltip.isEmpty() ? tooltip : null); } } protected class MyButtonModel extends DefaultButtonModel { @Override public boolean isPressed() { return myForcePressed || super.isPressed(); } @Override public boolean isArmed() { return myForcePressed || super.isArmed(); } } private class MyButtonSynchronizer implements PropertyChangeListener { @Override public void propertyChange(PropertyChangeEvent evt) { String propertyName = evt.getPropertyName(); if (Presentation.PROP_TEXT.equals(propertyName)) { setText((String)evt.getNewValue()); } else if (Presentation.PROP_DESCRIPTION.equals(propertyName)) { myTooltipText = (String)evt.getNewValue(); updateTooltipText(); } else if (Presentation.PROP_ICON.equals(propertyName)) { setIcon((Icon)evt.getNewValue()); } else if (Presentation.PROP_ENABLED.equals(propertyName)) { setEnabled(((Boolean)evt.getNewValue()).booleanValue()); } } } @Override public boolean isOpaque() { return !isSmallVariant(); } @Override public Dimension getPreferredSize() { Dimension prefSize = super.getPreferredSize(); int width = prefSize.width + (myPresentation != null && isArrowVisible(myPresentation) ? (UIUtil.isUnderWin10LookAndFeel() ? getArrowIcon(isEnabled()).getIconWidth() + JBUIScale.scale(6) : ICON_SIZE.get()) : 0) + (StringUtil.isNotEmpty(getText()) ? getIconTextGap() : 0); Dimension size = new Dimension(width, isSmallVariant() ? JBUIScale.scale(24) : Math.max(JBUIScale.scale(24), prefSize.height)); JBInsets.addTo(size, getMargin()); return size; } @Override public Dimension getMinimumSize() { return new Dimension(super.getMinimumSize().width, getPreferredSize().height); } @Override public Font getFont() { return isSmallVariant() ? UIUtil.getToolbarFont() : UIUtil.getLabelFont(); } @Override protected Graphics getComponentGraphics(Graphics graphics) { return JBSwingUtilities.runGlobalCGTransform(this, super.getComponentGraphics(graphics)); } @Override public void paint(Graphics g) { super.paint(g); if (!isArrowVisible(myPresentation)) { return; } if (UIUtil.isUnderWin10LookAndFeel()) { Icon icon = getArrowIcon(isEnabled()); int x = getWidth() - icon.getIconWidth() - getInsets().right - getMargin().right - JBUIScale.scale(3); int y = (getHeight() - icon.getIconHeight()) / 2; icon.paintIcon(null, g, x, y); } else { Graphics2D g2 = (Graphics2D)g.create(); try { int iconSize = ICON_SIZE.get(); int x = getWidth() - iconSize - getInsets().right - getMargin().right; // Different icons correction int y = (getHeight() - iconSize)/2; g2.translate(x, y); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_NORMALIZE); g2.setColor(JBUI.CurrentTheme.Arrow.foregroundColor(isEnabled())); Path2D arrow = new Path2D.Float(Path2D.WIND_EVEN_ODD); arrow.moveTo(JBUIScale.scale(3.5f), JBUIScale.scale(6f)); arrow.lineTo(JBUIScale.scale(12.5f), JBUIScale.scale(6f)); arrow.lineTo(JBUIScale.scale(8f), JBUIScale.scale(11f)); arrow.closePath(); g2.fill(arrow); } finally { g2.dispose(); } } } protected boolean isArrowVisible(@NotNull Presentation presentation) { return true; } @Override public void updateUI() { super.updateUI(); setMargin(JBUI.insets(0, 5, 0, 2)); } /** * @deprecated This method is noop. Set icon, text and tooltip in the constructor * or property change listener for proper computation of preferred size. * Other updates happen in Swing. */ @Deprecated @ApiStatus.ScheduledForRemoval(inVersion = "2021.1") protected void updateButtonSize() {} @ApiStatus.Experimental protected void doShiftClick() { doClick(); } } protected Condition<AnAction> getPreselectCondition() { return null; } }
package com.intellij.ide.ui.laf.darcula.ui; import com.intellij.icons.AllIcons; import com.intellij.ide.ui.UISettings; import com.intellij.ide.ui.laf.darcula.DarculaLaf; import com.intellij.ide.ui.laf.darcula.DarculaUIUtil; import com.intellij.openapi.actionSystem.ex.ComboBoxAction; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.util.text.StringUtil; import com.intellij.ui.JBColor; import com.intellij.ui.components.JBOptionButton; import com.intellij.ui.scale.JBUIScale; import com.intellij.util.ObjectUtils; import com.intellij.util.ui.*; import javax.swing.*; import javax.swing.plaf.ComponentUI; import javax.swing.plaf.FontUIResource; import javax.swing.plaf.basic.BasicButtonUI; import javax.swing.plaf.basic.BasicGraphicsUtils; import javax.swing.plaf.basic.BasicHTML; import javax.swing.text.View; import java.awt.*; import java.awt.geom.Ellipse2D; import java.awt.geom.RoundRectangle2D; import static com.intellij.ide.ui.laf.darcula.DarculaUIUtil.BW; import static com.intellij.ide.ui.laf.darcula.DarculaUIUtil.MINIMUM_HEIGHT; /** * @author Konstantin Bulenkov */ @SuppressWarnings("UnregisteredNamedColor") public class DarculaButtonUI extends BasicButtonUI { private final Rectangle viewRect = new Rectangle(); private final Rectangle textRect = new Rectangle(); private final Rectangle iconRect = new Rectangle(); protected static JBValue HELP_BUTTON_DIAMETER = new JBValue.Float(22); protected static JBValue MINIMUM_BUTTON_WIDTH = new JBValue.Float(72); protected static JBValue HORIZONTAL_PADDING = new JBValue.Float(14); @SuppressWarnings({"MethodOverridesStaticMethodOfSuperclass", "unused"}) public static ComponentUI createUI(JComponent c) { return new DarculaButtonUI(); } public static boolean isSquare(Component c) { return c instanceof AbstractButton && "square".equals(((AbstractButton)c).getClientProperty("JButton.buttonType")); } public static boolean isDefaultButton(JComponent c) { return c instanceof JButton && ((JButton)c).isDefaultButton(); } public static boolean isSmallComboButton(Component c) { ComboBoxAction a = getComboAction(c); return a != null && a.isSmallVariant(); } public static ComboBoxAction getComboAction(Component c) { return c instanceof AbstractButton ? (ComboBoxAction)((JComponent)c).getClientProperty("styleCombo") : null; } @Override public void installDefaults(AbstractButton b) { super.installDefaults(b); b.setIconTextGap(textIconGap()); b.setMargin(JBUI.emptyInsets()); } protected int textIconGap() { return JBUIScale.scale(4); } /** * Paints additional buttons decorations * * @param g Graphics * @param c button component * @return {@code true} if it is allowed to continue painting, * {@code false} if painting should be stopped */ @SuppressWarnings("UseJBColor") protected boolean paintDecorations(Graphics2D g, JComponent c) { Rectangle r = new Rectangle(c.getSize()); JBInsets.removeFrom(r, JBUI.insets(1)); if (UIUtil.isHelpButton(c)) { g.setPaint(UIUtil.getGradientPaint(0, 0, getButtonColorStart(), 0, r.height, getButtonColorEnd())); int diam = HELP_BUTTON_DIAMETER.get(); int x = r.x + (r.width - diam) / 2; int y = r.x + (r.height - diam) / 2; g.fill(new Ellipse2D.Float(x, y, diam, diam)); AllIcons.Actions.Help.paintIcon(c, g, x + JBUIScale.scale(3), y + JBUIScale.scale(3)); return false; } else { Graphics2D g2 = (Graphics2D)g.create(); try { g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, MacUIUtil.USE_QUARTZ ? RenderingHints.VALUE_STROKE_PURE : RenderingHints.VALUE_STROKE_NORMALIZE); g2.translate(r.x, r.y); float arc = DarculaUIUtil.BUTTON_ARC.getFloat(); float bw = isSmallComboButton(c) ? 0 : BW.getFloat(); if (!c.hasFocus() && !isSmallComboButton(c) && c.isEnabled() && UIManager.getBoolean("Button.paintShadow")) { Color shadowColor = JBColor.namedColor("Button.shadowColor", JBColor.namedColor("Button.darcula.shadowColor", new JBColor(new Color(0xa6a6a633, true), new Color(0x36363680, true)))); int shadowWidth = JBUIScale.scale(JBUI.getInt("Button.shadowWidth", 2)); g2.setColor(isDefaultButton(c) ? JBColor.namedColor("Button.default.shadowColor", shadowColor) : shadowColor); g2.fill(new RoundRectangle2D.Float(bw, bw + shadowWidth, r.width - bw * 2, r.height - bw * 2, arc, arc)); } if (c.isEnabled()) { g2.setPaint(getBackground(c, r)); g2.fill(new RoundRectangle2D.Float(bw, bw, r.width - bw * 2, r.height - bw * 2, arc, arc)); } } finally { g2.dispose(); } return true; } } private Paint getBackground(JComponent c, Rectangle r) { Color backgroundColor = (Color)c.getClientProperty("JButton.backgroundColor"); return backgroundColor != null ? backgroundColor : isSmallComboButton(c) ? JBColor.namedColor("ComboBoxButton.background", JBColor.namedColor("Button.darcula.smallComboButtonBackground", UIUtil.getPanelBackground())) : isDefaultButton(c) ? UIUtil.getGradientPaint(0, 0, getDefaultButtonColorStart(), 0, r.height, getDefaultButtonColorEnd()) : UIUtil.getGradientPaint(0, 0, getButtonColorStart(), 0, r.height, getButtonColorEnd()); } @Override public void paint(Graphics g, JComponent c) { if (paintDecorations((Graphics2D)g, c)) { paintContents(g, (AbstractButton)c); } } @Override protected void paintText(Graphics g, JComponent c, Rectangle textRect, String text) { if (UIUtil.isHelpButton(c)) { return; } AbstractButton button = (AbstractButton)c; ButtonModel model = button.getModel(); g.setColor(getButtonTextColor(button)); FontMetrics metrics = UIUtilities.getFontMetrics(c, g); int mnemonicIndex = DarculaLaf.isAltPressed() ? button.getDisplayedMnemonicIndex() : -1; if (model.isEnabled()) { UIUtilities.drawStringUnderlineCharAt( c, g, text, mnemonicIndex, textRect.x + getTextShiftOffset(), textRect.y + metrics.getAscent() + getTextShiftOffset()); } else { paintDisabledText(g, text, c, textRect, metrics); } } protected Color getButtonTextColor(AbstractButton button) { Color textColor = (Color)button.getClientProperty("JButton.textColor"); return textColor != null ? textColor : DarculaUIUtil.getButtonTextColor(button); } public static Color getDisabledTextColor() { return UIManager.getColor("Button.disabledText"); } protected void paintDisabledText(Graphics g, String text, JComponent c, Rectangle textRect, FontMetrics metrics) { g.setColor(UIManager.getColor("Button.disabledText")); UIUtilities.drawStringUnderlineCharAt( c, g, text, -1, textRect.x + getTextShiftOffset(), textRect.y + metrics.getAscent() + getTextShiftOffset()); } protected void paintContents(Graphics g, AbstractButton b) { if (b instanceof JBOptionButton) return; FontMetrics fm = UIUtilities.getFontMetrics(b, g); boolean isDotButton = isSquare(b) && b.getIcon() == AllIcons.General.Ellipsis; String text = isDotButton ? "..." : b.getText(); Icon icon = isDotButton ? null : b.getIcon(); text = layout(b, text, icon, fm, b.getWidth(), b.getHeight()); if (isSquare(b)) { if (b.getIcon() == AllIcons.General.Ellipsis) { UISettings.setupAntialiasing(g); paintText(g, b, textRect, text); } else if (b.getIcon() != null) { paintIcon(g, b, iconRect); } } else { // Paint the Icon if (b.getIcon() != null) { paintIcon(g, b, iconRect); } if (text != null && !text.isEmpty()) { View v = (View)b.getClientProperty(BasicHTML.propertyKey); if (v != null) { v.paint(g, textRect); } else { UISettings.setupAntialiasing(g); paintText(g, b, textRect, text); } } } } protected Dimension getDarculaButtonSize(JComponent c, Dimension prefSize) { Insets i = c.getInsets(); prefSize = ObjectUtils.notNull(prefSize, JBUI.emptySize()); if (UIUtil.isHelpButton(c) || isSquare(c)) { int helpDiam = HELP_BUTTON_DIAMETER.get(); return new Dimension(Math.max(prefSize.width, helpDiam + i.left + i.right), Math.max(prefSize.height, helpDiam + i.top + i.bottom)); } else { int width = getComboAction(c) != null ? prefSize.width : Math.max(HORIZONTAL_PADDING.get() * 2 + prefSize.width, MINIMUM_BUTTON_WIDTH.get() + i.left + i.right); int height = Math.max(prefSize.height, getMinimumHeight() + i.top + i.bottom); return new Dimension(width, height); } } protected int getMinimumHeight() { return MINIMUM_HEIGHT.get(); } @Override public final Dimension getPreferredSize(JComponent c) { AbstractButton b = (AbstractButton)c; int textIconGap = StringUtil.isEmpty(b.getText()) || b.getIcon() == null ? 0 : b.getIconTextGap(); Dimension size = BasicGraphicsUtils.getPreferredButtonSize(b, textIconGap); return getDarculaButtonSize(c, size); } @Override public void update(Graphics g, JComponent c) { setupDefaultButton(c, g); super.update(g, c); } protected void setupDefaultButton(JComponent button, Graphics g) { Font f = button.getFont(); if (!SystemInfo.isMac && f instanceof FontUIResource && isDefaultButton(button)) { g.setFont(f.deriveFont(Font.BOLD)); } } protected Color getButtonColorStart() { return JBColor.namedColor("Button.startBackground", JBColor.namedColor("Button.darcula.startColor", 0x555a5c)); } protected Color getButtonColorEnd() { return JBColor.namedColor("Button.endBackground", JBColor.namedColor("Button.darcula.endColor", 0x414648)); } protected Color getDefaultButtonColorStart() { return JBColor.namedColor("Button.default.startBackground", JBColor.namedColor("Button.darcula.defaultStartColor", 0x384f6b)); } protected Color getDefaultButtonColorEnd() { return JBColor.namedColor("Button.default.endBackground", JBColor.namedColor("Button.darcula.defaultEndColor", 0x233143)); } protected String layout(AbstractButton b, String text, Icon icon, FontMetrics fm, int width, int height) { textRect.setBounds(0, 0, 0, 0); iconRect.setBounds(0, 0, 0, 0); viewRect.setBounds(0, 0, width, height); modifyViewRect(b, viewRect); // layout the text and icon return SwingUtilities.layoutCompoundLabel( b, fm, text, icon, b.getVerticalAlignment(), b.getHorizontalAlignment(), b.getVerticalTextPosition(), b.getHorizontalTextPosition(), viewRect, iconRect, textRect, StringUtil.isEmpty(text) || icon == null ? 0 : b.getIconTextGap()); } protected void modifyViewRect(AbstractButton b, Rectangle rect) { JBInsets.removeFrom(rect, b.getInsets()); JBInsets.removeFrom(rect, b.getMargin()); } }
package com.intellij.openapi.ui.impl; import com.intellij.ide.DataManager; import com.intellij.ide.IdeEventQueue; import com.intellij.ide.impl.TypeSafeDataProviderAdapter; import com.intellij.ide.ui.AntialiasingType; import com.intellij.ide.ui.UISettings; import com.intellij.jdkEx.JdkEx; import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.impl.LaterInvocator; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.command.CommandProcessorEx; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.DumbAware; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.ui.DialogWrapperDialog; import com.intellij.openapi.ui.DialogWrapperPeer; import com.intellij.openapi.ui.Queryable; import com.intellij.openapi.ui.popup.StackingPopupDispatcher; import com.intellij.openapi.util.*; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.wm.IdeFocusManager; import com.intellij.openapi.wm.IdeFrame; import com.intellij.openapi.wm.WindowManager; import com.intellij.openapi.wm.ex.LayoutFocusTraversalPolicyExt; import com.intellij.openapi.wm.ex.WindowManagerEx; import com.intellij.openapi.wm.impl.IdeFrameDecorator; import com.intellij.openapi.wm.impl.ProjectFrameHelper; import com.intellij.openapi.wm.impl.IdeGlassPaneImpl; import com.intellij.openapi.wm.impl.IdeFrameImpl; import com.intellij.openapi.wm.impl.customFrameDecorations.header.CustomFrameDialogContent; import com.intellij.reference.SoftReference; import com.intellij.ui.*; import com.intellij.ui.components.JBLayeredPane; import com.intellij.ui.mac.touchbar.TouchBarsManager; import com.intellij.util.IJSwingUtilities; import com.intellij.util.ui.GraphicsUtil; import com.intellij.util.ui.JBInsets; import com.intellij.util.ui.OwnerOptional; import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.awt.image.BufferStrategy; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.List; import java.util.Map; public class DialogWrapperPeerImpl extends DialogWrapperPeer { private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.ui.DialogWrapper"); public static boolean isHeadlessEnv() { Application app = ApplicationManager.getApplication(); return app == null ? GraphicsEnvironment.isHeadless() : app.isUnitTestMode() || app.isHeadlessEnvironment(); } private final DialogWrapper myWrapper; private final AbstractDialog myDialog; private final boolean myCanBeParent; private final WindowManagerEx myWindowManager; private final List<Runnable> myDisposeActions = new ArrayList<>(); private Project myProject; protected DialogWrapperPeerImpl(@NotNull DialogWrapper wrapper, @Nullable Project project, boolean canBeParent, @NotNull DialogWrapper.IdeModalityType ideModalityType) { boolean headless = isHeadlessEnv(); myWrapper = wrapper; myWindowManager = getWindowManager(); Window window = null; if (myWindowManager != null) { if (project == null) { //noinspection deprecation project = CommonDataKeys.PROJECT.getData(DataManager.getInstance().getDataContext()); } myProject = project; window = myWindowManager.suggestParentWindow(project); if (window == null) { Window focusedWindow = myWindowManager.getMostRecentFocusedWindow(); if (focusedWindow instanceof IdeFrameImpl) { window = focusedWindow; } } if (window == null) { IdeFrame[] frames = myWindowManager.getAllProjectFrames(); for (IdeFrame frame : frames) { if (frame instanceof ProjectFrameHelper && ((ProjectFrameHelper)frame).getFrame().isActive()) { window = ((ProjectFrameHelper)frame).getFrame(); break; } } } } Window owner; if (window != null) { owner = window; } else if (!headless) { owner = JOptionPane.getRootFrame(); } else { owner = null; } myDialog = createDialog(headless, owner, wrapper, myProject, ideModalityType); myCanBeParent = headless || canBeParent; } /** * Creates modal {@code DialogWrapper}. The currently active window will be the dialog's parent. * * @param project parent window for the dialog will be calculated based on focused window for the * specified {@code project}. This parameter can be {@code null}. In this case parent window * will be suggested based on current focused window. * @param canBeParent specifies whether the dialog can be parent for other windows. This parameter is used * by {@code WindowManager}. */ protected DialogWrapperPeerImpl(@NotNull DialogWrapper wrapper, @Nullable Project project, boolean canBeParent) { this(wrapper, project, canBeParent, DialogWrapper.IdeModalityType.IDE); } protected DialogWrapperPeerImpl(@NotNull DialogWrapper wrapper, boolean canBeParent) { this(wrapper, (Project)null, canBeParent); } /** * @param parent parent component (must be showing) which is used to calculate heavy weight window ancestor. */ protected DialogWrapperPeerImpl(@NotNull DialogWrapper wrapper, @NotNull Component parent, boolean canBeParent) { boolean headless = isHeadlessEnv(); myWrapper = wrapper; myWindowManager = getWindowManager(); myDialog = createDialog(headless, OwnerOptional.fromComponent(parent).get(), wrapper, null, DialogWrapper.IdeModalityType.IDE); myCanBeParent = headless || canBeParent; } protected DialogWrapperPeerImpl(@NotNull DialogWrapper wrapper, Window owner, boolean canBeParent, DialogWrapper.IdeModalityType ideModalityType) { boolean headless = isHeadlessEnv(); myWrapper = wrapper; myWindowManager = getWindowManager(); myDialog = createDialog(headless, owner, wrapper, null, DialogWrapper.IdeModalityType.IDE); myCanBeParent = headless || canBeParent; if (!headless) { Dialog.ModalityType modalityType = DialogWrapper.IdeModalityType.IDE.toAwtModality(); if (Registry.is("ide.perProjectModality", false)) { modalityType = ideModalityType.toAwtModality(); } myDialog.setModalityType(modalityType); } } private static WindowManagerEx getWindowManager() { WindowManagerEx windowManager = null; Application application = ApplicationManager.getApplication(); if (application != null) { windowManager = (WindowManagerEx)application.getComponent(WindowManager.class); } return windowManager; } private static AbstractDialog createDialog(boolean headless, Window owner, DialogWrapper wrapper, Project project, DialogWrapper.IdeModalityType ideModalityType) { if (headless) { return new HeadlessDialog(wrapper); } else { ActionCallback focused = new ActionCallback("DialogFocusedCallback"); MyDialog dialog = new MyDialog(OwnerOptional.fromComponent(owner).get(), wrapper, project, focused); dialog.setModalityType(ideModalityType.toAwtModality()); return dialog; } } @Override public boolean isHeadless() { return myDialog instanceof HeadlessDialog; } @Override public Object[] getCurrentModalEntities() { return LaterInvocator.getCurrentModalEntities(); } @Override public void setUndecorated(boolean undecorated) { myDialog.setUndecorated(undecorated); } @Override public void addMouseListener(MouseListener listener) { myDialog.addMouseListener(listener); } @Override public void addMouseListener(MouseMotionListener listener) { myDialog.addMouseMotionListener(listener); } @Override public void addKeyListener(KeyListener listener) { myDialog.addKeyListener(listener); } @Override public void toFront() { myDialog.toFront(); } @Override public void toBack() { myDialog.toBack(); } @Override @SuppressWarnings("SSBasedInspection") protected void dispose() { LOG.assertTrue(EventQueue.isDispatchThread(), "Access is allowed from event dispatch thread only"); for (Runnable runnable : myDisposeActions) { runnable.run(); } myDisposeActions.clear(); Runnable disposer = () -> { Disposer.dispose(myDialog); myProject = null; SwingUtilities.invokeLater(() -> { if (myDialog.getRootPane() != null) { myDialog.remove(myDialog.getRootPane()); } }); }; UIUtil.invokeLaterIfNeeded(disposer); } private boolean isProgressDialog() { return myWrapper.isModalProgress(); } @Override @Nullable public Container getContentPane() { return getRootPane() != null ? myDialog.getContentPane() : null; } /** * @see JDialog#validate */ @Override public void validate() { myDialog.validate(); } /** * @see JDialog#repaint */ @Override public void repaint() { myDialog.repaint(); } @Override public Window getOwner() { return myDialog.getOwner(); } @Override public Window getWindow() { return myDialog.getWindow(); } @Override public JRootPane getRootPane() { return myDialog.getRootPane(); } @Override public Dimension getSize() { return myDialog.getSize(); } @Override public String getTitle() { return myDialog.getTitle(); } /** * @see Window#pack */ @Override public void pack() { myDialog.pack(); } @Override public void setAppIcons() { AppUIUtil.updateWindowIcon(getWindow()); } @Override public Dimension getPreferredSize() { return myDialog.getPreferredSize(); } @Override public void setModal(boolean modal) { myDialog.setModal(modal); } @Override public boolean isModal() { return myDialog.isModal(); } @Override public boolean isVisible() { return myDialog.isVisible(); } @Override public boolean isShowing() { return myDialog.isShowing(); } @Override public void setSize(int width, int height) { myDialog.setSize(width, height); } @Override public void setTitle(String title) { myDialog.setTitle(title); } @Override public void isResizable() { myDialog.isResizable(); } @Override public void setResizable(boolean resizable) { myDialog.setResizable(resizable); } @NotNull @Override public Point getLocation() { return myDialog.getLocation(); } @Override public void setLocation(@NotNull Point p) { myDialog.setLocation(p); } @Override public void setLocation(int x, int y) { myDialog.setLocation(x, y); } @Override public ActionCallback show() { LOG.assertTrue(EventQueue.isDispatchThread(), "Access is allowed from event dispatch thread only"); final ActionCallback result = new ActionCallback(); final AnCancelAction anCancelAction = new AnCancelAction(); final JRootPane rootPane = getRootPane(); UIUtil.decorateWindowHeader(rootPane); Window window = getWindow(); if (window instanceof JDialog && !((JDialog)window).isUndecorated()) { UIUtil.setCustomTitleBar(window, rootPane, runnable -> Disposer.register(myWrapper.getDisposable(), () -> runnable.run())); } Container contentPane = getContentPane(); if (IdeFrameDecorator.isCustomDecorationActive() && contentPane instanceof JComponent) { setContentPane(CustomFrameDialogContent.getContent(window, (JComponent) contentPane)); } anCancelAction.registerCustomShortcutSet(CommonShortcuts.ESCAPE, rootPane); myDisposeActions.add(() -> anCancelAction.unregisterCustomShortcutSet(rootPane)); if (!myCanBeParent && myWindowManager != null) { myWindowManager.doNotSuggestAsParent(myDialog.getWindow()); } final CommandProcessorEx commandProcessor = ApplicationManager.getApplication() != null ? (CommandProcessorEx)CommandProcessor.getInstance() : null; final boolean appStarted = commandProcessor != null; boolean changeModalityState = appStarted && myDialog.isModal() && !isProgressDialog(); // ProgressWindow starts a modality state itself Project project = myProject; boolean perProjectModality = Registry.is("ide.perProjectModality", false); if (changeModalityState) { commandProcessor.enterModal(); if (perProjectModality) { LaterInvocator.enterModal(project, myDialog.getWindow()); } else { LaterInvocator.enterModal(myDialog); } } if (appStarted) { hidePopupsIfNeeded(); } myDialog.getWindow().setAutoRequestFocus(!UIUtil.SUPPRESS_FOCUS_STEALING); if (SystemInfo.isMac) { final Disposable tb = TouchBarsManager.showDialogWrapperButtons(myDialog.getContentPane()); if (tb != null) { myDisposeActions.add(() -> Disposer.dispose(tb)); } } try { myDialog.show(); } finally { if (changeModalityState) { commandProcessor.leaveModal(); if (perProjectModality) { LaterInvocator.leaveModal(project, myDialog.getWindow()); } else { LaterInvocator.leaveModal(myDialog); } } myDialog.getFocusManager().doWhenFocusSettlesDown(result.createSetDoneRunnable()); } return result; } //hopefully this whole code will go away private void hidePopupsIfNeeded() { if (!SystemInfo.isMac) return; StackingPopupDispatcher.getInstance().hidePersistentPopups(); myDisposeActions.add(() -> StackingPopupDispatcher.getInstance().restorePersistentPopups()); } private class AnCancelAction extends AnAction implements DumbAware { @Override public void update(@NotNull AnActionEvent e) { Component focusOwner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner(); e.getPresentation().setEnabled(false); if (focusOwner instanceof JComponent && SpeedSearchBase.hasActiveSpeedSearch((JComponent)focusOwner)) { return; } if (StackingPopupDispatcher.getInstance().isPopupFocused()) return; JTree tree = ComponentUtil.getParentOfType((Class<? extends JTree>)JTree.class, focusOwner); JTable table = ComponentUtil.getParentOfType((Class<? extends JTable>)JTable.class, focusOwner); if (tree != null || table != null) { if (hasNoEditingTreesOrTablesUpward(focusOwner)) { e.getPresentation().setEnabled(true); } } } private boolean hasNoEditingTreesOrTablesUpward(Component comp) { while (comp != null) { if (isEditingTreeOrTable(comp)) return false; comp = comp.getParent(); } return true; } private boolean isEditingTreeOrTable(Component comp) { if (comp instanceof JTree) { return ((JTree)comp).isEditing(); } else if (comp instanceof JTable) { return ((JTable)comp).isEditing(); } return false; } @Override public void actionPerformed(@NotNull AnActionEvent e) { myWrapper.doCancelAction(e.getInputEvent()); } } private static class MyDialog extends JDialog implements DialogWrapperDialog, DataProvider, Queryable, AbstractDialog { private final WeakReference<DialogWrapper> myDialogWrapper; /** * Initial size of the dialog. When the dialog is being closed and * current size of the dialog is not equals to the initial size then the * current (changed) size is stored in the {@code DimensionService}. */ private Dimension myInitialSize; private String myDimensionServiceKey; private boolean myOpened = false; private boolean myActivated = false; private MyDialog.MyWindowListener myWindowListener; private final WeakReference<Project> myProject; private final ActionCallback myFocusedCallback; MyDialog(Window owner, DialogWrapper dialogWrapper, Project project, @NotNull ActionCallback focused) { super(owner); UIUtil.markAsTypeAheadAware(this); myDialogWrapper = new WeakReference<>(dialogWrapper); myProject = project != null ? new WeakReference<>(project) : null; setFocusTraversalPolicy(new LayoutFocusTraversalPolicyExt() { @Override protected boolean accept(Component aComponent) { if (UIUtil.isFocusProxy(aComponent)) return false; return super.accept(aComponent); } }); myFocusedCallback = focused; final long typeAhead = getDialogWrapper().getTypeAheadTimeoutMs(); setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); myWindowListener = new MyWindowListener(); addWindowListener(myWindowListener); UIUtil.setAutoRequestFocus(this, !UIUtil.SUPPRESS_FOCUS_STEALING); } /** * @deprecated use {@link MyDialog#MyDialog(Window, DialogWrapper, Project, ActionCallback)} */ @Deprecated MyDialog(Window owner, DialogWrapper dialogWrapper, Project project, @NotNull ActionCallback focused, @NotNull ActionCallback typeAheadDone, ActionCallback typeAheadCallback) { this(owner, dialogWrapper, project, focused); } @Override public JDialog getWindow() { return this; } @Override public void putInfo(@NotNull Map<String, String> info) { info.put("dialog", getTitle()); } @Override public DialogWrapper getDialogWrapper() { return myDialogWrapper.get(); } @Override public void centerInParent() { setLocationRelativeTo(getOwner()); } @Override public Object getData(@NotNull String dataId) { final DialogWrapper wrapper = myDialogWrapper.get(); if (wrapper instanceof DataProvider) { return ((DataProvider)wrapper).getData(dataId); } if (wrapper instanceof TypeSafeDataProvider) { TypeSafeDataProviderAdapter adapter = new TypeSafeDataProviderAdapter((TypeSafeDataProvider)wrapper); return adapter.getData(dataId); } return null; } @Override public void setSize(int width, int height) { _setSizeForLocation(width, height, null); } private void _setSizeForLocation(int width, int height, @Nullable Point initial) { Point location = initial != null ? initial : getLocation(); Rectangle rect = new Rectangle(location.x, location.y, width, height); ScreenUtil.fitToScreen(rect); if (initial != null || location.x != rect.x || location.y != rect.y) { setLocation(rect.x, rect.y); } super.setSize(rect.width, rect.height); } @Override public void setBounds(int x, int y, int width, int height) { Rectangle rect = new Rectangle(x, y, width, height); ScreenUtil.fitToScreen(rect); super.setBounds(rect.x, rect.y, rect.width, rect.height); } @Override public void setBounds(Rectangle r) { ScreenUtil.fitToScreen(r); super.setBounds(r); } @NotNull @Override protected JRootPane createRootPane() { return new DialogRootPane(); } @Override public void addNotify() { if (IdeFrameDecorator.isCustomDecorationActive()) { JdkEx.setHasCustomDecoration(this); } super.addNotify(); } @Override @SuppressWarnings("deprecation") public void show() { final DialogWrapper dialogWrapper = getDialogWrapper(); boolean isAutoAdjustable = dialogWrapper.isAutoAdjustable(); Point location = null; if (isAutoAdjustable) { pack(); Dimension packedSize = getSize(); Dimension minSize = getMinimumSize(); setSize(Math.max(packedSize.width, minSize.width), Math.max(packedSize.height, minSize.height)); setSize((int)(getWidth() * dialogWrapper.getHorizontalStretch()), (int)(getHeight() * dialogWrapper.getVerticalStretch())); // Restore dialog's size and location myDimensionServiceKey = dialogWrapper.getDimensionKey(); if (myDimensionServiceKey != null) { final Project projectGuess = CommonDataKeys.PROJECT.getData(DataManager.getInstance().getDataContext(this)); location = getWindowStateService(projectGuess).getLocation(myDimensionServiceKey); //if (location == null) location = DimensionService.getInstance().getLocation(myDimensionServiceKey, projectGuess); Dimension size = getWindowStateService(projectGuess).getSize(myDimensionServiceKey); //if (size == null) size = DimensionService.getInstance().getSize(myDimensionServiceKey, projectGuess); if (size != null) { myInitialSize = new Dimension(size); _setSizeForLocation(myInitialSize.width, myInitialSize.height, location); } } if (myInitialSize == null) { myInitialSize = getSize(); } } if (location == null) { location = dialogWrapper.getInitialLocation(); } if (location != null) { setLocation(location); } else { setLocationRelativeTo(getOwner()); } if (isAutoAdjustable) { final Rectangle bounds = getBounds(); ScreenUtil.fitToScreen(bounds); setBounds(bounds); } if (Registry.is("actionSystem.fixLostTyping", true)) { final IdeEventQueue queue = IdeEventQueue.getInstance(); if (queue != null) { queue.getKeyEventDispatcher().resetState(); } } // Workaround for switching workspaces on dialog show if (SystemInfo.isMac && myProject != null && Registry.is("ide.mac.fix.dialog.showing", false) && !dialogWrapper.isModalProgress()) { final IdeFrame frame = WindowManager.getInstance().getIdeFrame(myProject.get()); AppIcon.getInstance().requestFocus(frame); } setBackground(UIUtil.getPanelBackground()); super.show(); } @Nullable private Project getProject() { return SoftReference.dereference(myProject); } @NotNull @Override public IdeFocusManager getFocusManager() { Project project = getProject(); if (project != null && !project.isDisposed()) { return IdeFocusManager.getInstance(project); } else { return IdeFocusManager.findInstance(); } } @Override @SuppressWarnings("deprecation") public void hide() { super.hide(); } @Override public void dispose() { if (isShowing()) { hide(); } if (myWindowListener != null) { myWindowListener.saveSize(); removeWindowListener(myWindowListener); myWindowListener = null; } DialogWrapper wrapper = getDialogWrapper(); if (wrapper != null) wrapper.disposeIfNeeded(); final BufferStrategy strategy = getBufferStrategy(); if (strategy != null) { strategy.dispose(); } super.dispose(); removeAll(); DialogWrapper.cleanupRootPane(rootPane); DialogWrapper.cleanupWindowListeners(this); rootPane = null; } @Override public Component getMostRecentFocusOwner() { if (!myOpened) { final DialogWrapper wrapper = getDialogWrapper(); if (wrapper != null) { JComponent toFocus = wrapper.getPreferredFocusedComponent(); if (toFocus != null) { return toFocus; } } } return super.getMostRecentFocusOwner(); } @Override public void paint(Graphics g) { if (!SystemInfo.isMac) { // avoid rendering problems with non-aqua (alloy) LaFs under mac // actually, it's a bad idea to globally enable this for dialog graphics since renderers, for example, may not // inherit graphics so rendering hints won't be applied and trees or lists may render ugly. UISettings.setupAntialiasing(g); } super.paint(g); } @SuppressWarnings("SSBasedInspection") private class MyWindowListener extends WindowAdapter { @Override public void windowClosing(WindowEvent e) { DialogWrapper dialogWrapper = getDialogWrapper(); if (dialogWrapper.shouldCloseOnCross()) { dialogWrapper.doCancelAction(e); } } @Override public void windowClosed(WindowEvent e) { saveSize(); } public void saveSize() { if (myDimensionServiceKey != null && myInitialSize != null && myOpened) { // myInitialSize can be null only if dialog is disposed before first showing final Project projectGuess = CommonDataKeys.PROJECT.getData(DataManager.getInstance().getDataContext(MyDialog.this)); // Save location Point location = getLocation(); getWindowStateService(projectGuess).putLocation(myDimensionServiceKey, location); DimensionService.getInstance().setLocation(myDimensionServiceKey, location, projectGuess); // Save size Dimension size = getSize(); if (!myInitialSize.equals(size)) { getWindowStateService(projectGuess).putSize(myDimensionServiceKey, size); DimensionService.getInstance().setSize(myDimensionServiceKey, size, projectGuess); } myOpened = false; } } @Override public void windowOpened(final WindowEvent e) { SwingUtilities.invokeLater(() -> { myOpened = true; final DialogWrapper activeWrapper = getActiveWrapper(); UIUtil.uiTraverser(e.getWindow()).filter(JComponent.class).consumeEach(c -> { GraphicsUtil.setAntialiasingType(c, AntialiasingType.getAAHintForSwingComponent()); c.invalidate(); }); JComponent rootPane = ((JDialog)e.getComponent()).getRootPane(); if (rootPane != null) { rootPane.revalidate(); } e.getComponent().repaint(); if (activeWrapper == null) { myFocusedCallback.setRejected(); } final DialogWrapper wrapper = getActiveWrapper(); if (wrapper == null && !myFocusedCallback.isProcessed()) { myFocusedCallback.setRejected(); return; } if (myActivated) { return; } myActivated = true; JComponent toFocus = wrapper == null ? null : wrapper.getPreferredFocusedComponent(); if (getRootPane() != null && toFocus == null) { toFocus = getRootPane().getDefaultButton(); } if (getRootPane() != null) { IJSwingUtilities.moveMousePointerOn(getRootPane().getDefaultButton()); } setupSelectionOnPreferredComponent(toFocus); if (toFocus != null) { if (isShowing() && (ApplicationManager.getApplication() == null || ApplicationManager.getApplication().isActive())) { toFocus.requestFocus(); } else { toFocus.requestFocusInWindow(); } notifyFocused(wrapper); } else { if (isShowing()) { notifyFocused(wrapper); } } }); } private void notifyFocused(DialogWrapper wrapper) { myFocusedCallback.setDone(); } private DialogWrapper getActiveWrapper() { DialogWrapper activeWrapper = getDialogWrapper(); if (activeWrapper == null || !activeWrapper.isShowing()) { return null; } return activeWrapper; } } private class DialogRootPane extends JRootPane implements DataProvider { private final boolean myGlassPaneIsSet; private Dimension myLastMinimumSize; private DialogRootPane() { setGlassPane(new IdeGlassPaneImpl(this)); myGlassPaneIsSet = true; putClientProperty("DIALOG_ROOT_PANE", true); setBorder(UIManager.getBorder("Window.border")); } @NotNull @Override protected JLayeredPane createLayeredPane() { JLayeredPane p = new JBLayeredPane(); p.setName(this.getName()+".layeredPane"); return p; } @Override public void validate() { super.validate(); DialogWrapper wrapper = myDialogWrapper.get(); if (wrapper != null && wrapper.isAutoAdjustable()) { Window window = wrapper.getWindow(); if (window != null) { Dimension size = getMinimumSize(); if (!(size == null ? myLastMinimumSize == null : size.equals(myLastMinimumSize))) { // update window minimum size only if root pane minimum size is changed if (size == null) { myLastMinimumSize = null; } else { myLastMinimumSize = new Dimension(size); JBInsets.addTo(size, window.getInsets()); Rectangle screen = ScreenUtil.getScreenRectangle(window); if (size.width > screen.width || size.height > screen.height) { Application application = ApplicationManager.getApplication(); if (application != null && application.isInternal()) { LOG.warn("minimum size " + size.width + "x" + size.height + " is bigger than screen " + screen.width + "x" + screen.height); } if (size.width > screen.width) size.width = screen.width; if (size.height > screen.height) size.height = screen.height; } } window.setMinimumSize(size); } } } } @Override public void setGlassPane(final Component glass) { if (myGlassPaneIsSet) { LOG.warn("Setting of glass pane for DialogWrapper is prohibited", new Exception()); return; } super.setGlassPane(glass); } @Override public void setContentPane(Container contentPane) { super.setContentPane(contentPane); if (contentPane != null) { contentPane.addMouseMotionListener(new MouseMotionAdapter() {}); // listen to mouse motino events for a11y } } @Override public Object getData(@NotNull @NonNls String dataId) { final DialogWrapper wrapper = myDialogWrapper.get(); return wrapper != null && PlatformDataKeys.UI_DISPOSABLE.is(dataId) ? wrapper.getDisposable() : null; } } @NotNull private static WindowStateService getWindowStateService(@Nullable Project project) { return project == null ? WindowStateService.getInstance() : WindowStateService.getInstance(project); } } private static void setupSelectionOnPreferredComponent(final JComponent component) { if (component instanceof JTextField) { JTextField field = (JTextField)component; String text = field.getText(); if (text != null && field.getClientProperty(HAVE_INITIAL_SELECTION) == null) { field.setSelectionStart(0); field.setSelectionEnd(text.length()); } } else if (component instanceof JComboBox) { JComboBox combobox = (JComboBox)component; combobox.getEditor().selectAll(); } } @Override public void setContentPane(JComponent content) { myDialog.setContentPane(content); } @Override public void centerInParent() { myDialog.centerInParent(); } public void setAutoRequestFocus(boolean b) { UIUtil.setAutoRequestFocus((JDialog)myDialog, b); } }
package com.intellij.openapi.vfs.newvfs; import com.intellij.codeInsight.daemon.impl.FileStatusMap; import com.intellij.openapi.application.*; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileManager; import com.intellij.openapi.vfs.ex.VirtualFileManagerEx; import com.intellij.openapi.vfs.impl.local.LocalFileSystemImpl; import com.intellij.openapi.vfs.newvfs.events.VFileEvent; import com.intellij.openapi.vfs.newvfs.persistent.PersistentFS; import com.intellij.openapi.vfs.newvfs.persistent.RefreshWorker; import com.intellij.util.concurrency.Semaphore; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; import java.util.concurrent.atomic.AtomicLong; /** * @author max */ public class RefreshSessionImpl extends RefreshSession { private static final Logger LOG = Logger.getInstance(RefreshSession.class); private static final AtomicLong ID_COUNTER = new AtomicLong(0); private final long myId = ID_COUNTER.incrementAndGet(); private final boolean myIsAsync; private final boolean myIsRecursive; private final Runnable myFinishRunnable; private final Throwable myStartTrace; private final Semaphore mySemaphore = new Semaphore(); private List<VirtualFile> myWorkQueue = new ArrayList<>(); private List<VFileEvent> myEvents = new ArrayList<>(); private volatile boolean myHaveEventsToFire; private volatile RefreshWorker myWorker; private volatile boolean myCancelled; private final TransactionId myTransaction; RefreshSessionImpl(boolean async, boolean recursive, @Nullable Runnable finishRunnable, @NotNull ModalityState context) { myIsAsync = async; myIsRecursive = recursive; myFinishRunnable = finishRunnable; myTransaction = ((TransactionGuardImpl)TransactionGuard.getInstance()).getModalityTransaction(context); LOG.assertTrue(context == ModalityState.NON_MODAL || context != ModalityState.any(), "Refresh session should have a specific modality"); myStartTrace = rememberStartTrace(); } private Throwable rememberStartTrace() { if (ApplicationManager.getApplication().isUnitTestMode() && (myIsAsync || !ApplicationManager.getApplication().isDispatchThread())) { return new Throwable(); } return null; } RefreshSessionImpl(@NotNull List<? extends VFileEvent> events) { this(false, false, null, ModalityState.defaultModalityState()); myEvents.addAll(events); } @Override public long getId() { return myId; } @Override public void addAllFiles(@NotNull Collection<? extends VirtualFile> files) { for (VirtualFile file : files) { if (file == null) { LOG.error("null passed among " + files); } else { addFile(file); } } } @Override public void addFile(@NotNull VirtualFile file) { if (file instanceof NewVirtualFile) { myWorkQueue.add(file); } else { LOG.debug("skipped: " + file + " / " + file.getClass()); } } @Override public boolean isAsynchronous() { return myIsAsync; } @Override public void launch() { mySemaphore.down(); ((RefreshQueueImpl)RefreshQueue.getInstance()).execute(this); } public void scan() { List<VirtualFile> workQueue = myWorkQueue; myWorkQueue = new ArrayList<>(); boolean haveEventsToFire = myFinishRunnable != null || !myEvents.isEmpty(); boolean forceRefresh = !myIsRecursive && !myIsAsync; // shallow sync refresh (e.g. project config files on open) if (!workQueue.isEmpty()) { LocalFileSystem fs = LocalFileSystem.getInstance(); if (!forceRefresh && fs instanceof LocalFileSystemImpl) { ((LocalFileSystemImpl)fs).markSuspiciousFilesDirty(workQueue); } long t = 0; if (LOG.isTraceEnabled()) { LOG.trace("scanning " + workQueue); t = System.currentTimeMillis(); } int count = 0; refresh: do { if (LOG.isTraceEnabled()) LOG.trace("try=" + count); for (VirtualFile file : workQueue) { if (myCancelled) break refresh; NewVirtualFile nvf = (NewVirtualFile)file; if (forceRefresh) { nvf.markDirty(); } RefreshWorker worker = new RefreshWorker(nvf, myIsRecursive); myWorker = worker; worker.scan(); haveEventsToFire |= myEvents.addAll(worker.getEvents()); } count++; if (LOG.isTraceEnabled()) LOG.trace("events=" + myEvents.size()); } while (!myCancelled && myIsRecursive && count < 3 && ContainerUtil.exists(workQueue, f -> ((NewVirtualFile)f).isDirty())); if (t != 0) { t = System.currentTimeMillis() - t; LOG.trace((myCancelled ? "cancelled, " : "done, ") + t + " ms, events " + myEvents); } } myWorker = null; myHaveEventsToFire = haveEventsToFire; } void cancel() { myCancelled = true; RefreshWorker worker = myWorker; if (worker != null) { worker.cancel(); } } void fireEvents() { if (!myHaveEventsToFire || ApplicationManager.getApplication().isDisposed()) { mySemaphore.up(); return; } try { if (LOG.isDebugEnabled()) LOG.debug("events are about to fire: " + myEvents); WriteAction.run(this::fireEventsInWriteAction); } finally { mySemaphore.up(); } } private void fireEventsInWriteAction() { final VirtualFileManagerEx manager = (VirtualFileManagerEx)VirtualFileManager.getInstance(); manager.fireBeforeRefreshStart(myIsAsync); try { while (!myWorkQueue.isEmpty() || !myEvents.isEmpty()) { PersistentFS.getInstance().processEvents(mergeEventsAndReset()); scan(); } } catch (AssertionError e) { if (FileStatusMap.CHANGES_NOT_ALLOWED_DURING_HIGHLIGHTING.equals(e.getMessage())) { throw new AssertionError("VFS changes are not allowed during highlighting", myStartTrace); } throw e; } finally { try { manager.fireAfterRefreshFinish(myIsAsync); } finally { if (myFinishRunnable != null) { myFinishRunnable.run(); } } } } public void waitFor() { mySemaphore.waitFor(); } private List<VFileEvent> mergeEventsAndReset() { Set<VFileEvent> mergedEvents = new LinkedHashSet<>(myEvents); List<VFileEvent> events = new ArrayList<>(mergedEvents); myEvents = new ArrayList<>(); return events; } @Nullable TransactionId getTransaction() { return myTransaction; } @Override public String toString() { return myWorkQueue.size() <= 1 ? "" : myWorkQueue.size() + " roots in queue."; } }
package org.jenkins.tools.test; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import hudson.AbortException; import hudson.Functions; import hudson.model.UpdateSite; import hudson.model.UpdateSite.Plugin; import hudson.util.VersionNumber; import io.jenkins.lib.versionnumber.JavaSpecificationVersion; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Constructor; import java.net.URL; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.jar.JarInputStream; import java.util.jar.Manifest; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.annotation.Nonnull; import javax.xml.transform.Result; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.apache.maven.model.Dependency; import org.apache.maven.model.Model; import org.apache.maven.model.Parent; import org.apache.maven.scm.ScmException; import org.apache.maven.scm.ScmFileSet; import org.apache.maven.scm.ScmTag; import org.apache.maven.scm.command.checkout.CheckOutScmResult; import org.apache.maven.scm.manager.ScmManager; import org.apache.maven.scm.repository.ScmRepository; import org.codehaus.plexus.PlexusContainerException; import org.codehaus.plexus.component.repository.exception.ComponentLookupException; import org.codehaus.plexus.util.FileUtils; import org.codehaus.plexus.util.io.RawInputStreamFacade; import org.codehaus.plexus.util.xml.pull.XmlPullParserException; import org.jenkins.tools.test.exception.PluginSourcesUnavailableException; import org.jenkins.tools.test.exception.PomExecutionException; import org.jenkins.tools.test.exception.ExecutedTestNamesSolverException; import org.jenkins.tools.test.maven.ExternalMavenRunner; import org.jenkins.tools.test.model.MavenBom; import org.jenkins.tools.test.maven.MavenRunner; import org.jenkins.tools.test.model.MavenCoordinates; import org.jenkins.tools.test.model.MavenPom; import org.jenkins.tools.test.model.PCTPlugin; import org.jenkins.tools.test.model.PluginCompatReport; import org.jenkins.tools.test.model.PluginCompatResult; import org.jenkins.tools.test.model.PluginCompatTesterConfig; import org.jenkins.tools.test.model.PluginInfos; import org.jenkins.tools.test.model.PluginRemoting; import org.jenkins.tools.test.model.PomData; import org.jenkins.tools.test.model.TestExecutionResult; import org.jenkins.tools.test.model.TestStatus; import org.jenkins.tools.test.model.hook.PluginCompatTesterHookBeforeCompile; import org.jenkins.tools.test.model.hook.PluginCompatTesterHooks; import org.jenkins.tools.test.util.ExecutedTestNamesSolver; import org.springframework.core.io.ClassPathResource; import org.jenkins.tools.test.exception.PomTransformationException; /** * Frontend for plugin compatibility tests * * @author Frederic Camblor, Olivier Lamy */ public class PluginCompatTester { private static final Logger LOGGER = Logger.getLogger(PluginCompatTester.class.getName()); private static final String DEFAULT_SOURCE_ID = "default"; /** First version with new parent POM. */ public static final String JENKINS_CORE_FILE_REGEX = "WEB-INF/lib/jenkins-core-([0-9.]+(?:-[0-9a-f.]+)*(?:-(?i)([a-z]+)(-)?([0-9a-f.]+)?)?(?:-(?i)([a-z]+)(-)?([0-9a-f_.]+)?)?(?:-SNAPSHOT)?)[.]jar"; private PluginCompatTesterConfig config; private final ExternalMavenRunner runner; private List<String> splits; private Set<String> splitCycles; @SuppressFBWarnings(value = "EI_EXPOSE_REP2", justification = "not mutated after this point I hope") public PluginCompatTester(PluginCompatTesterConfig config){ this.config = config; runner = new ExternalMavenRunner(config.getExternalMaven()); } private SortedSet<MavenCoordinates> generateCoreCoordinatesToTest(UpdateSite.Data data, PluginCompatReport previousReport){ SortedSet<MavenCoordinates> coreCoordinatesToTest; // If parent GroupId/Artifact are not null, this will be fast : we will only test // against 1 core coordinate if(config.getParentGroupId() != null && config.getParentArtifactId() != null){ coreCoordinatesToTest = new TreeSet<>(); // If coreVersion is not provided in PluginCompatTesterConfig, let's use latest core // version used in update center String coreVersion = config.getParentVersion()==null?data.core.version:config.getParentVersion(); MavenCoordinates coreArtifact = new MavenCoordinates(config.getParentGroupId(), config.getParentArtifactId(), coreVersion); coreCoordinatesToTest.add(coreArtifact); // If parent groupId/artifactId are null, we'll test against every already recorded // cores } else if(config.getParentGroupId() == null && config.getParentArtifactId() == null){ coreCoordinatesToTest = previousReport.getTestedCoreCoordinates(); } else { throw new IllegalStateException("config.parentGroupId and config.parentArtifactId should either be both null or both filled\n" + "config.parentGroupId=" + config.getParentGroupId() + ", config.parentArtifactId=" + config.getParentArtifactId()); } return coreCoordinatesToTest; } public PluginCompatReport testPlugins() throws PlexusContainerException, IOException, PomExecutionException, XmlPullParserException { File war = config.getWar(); if (war != null) { populateSplits(war); } else { // TODO find a way to load the local version of jenkins.war acc. to UC metadata splits = HISTORICAL_SPLITS; splitCycles = HISTORICAL_SPLIT_CYCLES; } PluginCompatTesterHooks pcth = new PluginCompatTesterHooks(config.getHookPrefixes(), config.getExternalHooksJars()); // Providing XSL Stylesheet along xml report file if(config.reportFile != null){ if(config.isProvideXslReport()){ File xslFilePath = PluginCompatReport.getXslFilepath(config.reportFile); FileUtils.copyStreamToFile(new RawInputStreamFacade(getXslTransformerResource().getInputStream()), xslFilePath); } } // Determine the plugin data HashMap<String,String> pluginGroupIds = new HashMap<>(); // Used to track real plugin groupIds from WARs // Scan bundled plugins // If there is any bundled plugin, only these plugins will be taken under the consideration for the PCT run UpdateSite.Data data = null; if (config.getBom() != null) { data = scanBom(pluginGroupIds, "([^/.]+)[.][hj]pi"); } else { data = config.getWar() == null ? extractUpdateCenterData(pluginGroupIds) : scanWAR(config.getWar(), pluginGroupIds, "WEB-INF/(?:optional-)?plugins/([^/.]+)[.][hj]pi"); } if (!data.plugins.isEmpty()) { // Scan detached plugins to recover proper Group IDs for them // At the moment, we are considering that bomfile contains the info about the detached ones UpdateSite.Data detachedData = config.getBom() != null ? null : config.getWar() != null ? scanWAR(config.getWar(), pluginGroupIds, "WEB-INF/(?:detached-)?plugins/([^/.]+)[.][hj]pi") : extractUpdateCenterData(pluginGroupIds); // Add detached if and only if no added as normal one UpdateSite.Data finalData = data; if (detachedData != null) { detachedData.plugins.forEach((key, value) -> { if (!finalData.plugins.containsKey(key)) { finalData.plugins.put(key, value); } }); } } final Map<String, Plugin> pluginsToCheck; final List<String> pluginsToInclude = config.getIncludePlugins(); if (data.plugins.isEmpty() && pluginsToInclude != null && !pluginsToInclude.isEmpty()) { // Update Center returns empty info OR the "-war" option is specified for WAR without bundled plugins System.out.println("WAR file does not contain plugin info, will try to extract it from UC for included plugins"); pluginsToCheck = new HashMap<>(pluginsToInclude.size()); UpdateSite.Data ucData = extractUpdateCenterData(pluginGroupIds); for (String plugin : pluginsToInclude) { UpdateSite.Plugin pluginData = ucData.plugins.get(plugin); if (pluginData != null) { System.out.println("Adding " + plugin + " to the test scope"); pluginsToCheck.put(plugin, pluginData); } } } else { pluginsToCheck = data.plugins; } if (pluginsToCheck.isEmpty()) { throw new IOException("List of plugins to check is empty, it is not possible to run PCT"); } // if there is only one plugin and it's not already resolved (not in the war, not in a bom and not in an update center) // and there is a local checkout available then it needs to be added to the plugins to check if (onlyOnePluginIncluded() && localCheckoutProvided() && !pluginsToCheck.containsKey(config.getIncludePlugins().get(0))) { String artifactId = config.getIncludePlugins().get(0); try { Plugin extracted = extractFromLocalCheckout(); pluginsToCheck.put(artifactId, extracted); } catch (PluginSourcesUnavailableException e) { LOGGER.log(Level.SEVERE, String.format("Local checkout provided but plugin sources are not available. Cannot test plugin [%s]", artifactId)); } } PluginCompatReport report = PluginCompatReport.fromXml(config.reportFile); SortedSet<MavenCoordinates> testedCores = config.getWar() == null ? generateCoreCoordinatesToTest(data, report) : coreVersionFromWAR(data); MavenRunner.Config mconfig = new MavenRunner.Config(); mconfig.userSettingsFile = config.getM2SettingsFile(); // TODO REMOVE mconfig.userProperties.put( "failIfNoTests", "false" ); mconfig.userProperties.putAll(this.config.retrieveMavenProperties()); report.setTestJavaVersion(config.getTestJavaVersion()); boolean failed = false; SCMManagerFactory.getInstance().start(); ROOT_CYCLE: for(MavenCoordinates coreCoordinates : testedCores){ System.out.println("Starting plugin tests on core coordinates : "+coreCoordinates.toString()); for (Plugin plugin : pluginsToCheck.values()) { if(config.getIncludePlugins()==null || config.getIncludePlugins().contains(plugin.name.toLowerCase())){ PluginInfos pluginInfos = new PluginInfos(plugin.name, plugin.version, plugin.url); if(config.getExcludePlugins()!=null && config.getExcludePlugins().contains(plugin.name.toLowerCase())){ System.out.println("Plugin "+plugin.name+" is in excluded plugins => test skipped !"); continue; } String errorMessage = null; TestStatus status = null; MavenCoordinates actualCoreCoordinates = coreCoordinates; PluginRemoting remote; if (localCheckoutProvided() && onlyOnePluginIncluded()) { // Only one plugin and checkout directory provided remote = new PluginRemoting(new File(config.getLocalCheckoutDir(), "pom.xml")); } else if(localCheckoutProvided()) { // local directory provided for more than one plugin, so each plugin is allocated in localCheckoutDir/plugin-name // If there is no subdirectory for the plugin, it will be cloned from scm File pomFile = new File(new File(config.getLocalCheckoutDir(), plugin.name), "pom.xml"); if (pomFile.exists()) { remote = new PluginRemoting(pomFile); } else { remote = new PluginRemoting(plugin.url); } } else { // Only one plugin but checkout directory not provided or // more than a plugin and no local checkout directory provided remote = new PluginRemoting(plugin.url); } PomData pomData; try { pomData = remote.retrievePomData(); MavenCoordinates parentPom = pomData.parent; if (parentPom != null) { // Parent POM is used here only to detect old versions of core LOGGER.log(Level.INFO,"Detected parent POM: {0}", parentPom.toGAV()); if ((parentPom.groupId.equals(PluginCompatTesterConfig.DEFAULT_PARENT_GROUP) && parentPom.artifactId.equals(PluginCompatTesterConfig.DEFAULT_PARENT_ARTIFACT) || parentPom.groupId.equals("org.jvnet.hudson.plugins")) && coreCoordinates.version.matches("1[.][0-9]+[.][0-9]+") && new VersionNumber(coreCoordinates.version).compareTo(new VersionNumber("1.485")) < 0) { // TODO unless 1.480.3+ LOGGER.log(Level.WARNING, "Cannot test against " + coreCoordinates.version + " due to lack of deployed POM for " + coreCoordinates.toGAV()); actualCoreCoordinates = new MavenCoordinates(coreCoordinates.groupId, coreCoordinates.artifactId, coreCoordinates.version.replaceFirst("[.][0-9]+$", "")); } } } catch (Throwable t) { status = TestStatus.INTERNAL_ERROR; LOGGER.log(Level.SEVERE, String.format("Internal error while executing a test for core %s and plugin %s %s. Please submit a bug to plugin-compat-tester", coreCoordinates.version, plugin.getDisplayName(), plugin.version), t); errorMessage = t.getMessage(); pomData = null; } if(!config.isSkipTestCache() && report.isCompatTestResultAlreadyInCache(pluginInfos, actualCoreCoordinates, config.getTestCacheTimeout(), config.getCacheThresholdStatus())){ System.out.println("Cache activated for plugin "+pluginInfos.pluginName+" => test skipped !"); continue; // Don't do anything : we are in the cached interval ! :-) } List<String> warningMessages = new ArrayList<>(); Set<String> testDetails = new TreeSet<>(); if (errorMessage == null) { try { TestExecutionResult result = testPluginAgainst(actualCoreCoordinates, plugin, mconfig, pomData, pluginsToCheck, pluginGroupIds, pcth, config.getOverridenPlugins()); if (result.getTestDetails().isSuccess()) { status = TestStatus.SUCCESS; } else { status = TestStatus.TEST_FAILURES; } warningMessages.addAll(result.pomWarningMessages); testDetails.addAll(config.isStoreAll() ? result.getTestDetails().getAll() : result.getTestDetails().hasFailures() ? result.getTestDetails().getFailed() : Collections.emptySet()); } catch (PomExecutionException e) { if(!e.succeededPluginArtifactIds.contains("maven-compiler-plugin")){ status = TestStatus.COMPILATION_ERROR; } else if (!e.getTestDetails().hasBeenExecuted()) { // testing was not able to start properly (i.e: invalid exclusion list file format) status = TestStatus.INTERNAL_ERROR; } else if (e.getTestDetails().hasFailures()) { status = TestStatus.TEST_FAILURES; } else { // Can this really happen ??? status = TestStatus.SUCCESS; } errorMessage = e.getErrorMessage(); warningMessages.addAll(e.getPomWarningMessages()); testDetails.addAll(config.isStoreAll() ? e.getTestDetails().getAll() : e.getTestDetails().hasFailures() ? e.getTestDetails().getFailed() : Collections.emptySet()); } catch (Error e){ // Rethrow the error ... something is wrong ! throw e; } catch (Throwable t){ status = TestStatus.INTERNAL_ERROR; LOGGER.log(Level.SEVERE, String.format("Internal error while executing a test for core %s and plugin %s %s. Please submit a bug to plugin-compat-tester", coreCoordinates.version, plugin.getDisplayName(), plugin.version), t); errorMessage = t.getMessage(); } } File buildLogFile = createBuildLogFile(config.reportFile, plugin.name, plugin.version, actualCoreCoordinates); String buildLogFilePath = ""; if(buildLogFile.exists()){ buildLogFilePath = createBuildLogFilePathFor(pluginInfos.pluginName, pluginInfos.pluginVersion, actualCoreCoordinates); } if(config.getBom() != null) { actualCoreCoordinates = new MavenCoordinates(actualCoreCoordinates.groupId, actualCoreCoordinates.artifactId, solveVersionFromModel(new MavenBom(config.getBom()).getModel())); } PluginCompatResult result = new PluginCompatResult(actualCoreCoordinates, status, errorMessage, warningMessages, testDetails, buildLogFilePath); report.add(pluginInfos, result); if(config.reportFile != null){ if(!config.reportFile.exists()){ FileUtils.fileWrite(config.reportFile.getAbsolutePath(), ""); } report.save(config.reportFile); } if (status != TestStatus.SUCCESS) { failed = true; if (config.isFailOnError()) { break ROOT_CYCLE; } } } else { System.out.println("Plugin "+plugin.name+" not in included plugins => test skipped !"); } } } // Generating HTML report only if needed, if the file does not exist is because no test has been executed if(config.isGenerateHtmlReport() && config.reportFile != null && config.reportFile.exists()) { generateHtmlReportFile(); } else { System.out.println("No HTML report is generated, because it has been disabled or no tests have been executed"); } if (failed && config.isFailOnError()) { throw new AbortException("Execution was aborted due to the failure in a plugin test (-failOnError is set)"); } return report; } private Plugin extractFromLocalCheckout() throws PluginSourcesUnavailableException { PomData data = new PluginRemoting(new File(config.getLocalCheckoutDir(), "pom.xml")).retrievePomData(); JSONObject o = new JSONObject(); o.put("name", data.artifactId); o.put("version", ""); // version is not required o.put("url", data.getConnectionUrl()); o.put("dependencies", new JSONArray()); return new UpdateSite(DEFAULT_SOURCE_ID, null).new Plugin(DEFAULT_SOURCE_ID, o); } protected void generateHtmlReportFile() throws IOException { if (!config.reportFile.exists() || !config.reportFile.isFile()) { throw new FileNotFoundException("Cannot find the XML report file: " + config.reportFile); } Source xmlSource = new StreamSource(config.reportFile); try(InputStream xsltStream = getXslTransformerResource().getInputStream()) { Source xsltSource = new StreamSource(xsltStream); Result result = new StreamResult(PluginCompatReport.getHtmlFilepath(config.reportFile)); TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer; try { transformer = factory.newTransformer(xsltSource); transformer.transform(xmlSource, result); } catch (TransformerException e) { throw new RuntimeException(e); } } } private static ClassPathResource getXslTransformerResource(){ return new ClassPathResource("resultToReport.xsl"); } private static File createBuildLogFile(File reportFile, String pluginName, String pluginVersion, MavenCoordinates coreCoords){ return new File(reportFile.getParentFile().getAbsolutePath() + File.separator + createBuildLogFilePathFor(pluginName, pluginVersion, coreCoords)); } private static String createBuildLogFilePathFor(String pluginName, String pluginVersion, MavenCoordinates coreCoords){ return String.format("logs/%s/v%s_against_%s_%s_%s.log", pluginName, pluginVersion, coreCoords.groupId, coreCoords.artifactId, coreCoords.version); } private TestExecutionResult testPluginAgainst(MavenCoordinates coreCoordinates, Plugin plugin, MavenRunner.Config mconfig, PomData pomData, Map<String, Plugin> otherPlugins, Map<String, String> pluginGroupIds, PluginCompatTesterHooks pcth, List<PCTPlugin> overridenPlugins) throws PluginSourcesUnavailableException, PomExecutionException, IOException, PomTransformationException { System.out.println(String.format("%n%n%n%n%n")); System.out.println(" System.out.println(" System.out.println(String.format("##%n## Starting to test plugin %s v%s%n## against %s%n##", plugin.name, plugin.version, coreCoordinates)); System.out.println(" System.out.println(" System.out.println(String.format("%n%n%n%n%n")); File pluginCheckoutDir = new File(config.workDirectory.getAbsolutePath() + File.separator + plugin.name + File.separator); String parentFolder = StringUtils.EMPTY; try { // Run any precheckout hooks Map<String, Object> beforeCheckout = new HashMap<>(); beforeCheckout.put("pluginName", plugin.name); beforeCheckout.put("plugin", plugin); beforeCheckout.put("pomData", pomData); beforeCheckout.put("config", config); beforeCheckout.put("runCheckout", true); beforeCheckout = pcth.runBeforeCheckout(beforeCheckout); if(beforeCheckout.get("executionResult") != null) { // Check if the hook returned a result return (TestExecutionResult)beforeCheckout.get("executionResult"); } else if((boolean)beforeCheckout.get("runCheckout")) { if(beforeCheckout.get("checkoutDir") != null){ pluginCheckoutDir = (File)beforeCheckout.get("checkoutDir"); } if (Files.isDirectory(pluginCheckoutDir.toPath())) { System.out.println("Deleting working directory "+pluginCheckoutDir.getAbsolutePath()); FileUtils.deleteDirectory(pluginCheckoutDir); } Files.createDirectory(pluginCheckoutDir.toPath()); System.out.println("Created plugin checkout dir : "+pluginCheckoutDir.getAbsolutePath()); if (localCheckoutProvided()) { if (!onlyOnePluginIncluded()) { File localCheckoutPluginDir = new File(config.getLocalCheckoutDir(), plugin.name); File pomLocalCheckoutPluginDir = new File(localCheckoutPluginDir, "pom.xml"); if(pomLocalCheckoutPluginDir.exists()) { System.out.println("Copy plugin directory from : " + localCheckoutPluginDir.getAbsolutePath()); FileUtils.copyDirectoryStructure(localCheckoutPluginDir, pluginCheckoutDir); } else { cloneFromSCM(pomData, plugin.name, plugin.version, pluginCheckoutDir, ""); } } else { // and even up-to-date versions of org.apache.commons.io.FileUtils seem to not handle links, System.out.println("Copy plugin directory from : " + config.getLocalCheckoutDir().getAbsolutePath()); FileUtils.copyDirectoryStructure(config.getLocalCheckoutDir(), pluginCheckoutDir); } } else { // These hooks could redirect the SCM, skip checkout (if multiple plugins use the same preloaded repo) cloneFromSCM(pomData, plugin.name, plugin.version, pluginCheckoutDir, ""); } } else { // If the plugin exists in a different directory (multimodule plugins) if (beforeCheckout.get("pluginDir") != null) { pluginCheckoutDir = (File)beforeCheckout.get("checkoutDir"); } if (beforeCheckout.get("parentFolder") != null) { parentFolder = (String) beforeCheckout.get("parentFolder"); } System.out.println("The plugin has already been checked out, likely due to a multimodule situation. Continue."); } } catch (ComponentLookupException e) { System.err.println("Error : " + e.getMessage()); throw new PluginSourcesUnavailableException("Problem while creating ScmManager !", e); } catch (Exception e) { System.err.println("Error : " + e.getMessage()); throw new PluginSourcesUnavailableException("Problem while checking out plugin sources!", e); } File buildLogFile = createBuildLogFile(config.reportFile, plugin.name, plugin.version, coreCoordinates); FileUtils.forceMkdir(buildLogFile.getParentFile()); // Creating log directory FileUtils.fileWrite(buildLogFile.getAbsolutePath(), ""); // Creating log file // Ran the BeforeCompileHooks Map<String, Object> beforeCompile = new HashMap<>(); beforeCompile.put("pluginName", plugin.name); beforeCompile.put("plugin", plugin); beforeCompile.put("pluginDir", pluginCheckoutDir); beforeCompile.put("pomData", pomData); beforeCompile.put("config", config); beforeCompile.put("core", coreCoordinates); if (StringUtils.isNotEmpty(parentFolder)) { beforeCompile.put("parentFolder", parentFolder); } Map<String, Object> hookInfo = pcth.runBeforeCompilation(beforeCompile); boolean ranCompile = hookInfo.containsKey(PluginCompatTesterHookBeforeCompile.OVERRIDE_DEFAULT_COMPILE) && (boolean) hookInfo.get(PluginCompatTesterHookBeforeCompile.OVERRIDE_DEFAULT_COMPILE); try { // First build against the original POM. // This defends against source incompatibilities (which we do not care about for this purpose); // and ensures that we are testing a plugin binary as close as possible to what was actually released. // We also skip potential javadoc execution to avoid general test failure. if (!ranCompile) { runner.run(mconfig, pluginCheckoutDir, buildLogFile, "clean", "process-test-classes", "-Dmaven.javadoc.skip"); } ranCompile = true; // Then transform the POM and run tests against that. // You might think that it would suffice to run e.g. // (2.15+ required for ${maven.test.dependency.excludes} and ${maven.test.additionalClasspath} to be honored from CLI) // but it does not work; there are lots of linkage errors as some things are expected to be in the test classpath which are not. // Much simpler to do use the parent POM to set up the test classpath. MavenPom pom = new MavenPom(pluginCheckoutDir); try { addSplitPluginDependencies(plugin.name, mconfig, pluginCheckoutDir, pom, otherPlugins, pluginGroupIds, coreCoordinates.version, overridenPlugins, parentFolder); } catch (PomTransformationException x) { throw x; } catch (Exception x) { x.printStackTrace(); pomData.getWarningMessages().add(Functions.printThrowable(x)); // but continue } List<String> args = new ArrayList<>(); Map<String, String> userProperties = mconfig.userProperties; args.add(String.format("--define=forkCount=%s",userProperties.containsKey("forkCount") ? userProperties.get("forkCount") : "1")); args.add("hpi:resolve-test-dependencies"); args.add("hpi:test-hpl"); args.add("surefire:test"); // Run preexecution hooks List<String> testTypes = new LinkedList<>(); testTypes.add("surefire"); // default Map<String, Object> forExecutionHooks = new HashMap<>(); forExecutionHooks.put("pluginName", plugin.name); forExecutionHooks.put("plugin", plugin); forExecutionHooks.put("args", args); forExecutionHooks.put("pomData", pomData); forExecutionHooks.put("pom", pom); forExecutionHooks.put("coreCoordinates", coreCoordinates); forExecutionHooks.put("config", config); forExecutionHooks.put("pluginDir", pluginCheckoutDir); forExecutionHooks.put("types", testTypes); pcth.runBeforeExecution(forExecutionHooks); args = (List<String>)forExecutionHooks.get("args"); Set<String> types = new HashSet<>((List<String>) forExecutionHooks.get("types")); userProperties.put("types", String.join(",", types)); // Execute with tests runner.run(mconfig, pluginCheckoutDir, buildLogFile, args.toArray(new String[args.size()])); return new TestExecutionResult(((PomData)forExecutionHooks.get("pomData")).getWarningMessages(), new ExecutedTestNamesSolver().solve(types, runner.getExecutedTests(), pluginCheckoutDir)); } catch (ExecutedTestNamesSolverException e) { throw new PomExecutionException(e); } catch (PomExecutionException e){ e.getPomWarningMessages().addAll(pomData.getWarningMessages()); if (ranCompile) { // So the status cannot be considered COMPILATION_ERROR e.succeededPluginArtifactIds.add("maven-compiler-plugin"); } throw e; } } public void cloneFromSCM(PomData pomData, String name, String version, File checkoutDirectory, String tag) throws ComponentLookupException, ScmException, IOException { String scmTag = !(tag.equals("")) ? tag : getScmTag(pomData, name, version); String connectionURLPomData = pomData.getConnectionUrl(); List<String> connectionURLs = new ArrayList<String>(); connectionURLs.add(connectionURLPomData); if(config.getFallbackGitHubOrganization() != null){ connectionURLs = getFallbackConnectionURL(connectionURLs, connectionURLPomData, config.getFallbackGitHubOrganization()); } Boolean repositoryCloned = false; String errorMessage = ""; ScmRepository repository; ScmManager scmManager = SCMManagerFactory.getInstance().createScmManager(); for (String connectionURL: connectionURLs){ if (connectionURL != null) { connectionURL = connectionURL.replace("git: } System.out.println("Checking out from SCM connection URL : " + connectionURL + " (" + name + "-" + version + ") at tag " + scmTag); if (checkoutDirectory.isDirectory()) { FileUtils.deleteDirectory(checkoutDirectory); } repository = scmManager.makeScmRepository(connectionURL); CheckOutScmResult result = scmManager.checkOut(repository, new ScmFileSet(checkoutDirectory), new ScmTag(scmTag)); if(result.isSuccess()){ repositoryCloned = true; break; } else { errorMessage = result.getProviderMessage() + " || " + result.getCommandOutput(); } } if (!repositoryCloned) { throw new RuntimeException(errorMessage); } } private String getScmTag(PomData pomData, String name, String version){ String scmTag; if (pomData.getScmTag() != null) { scmTag = pomData.getScmTag(); System.out.println(String.format("Using SCM tag '%s' from POM.", scmTag)); } else { scmTag = name + "-" + version; System.out.println(String.format("POM did not provide an SCM tag. Inferring tag '%s'.", scmTag)); } return scmTag; } public static List<String> getFallbackConnectionURL(List<String> connectionURLs,String connectionURLPomData, String fallbackGitHubOrganization){ Pattern pattern = Pattern.compile("(.*github.com[:|/])([^/]*)(.*)"); Matcher matcher = pattern.matcher(connectionURLPomData); matcher.find(); connectionURLs.add(matcher.replaceFirst("scm:git:git@github.com:" + fallbackGitHubOrganization + "$3")); pattern = Pattern.compile("(.*github.com[:|/])([^/]*)(.*)"); matcher = pattern.matcher(connectionURLPomData); matcher.find(); connectionURLs.add(matcher.replaceFirst("$1" + fallbackGitHubOrganization + "$3")); return connectionURLs; } private boolean localCheckoutProvided() { return config.getLocalCheckoutDir() != null && config.getLocalCheckoutDir().exists(); } private boolean onlyOnePluginIncluded() { return config.getIncludePlugins() != null && config.getIncludePlugins().size() == 1; } /** * Extracts Update Site data from the update center. * @param groupIDs Target storage for Group IDs. The existing values won't be overridden * @return Update site Data */ private UpdateSite.Data extractUpdateCenterData(Map<String, String> groupIDs){ URL url; String jsonp; try { url = new URL(config.updateCenterUrl); jsonp = IOUtils.toString(url.openStream()); }catch(IOException e){ throw new RuntimeException("Invalid update center url : "+config.updateCenterUrl, e); } String json = jsonp.substring(jsonp.indexOf('(')+1,jsonp.lastIndexOf(')')); UpdateSite us = new UpdateSite(DEFAULT_SOURCE_ID, url.toExternalForm()); JSONObject jsonObj = JSONObject.fromObject(json); UpdateSite.Data site = newUpdateSiteData(us, jsonObj); // UpdateSite.Plugin does not contain gav object, so we process the JSON object on our own here for(Map.Entry<String,JSONObject> e : (Set<Map.Entry<String,JSONObject>>)jsonObj.getJSONObject("plugins").entrySet()) { String gav = e.getValue().getString("gav"); String groupId = gav.split(":")[0]; groupIDs.putIfAbsent(e.getKey(), groupId); } return site; } private UpdateSite.Data scanBom(HashMap<String, String> pluginGroupIds, String pluginRegExp) throws IOException, PomExecutionException, XmlPullParserException { JSONObject top = new JSONObject(); top.put("id", DEFAULT_SOURCE_ID); JSONObject plugins = new JSONObject(); for (File entry : getBomEntries()) { String name = entry.getName(); Matcher m = Pattern.compile(pluginRegExp).matcher(name); try (InputStream is = new FileInputStream(entry); JarInputStream jis = new JarInputStream(is)) { Manifest manifest = jis.getManifest(); if (manifest == null || manifest.getMainAttributes() == null) { // Skip this entry, is not a plugin and/or contains a malformed manifest so is not parseable System.out.println("Entry " + name + "defined in the BOM looks non parseable, ignoring"); continue; } String jenkinsVersion = manifest.getMainAttributes().getValue("Jenkins-Version"); String shortName = manifest.getMainAttributes().getValue("Short-Name"); String groupId = manifest.getMainAttributes().getValue("Group-Id"); String version = manifest.getMainAttributes().getValue("Plugin-Version"); String dependencies = manifest.getMainAttributes().getValue("Plugin-Dependencies"); // I expect BOMs to not specify hpi as type, which results in getting the jar artifact if (m.matches() || (jenkinsVersion != null && version != null)) { // I need a plugin version JSONObject plugin = new JSONObject().accumulate("url", ""); if (shortName == null) { shortName = manifest.getMainAttributes().getValue("Extension-Name"); if (shortName == null) { shortName = m.group(1); } } // If hpi is registered, avoid to override it by its jar entry if(plugins.containsKey(shortName) && entry.getPath().endsWith(".jar")) { continue; } plugin.put("name", shortName); pluginGroupIds.put(shortName, groupId); // Remove extra build information from the version number final Matcher matcher = Pattern.compile("^(.+-SNAPSHOT)(.+)$").matcher(version); if (matcher.matches()) { version = matcher.group(1); } plugin.put("version", version); plugin.put("url", "jar:" + entry.toURI().getPath() + "!/name.hpi"); JSONArray dependenciesA = new JSONArray(); if (dependencies != null) { // e.g. matrix-auth:1.0.2;resolution:=optional,credentials:1.8.3;resolution:=optional for (String pair : dependencies.split(",")) { boolean optional = pair.endsWith("resolution:=optional"); String[] nameVer = pair.replace(";resolution:=optional", "").split(":"); assert nameVer.length == 2; dependenciesA.add(new JSONObject().accumulate("name", nameVer[0]).accumulate("version", nameVer[1]).accumulate("optional", String.valueOf(optional))); } } plugin.accumulate("dependencies", dependenciesA); plugins.put(shortName, plugin); } } } top.put("plugins", plugins); if (!top.has("core")) { // Not all boms have the jenkins core dependency explicit, so, assume the bom version matches the jenkins version String core = solveCoreVersionFromBom(); if (StringUtils.isEmpty(core)) { throw new IllegalStateException("Unable to retrieve any version for the core"); } top.put("core", new JSONObject().accumulate("name", "core").accumulate("version",core).accumulate("url", "https://foobar")); } System.out.println("Readed contents of " + config.getBom() + ": " + top); return newUpdateSiteData(new UpdateSite(DEFAULT_SOURCE_ID, null), top); } private List<File> getBomEntries() throws IOException, XmlPullParserException, PomExecutionException { File fullDepPom = new MavenBom(config.getBom()).writeFullDepPom(config.workDirectory); MavenRunner.Config mconfig = new MavenRunner.Config(); mconfig.userSettingsFile = config.getM2SettingsFile(); System.out.println(mconfig.userSettingsFile); // TODO REMOVE mconfig.userProperties.putAll(this.config.retrieveMavenProperties()); File buildLogFile = new File(config.workDirectory + File.separator + "bom-download.log"); FileUtils.fileWrite(buildLogFile.getAbsolutePath(), ""); // Creating log file runner.run(mconfig, fullDepPom.getParentFile(), buildLogFile, "dependency:copy-dependencies", "-P consume-incrementals", "-N"); return FileUtils.getFiles(new File(config.workDirectory, "bom" + File.separator + "target" + File.separator + "dependency"),null, null); } /** * @return Provides the core version from the bomfile and in case it is not found, the bom version, if bom version does not exist, it provides from its parent * @throws IOException * @throws XmlPullParserException */ private String solveCoreVersionFromBom() throws IOException, XmlPullParserException { Model model = new MavenBom(config.getBom()).getModel(); for (Dependency dependency : model.getDependencies()) { if(dependency.getArtifactId().equals("jenkins-core")) { return getProperty(model, dependency.getVersion()); } } return solveVersionFromModel(model); } private String solveVersionFromModel(Model model) { String version = model.getVersion(); Parent parent = model.getParent(); return version != null ? version : parent != null ? parent.getVersion() : StringUtils.EMPTY; } /** * Given a value and a model, it checks if it is an interpolated value. In negative case it returns the same * value. In affirmative case, it retrieves its value from the properties of the Maven model. * @param model * @param version * @return the effective value of an specific value in a model */ private String getProperty(Model model, String value) { if (!value.contains("$")) { return value; } String key = value.replaceAll("\\$", "") .replaceAll("\\{", "") .replaceAll("\\}", ""); return getProperty(model, model.getProperties().getProperty(key)); } /** * Scans through a WAR file, accumulating plugin information * @param war WAR to scan * @param pluginGroupIds Map pluginName to groupId if set in the manifest, MUTATED IN THE EXECUTION * @param pluginRegExp The plugin regexp to use, can be used to differentiate between detached or "normal" plugins * in the war file * @return Update center data */ private UpdateSite.Data scanWAR(File war, @Nonnull Map<String, String> pluginGroupIds, String pluginRegExp) throws IOException { JSONObject top = new JSONObject(); top.put("id", DEFAULT_SOURCE_ID); JSONObject plugins = new JSONObject(); try (JarFile jf = new JarFile(war)) { Enumeration<JarEntry> entries = jf.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); String name = entry.getName(); Matcher m = Pattern.compile(JENKINS_CORE_FILE_REGEX).matcher(name); if (m.matches()) { if (top.has("core")) { throw new IOException(">1 jenkins-core.jar in " + war); } // We do not really care about the value top.put("core", new JSONObject().accumulate("name", "core").accumulate("version", m.group(1)).accumulate("url", "https://foobar")); } m = Pattern.compile(pluginRegExp).matcher(name); if (m.matches()) { JSONObject plugin = new JSONObject().accumulate("url", ""); try (InputStream is = jf.getInputStream(entry); JarInputStream jis = new JarInputStream(is)) { Manifest manifest = jis.getManifest(); String shortName = manifest.getMainAttributes().getValue("Short-Name"); if (shortName == null) { shortName = manifest.getMainAttributes().getValue("Extension-Name"); if (shortName == null) { shortName = m.group(1); } } plugin.put("name", shortName); pluginGroupIds.put(shortName, manifest.getMainAttributes().getValue("Group-Id")); String version = manifest.getMainAttributes().getValue("Plugin-Version"); // Remove extra build information from the version number final Matcher matcher = Pattern.compile("^(.+-SNAPSHOT)(.+)$").matcher(version); if (matcher.matches()) { version = matcher.group(1); } plugin.put("version", version); plugin.put("url", "jar:" + war.toURI() + "!/" + name); JSONArray dependenciesA = new JSONArray(); String dependencies = manifest.getMainAttributes().getValue("Plugin-Dependencies"); if (dependencies != null) { // e.g. matrix-auth:1.0.2;resolution:=optional,credentials:1.8.3;resolution:=optional for (String pair : dependencies.split(",")) { boolean optional = pair.endsWith("resolution:=optional"); String[] nameVer = pair.replace(";resolution:=optional", "").split(":"); assert nameVer.length == 2; dependenciesA.add(new JSONObject().accumulate("name", nameVer[0]).accumulate("version", nameVer[1]).accumulate("optional", String.valueOf(optional))); } } plugin.accumulate("dependencies", dependenciesA); plugins.put(shortName, plugin); } } } } top.put("plugins", plugins); if (!top.has("core")) { throw new IOException("no jenkins-core.jar in " + war); } System.out.println("Scanned contents of " + war + " with " + plugins.size() + " plugins"); return newUpdateSiteData(new UpdateSite(DEFAULT_SOURCE_ID, null), top); } private SortedSet<MavenCoordinates> coreVersionFromWAR(UpdateSite.Data data) { SortedSet<MavenCoordinates> result = new TreeSet<>(); result.add(new MavenCoordinates(PluginCompatTesterConfig.DEFAULT_PARENT_GROUP, PluginCompatTesterConfig.DEFAULT_PARENT_ARTIFACT, data.core.version)); return result; } private UpdateSite.Data newUpdateSiteData(UpdateSite us, JSONObject jsonO) throws RuntimeException { try { Constructor<UpdateSite.Data> dataConstructor = UpdateSite.Data.class.getDeclaredConstructor(UpdateSite.class, JSONObject.class); dataConstructor.setAccessible(true); return dataConstructor.newInstance(us, jsonO); }catch(Exception e){ throw new RuntimeException("UpdateSite.Data instantiation problems", e); } } /** * Provides the Maven module used for a plugin on a {@code mvn [...] -pl} operation in the parent path */ public static String getMavenModule(String plugin, File pluginPath, MavenRunner runner, MavenRunner.Config mavenConfig) throws PomExecutionException, IOException { String absolutePath = pluginPath.getAbsolutePath(); if (absolutePath.endsWith(plugin)) { return plugin; } String module = absolutePath.substring(absolutePath.lastIndexOf(File.separatorChar) + 1, absolutePath.length()); File parentFile = pluginPath.getParentFile(); if (parentFile == null) { return null; } File log = new File(parentFile.getAbsolutePath() + File.separatorChar + "modules.log"); runner.run(mavenConfig, parentFile, log, "-Dexpression=project.modules", "-q", "-DforceStdout", "help:evaluate"); for (String line : org.apache.commons.io.FileUtils.readLines(log)) { if (!StringUtils.startsWith(line.trim(), "<string>")) { continue; } String mvnModule = line.replace("<string>", "").replace("</string>", "").trim(); if (StringUtils.contains(mvnModule, module)) { return mvnModule; } } return null; } private void addSplitPluginDependencies(String thisPlugin, MavenRunner.Config mconfig, File pluginCheckoutDir, MavenPom pom, Map<String, Plugin> otherPlugins, Map<String, String> pluginGroupIds, String coreVersion, List<PCTPlugin> overridenPlugins, String parentFolder) throws Exception { File tmp = File.createTempFile("dependencies", ".log"); VersionNumber coreDep = null; Map<String,VersionNumber> pluginDeps = new HashMap<>(); Map<String,VersionNumber> pluginDepsTest = new HashMap<>(); try { if (StringUtils.isBlank(parentFolder)) { runner.run(mconfig, pluginCheckoutDir, tmp, "dependency:resolve"); } else { String mavenModule = getMavenModule(thisPlugin, pluginCheckoutDir, runner, mconfig); if (StringUtils.isBlank(mavenModule)) { throw new IOException(String.format("Unable to retrieve the Maven module for plugin %s on %s", thisPlugin, pluginCheckoutDir)); } runner.run(mconfig, pluginCheckoutDir.getParentFile(), tmp, "dependency:resolve", "-am", "-pl", mavenModule); } try (BufferedReader br = Files.newBufferedReader(tmp.toPath(), Charset.defaultCharset())) { Pattern p = Pattern.compile("\\[INFO\\]([^:]+):([^:]+):([a-z-]+):(([^:]+):)?([^:]+):(provided|compile|runtime|system)(\\(optional\\))?.*"); Pattern p2 = Pattern.compile("\\[INFO\\]([^:]+):([^:]+):([a-z-]+):(([^:]+):)?([^:]+):(test).*"); String line; while ((line = br.readLine()) != null) { line = line.replace(" ", ""); Matcher m = p.matcher(line); Matcher m2 = p2.matcher(line); String groupId; String artifactId; VersionNumber version; if (!m.matches() && !m2.matches()) { continue; } else if (m.matches()) { groupId = m.group(1); artifactId = m.group(2); try { version = new VersionNumber(m.group(6)); } catch (IllegalArgumentException x) { // OK, some other kind of dep, just ignore continue; } } else { //m2.matches() groupId = m2.group(1); artifactId = m2.group(2); try { version = new VersionNumber(m2.group(6)); } catch (IllegalArgumentException x) { // OK, some other kind of dep, just ignore continue; } } if (groupId.equals("org.jenkins-ci.main") && artifactId.equals("jenkins-core")) { coreDep = version; } else if (groupId.equals("org.jenkins-ci.plugins")) { if(m2.matches()) { pluginDepsTest.put(artifactId, version); } else { pluginDeps.put(artifactId, version); } } else if (groupId.equals("org.jenkins-ci.main") && artifactId.equals("maven-plugin")) { if(m2.matches()) { pluginDepsTest.put(artifactId, version); } else { pluginDeps.put(artifactId, version); } } else if (groupId.equals(pluginGroupIds.get(artifactId))) { if(m2.matches()) { pluginDepsTest.put(artifactId, version); } else { pluginDeps.put(artifactId, version); } } } } } finally { Files.delete(tmp.toPath()); } System.out.println("Analysis: coreDep=" + coreDep + " pluginDeps=" + pluginDeps + " pluginDepsTest=" + pluginDepsTest); if (coreDep != null) { Map<String,VersionNumber> toAdd = new HashMap<>(); Map<String,VersionNumber> toReplace = new HashMap<>(); Map<String,VersionNumber> toAddTest = new HashMap<>(); Map<String,VersionNumber> toReplaceTest = new HashMap<>(); overridenPlugins.forEach(plugin -> { toReplace.put(plugin.getName(), plugin.getVersion()); toReplaceTest.put(plugin.getName(), plugin.getVersion()); if (plugin.getGroupId() != null) { if (pluginGroupIds.containsKey(plugin.getName())) { if (!plugin.getGroupId().equals(pluginGroupIds.get(plugin.getName()))) { System.err.println("WARNING: mismatch between detected and explicit group ID for " + plugin.getName()); } } else { pluginGroupIds.put(plugin.getName(), plugin.getGroupId()); } } }); for (String split : splits) { String[] pieces = split.split(" "); String plugin = pieces[0]; if (splitCycles.contains(thisPlugin + ' ' + plugin)) { System.out.println("Skipping implicit dep " + thisPlugin + " → " + plugin); continue; } VersionNumber splitPoint = new VersionNumber(pieces[1]); VersionNumber declaredMinimum = new VersionNumber(pieces[2]); if (coreDep.compareTo(splitPoint) < 0 && new VersionNumber(coreVersion).compareTo(splitPoint) >=0 && !pluginDeps.containsKey(plugin)) { Plugin bundledP = otherPlugins.get(plugin); if (bundledP != null) { VersionNumber bundledV; try { bundledV = new VersionNumber(bundledP.version); } catch (NumberFormatException x) { // TODO apparently this does not handle `1.0-beta-1` and the like?! System.out.println("Skipping unparseable dep on " + bundledP.name + ": " + bundledP.version); continue; } if (bundledV.isNewerThan(declaredMinimum)) { toAdd.put(plugin, bundledV); continue; } } toAdd.put(plugin, declaredMinimum); } } List<String> convertFromTestDep = new ArrayList<>(); checkDefinedDeps(pluginDeps, toAdd, toReplace, otherPlugins, new ArrayList<>(pluginDepsTest.keySet()), convertFromTestDep); pluginDepsTest.putAll(difference(pluginDepsTest, toAdd)); pluginDepsTest.putAll(difference(pluginDepsTest, toReplace)); checkDefinedDeps(pluginDepsTest, toAddTest, toReplaceTest, otherPlugins); // Could contain transitive dependencies which were part of the plugin's dependencies or to be added toAddTest = difference(pluginDeps, toAddTest); toAddTest = difference(toAdd, toAddTest); if (!toAdd.isEmpty() || !toReplace.isEmpty() || !toAddTest.isEmpty() || !toReplaceTest.isEmpty()) { System.out.println("Adding/replacing plugin dependencies for compatibility: " + toAdd + " " + toReplace + "\nFor test: " + toAddTest + " " + toReplaceTest); pom.addDependencies(toAdd, toReplace, toAddTest, toReplaceTest, pluginGroupIds, convertFromTestDep); } // TODO(oleg_nenashev): This is a hack, logic above should be refactored somehow (JENKINS-55279) // Remove the self-dependency if any pom.removeDependency(pluginGroupIds.get(thisPlugin), thisPlugin); } else { // bad, we should always find a core dependency! throw new PomTransformationException("No jenkins core dependency found, aborting!", new Throwable()); } } private void checkDefinedDeps(Map<String,VersionNumber> pluginList, Map<String,VersionNumber> adding, Map<String,VersionNumber> replacing, Map<String,Plugin> otherPlugins) { checkDefinedDeps(pluginList, adding, replacing, otherPlugins, new ArrayList<>(), null); } private void checkDefinedDeps(Map<String,VersionNumber> pluginList, Map<String,VersionNumber> adding, Map<String,VersionNumber> replacing, Map<String,Plugin> otherPlugins, List<String> inTest, List<String> toConvertFromTest) { for (Map.Entry<String,VersionNumber> pluginDep : pluginList.entrySet()) { String plugin = pluginDep.getKey(); Plugin bundledP = otherPlugins.get(plugin); if (bundledP != null) { VersionNumber bundledV = new VersionNumber(bundledP.version); if (bundledV.isNewerThan(pluginDep.getValue())) { assert !adding.containsKey(plugin); replacing.put(plugin, bundledV); } // Also check any dependencies, so if we are upgrading cloudbees-folder, we also add an explicit dep on a bundled credentials. for (Map.Entry<String,String> dependency : bundledP.dependencies.entrySet()) { String depPlugin = dependency.getKey(); if (pluginList.containsKey(depPlugin)) { continue; // already handled } Plugin depBundledP = otherPlugins.get(depPlugin); if (depBundledP != null) { updateAllDependents(plugin, depBundledP, pluginList, adding, replacing, otherPlugins, inTest, toConvertFromTest); } } } } } /** * Search the dependents of a given plugin to determine if we need to use the bundled version. * This helps in cases where tests fail due to new insufficient versions as well as more * accurately representing the totality of upgraded plugins for provided war files. */ private void updateAllDependents(String parent, Plugin dependent, Map<String,VersionNumber> pluginList, Map<String,VersionNumber> adding, Map<String,VersionNumber> replacing, Map<String,Plugin> otherPlugins, List<String> inTest, List<String> toConvertFromTest) { // Check if this exists with an undesired scope String pluginName = dependent.name; if (inTest.contains(pluginName)) { // This is now required in the compile scope. For example: copyartifact's dependency matrix-project requires junit System.out.println("Converting " + pluginName + " from the test scope since it was a dependency of " + parent); toConvertFromTest.add(pluginName); replacing.put(pluginName, new VersionNumber(dependent.version)); } else { System.out.println("Adding " + pluginName + " since it was a dependency of " + parent); adding.put(pluginName, new VersionNumber(dependent.version)); } // Also check any dependencies for (Map.Entry<String,String> dependency : dependent.dependencies.entrySet()) { String depPlugin = dependency.getKey(); if (pluginList.containsKey(depPlugin)) { continue; // already handled } Plugin depBundledP = otherPlugins.get(depPlugin); if (depBundledP != null) { updateAllDependents(pluginName, depBundledP, pluginList, adding, replacing, otherPlugins, inTest, toConvertFromTest); } } } /** Use JENKINS-47634 to load metadata from jenkins-core.jar if available. */ private void populateSplits(File war) throws IOException { System.out.println("Checking " + war + " for plugin split metadata…"); System.out.println("Checking jdk version as splits may depend on a jdk version"); JavaSpecificationVersion jdkVersion = new JavaSpecificationVersion(config.getTestJavaVersion()); // From Java 9 onwards there is a standard for versions see JEP-223 try (JarFile jf = new JarFile(war, false)) { Enumeration<JarEntry> warEntries = jf.entries(); while (warEntries.hasMoreElements()) { JarEntry coreJar = warEntries.nextElement(); if (coreJar.getName().matches("WEB-INF/lib/jenkins-core-.+[.]jar")) { try (InputStream is = jf.getInputStream(coreJar); JarInputStream jis = new JarInputStream(is, false)) { JarEntry entry; int found = 0; while ((entry = jis.getNextJarEntry()) != null) { if (entry.getName().equals("jenkins/split-plugins.txt")) { splits = configLines(jis).collect(Collectors.toList()); // So make sure we are not applying splits not intended for our JDK splits = removeSplitsBasedOnJDK(splits, jdkVersion); System.out.println("found splits: " + splits); found++; } else if (entry.getName().equals("jenkins/split-plugin-cycles.txt")) { splitCycles = configLines(jis).collect(Collectors.toSet()); System.out.println("found split cycles: " + splitCycles); found++; } } if (found == 0) { System.out.println("None found, falling back to hard-coded historical values."); splits = HISTORICAL_SPLITS; splitCycles = HISTORICAL_SPLIT_CYCLES; } else if (found != 2) { throw new IOException("unexpected amount of metadata"); } } return; } } } throw new IOException("no jenkins-core-*.jar found in " + war); } private List<String> removeSplitsBasedOnJDK(List<String> splits, JavaSpecificationVersion jdkVersion) { List<String> filterSplits = new LinkedList<>(); for (String split : splits) { String[] tokens = split.trim().split("\\s+"); if (tokens.length == 4 ) { // We have a jdk field in the splits file if (jdkVersion.isNewerThanOrEqualTo(new JavaSpecificationVersion(tokens[3]))) { filterSplits.add(split); } else { System.out.println("Not adding " + split + " as split because jdk specified " + tokens[3] + " is newer than running jdk " + jdkVersion); } } else { filterSplits.add(split); } } return filterSplits; } // Matches syntax in ClassicPluginStrategy: private static Stream<String> configLines(InputStream is) throws IOException { return IOUtils.readLines(is, StandardCharsets.UTF_8).stream().filter(line -> !line.matches(" } private static final ImmutableList<String> HISTORICAL_SPLITS = ImmutableList.of( "maven-plugin 1.296 1.296", "subversion 1.310 1.0", "cvs 1.340 0.1", "ant 1.430 1.0", "javadoc 1.430 1.0", "external-monitor-job 1.467 1.0", "ldap 1.467 1.0", "pam-auth 1.467 1.0", "mailer 1.493 1.2", "matrix-auth 1.535 1.0.2", "windows-slaves 1.547 1.0", "antisamy-markup-formatter 1.553 1.0", "matrix-project 1.561 1.0", "junit 1.577 1.0", "bouncycastle-api 2.16 2.16.0", "command-launcher 2.86 1.0" ); private static final ImmutableSet<String> HISTORICAL_SPLIT_CYCLES = ImmutableSet.of( "script-security matrix-auth", "script-security windows-slaves", "script-security antisamy-markup-formatter", "script-security matrix-project", "script-security bouncycastle-api", "script-security command-launcher", "credentials matrix-auth", "credentials windows-slaves" ); /** * Finds the difference of the given maps. * In set theory: base - toAdd * * @param base the left map; all returned items are not in this map * @param toAdd the right map; all returned items are found in this map */ private Map<String, VersionNumber> difference(Map<String, VersionNumber> base, Map<String, VersionNumber> toAdd) { Map<String, VersionNumber> diff = new HashMap<>(); for (Map.Entry<String,VersionNumber> adding : toAdd.entrySet()) { if (!base.containsKey(adding.getKey())) { diff.put(adding.getKey(), adding.getValue()); } } return diff; } }
package laas.openrobots.ontology.modules.alterite; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.UUID; import laas.openrobots.ontology.OroServer; import laas.openrobots.ontology.PartialStatement; import laas.openrobots.ontology.backends.IOntologyBackend; import laas.openrobots.ontology.exceptions.AgentNotFoundException; import laas.openrobots.ontology.exceptions.EventRegistrationException; import laas.openrobots.ontology.exceptions.IllegalStatementException; import laas.openrobots.ontology.exceptions.NotComparableException; import laas.openrobots.ontology.exceptions.OntologyServerException; import laas.openrobots.ontology.helpers.Helpers; import laas.openrobots.ontology.helpers.Logger; import laas.openrobots.ontology.helpers.Namespaces; import laas.openrobots.ontology.helpers.VerboseLevel; import laas.openrobots.ontology.modules.IModule; import laas.openrobots.ontology.modules.alterite.AgentModel; import laas.openrobots.ontology.modules.alterite.AgentWatcher; import laas.openrobots.ontology.modules.base.BaseModule; import laas.openrobots.ontology.modules.categorization.CategorizationModule; import laas.openrobots.ontology.modules.events.IEventConsumer; import laas.openrobots.ontology.modules.events.IWatcher; import laas.openrobots.ontology.modules.events.OroEvent; import laas.openrobots.ontology.modules.memory.MemoryProfile; import laas.openrobots.ontology.service.IServiceProvider; import laas.openrobots.ontology.service.RPCMethod; import laas.openrobots.ontology.exceptions.InvalidQueryException; import com.hp.hpl.jena.rdf.model.Literal; import com.hp.hpl.jena.rdf.model.RDFNode; import com.hp.hpl.jena.rdf.model.Resource; import com.hp.hpl.jena.rdf.model.Statement; import com.hp.hpl.jena.shared.NotFoundException; import com.hp.hpl.jena.util.iterator.ExtendedIterator; public class AlteriteModule implements IModule, IServiceProvider, IEventConsumer { private Map<String, AgentModel> agents; private Properties serverParameters; private IOntologyBackend oro; public AlteriteModule(IOntologyBackend oro) throws EventRegistrationException { this(oro, OroServer.serverParameters); } public AlteriteModule(IOntologyBackend oro, Properties serverParameters) throws EventRegistrationException { agents = new HashMap<String, AgentModel>(); this.oro = oro; this.serverParameters = serverParameters; //Add myself as the first agent. agents.put("myself", new AgentModel("myself", oro)); //Add equivalent concept to 'myself' ExtendedIterator<? extends Resource> sameResource = oro.getResource("myself").listSameAs(); while (sameResource.hasNext()) { String syn = sameResource.next().getLocalName(); if (!syn.equals("myself")) { Logger.log("Alterite module: adding " + syn + " as a synonym for myself.\n", VerboseLevel.INFO); agents.put(syn, agents.get("myself")); } } try { Set<PartialStatement> ps = new HashSet<PartialStatement>(); ps.add(oro.createPartialStatement("?ag rdf:type Agent")); ps.add(oro.createPartialStatement("?ag owl:differentFrom myself")); //attention! ag must be computed to be actually different from myself! Set<RDFNode> existing_agents = oro.find("ag", ps, null); for (RDFNode ag : existing_agents) { String id = ag.asResource().getLocalName(); Logger.log("Alterite module: adding agent " + id + ".\n", VerboseLevel.INFO); agents.put(id, new AgentModel(id, serverParameters)); } } catch (IllegalStatementException ise) { assert(false); } catch (InvalidQueryException iqe) { assert(false); } //Register a new event that waits of appearance of new agents. //Each time a new agent appears, the this.consumeEvent() method is called. IWatcher w = new AgentWatcher(this); try { oro.registerEvent(w); } catch (EventRegistrationException ere) { Logger.log("Alterite module won't work because the \"new agent\" event " + "couldn't be registered.\n", VerboseLevel.WARNING); } } @Override public IServiceProvider getServiceProvider() { return this; } public void add(String id){ if (!checkAlreadyPresent(id)) { agents.put(id, new AgentModel(id, serverParameters)); } } public boolean checkAlreadyPresent(String id) { ExtendedIterator<? extends Resource> sameResource = oro.getResource(id).listSameAs(); Set<String> agentList = agents.keySet(); while (sameResource.hasNext()){ if (agentList.contains(sameResource.next().getLocalName())) return true; } return false; } public Map<String, AgentModel> getAgents() { return agents; } @RPCMethod ( category = "agents", desc = "Returns the set of agents I'm aware of (ie, for whom I have " + "a cognitive model)." ) public Set<String> listAgents() { return agents.keySet(); } @Override public void consumeEvent(UUID watcherId, OroEvent e) { if (OroServer.BLINGBLING) Logger.log("22, v'la les agents!\n", VerboseLevel.WARNING); try { for (String s : (Set<String>) Helpers.deserialize(e.getEventContext(), Set.class)) add(s); } catch (OntologyServerException ose) //thrown if an unparsable unicode character is encountered { Logger.log("\nBetter to exit now until proper handling of this " + "exception is added by maintainers! You can help by sending a " + "mail to openrobots@laas.fr with the exception stack.\n ", VerboseLevel.FATAL_ERROR); System.exit(-1); } catch (IllegalArgumentException iae) //thrown if the string couldn't be deserialized to the expect object. { Logger.log("\nBetter to exit now until proper handling of this " + "exception is added by maintainers! You can help by sending a " + "mail to openrobots@laas.fr with the exception stack.\n ", VerboseLevel.FATAL_ERROR); System.exit(-1); } //JAVA7: Note that in Java7, both exception can be grouped in one catch clause. } @RPCMethod( category = "agents", desc="adds one or several statements (triplets S-P-O) to a specific " + "agent model, in long term memory." ) public void addForAgent(String id, Set<String> rawStmts) throws IllegalStatementException, AgentNotFoundException { addForAgent(id, rawStmts, MemoryProfile.DEFAULT.toString()); } @RPCMethod( category = "agents", desc="try to add news statements to a specific agent model in long " + "term memory, if they don't lead to inconsistencies (return false " + "if at least one stmt wasn't added)." ) public boolean safeAdd(String id, Set<String> rawStmts) throws IllegalStatementException, AgentNotFoundException { return safeAdd(id, rawStmts, MemoryProfile.DEFAULT.toString()); } @RPCMethod( category = "agents", desc="adds one or several statements (triplets S-P-O) to a specific " + "agent model associated with a memory profile." ) public void addForAgent(String id, Set<String> rawStmts, String memProfile) throws IllegalStatementException, AgentNotFoundException { IOntologyBackend oro = getModelForAgent(id); Set<Statement> stmtsToAdd = new HashSet<Statement>(); for (String rawStmt : rawStmts) { if (rawStmt == null) throw new IllegalStatementException("Got a null statement to add!"); stmtsToAdd.add(oro.createStatement(rawStmt)); } Logger.log(id + ": "); oro.add(stmtsToAdd, MemoryProfile.fromString(memProfile), false); } @RPCMethod( desc="try to add news statements to a specific agent model with a " + "specific memory profile, if they don't lead to inconsistencies " + "(return false if at least one stmt wasn't added)." ) public boolean safeAdd(String id, Set<String> rawStmts, String memProfile) throws IllegalStatementException, AgentNotFoundException { Set<Statement> stmtsToAdd = new HashSet<Statement>(); for (String rawStmt : rawStmts) { if (rawStmt == null) throw new IllegalStatementException("Got a null statement to add!"); stmtsToAdd.add(oro.createStatement(rawStmt)); } Logger.log(id + ": "); return oro.add(stmtsToAdd, MemoryProfile.fromString(memProfile), true); } @RPCMethod( category = "agents", desc="removes one or several statements (triplets S-P-O) from a specific agent model, in long term memory." ) public void removeForAgent(String id, Set<String> rawStmts) throws IllegalStatementException, AgentNotFoundException { IOntologyBackend oro = getModelForAgent(id); for (String rawStmt : rawStmts) { Logger.log(id + ": "); oro.remove(oro.createStatement(rawStmt)); } } @RPCMethod( category = "agents", desc="updates one or several statements (triplets S-P-O) in a specific agent model, in long term memory." ) public void updateForAgent(String id, Set<String> rawStmts) throws IllegalStatementException, AgentNotFoundException { IOntologyBackend oro = getModelForAgent(id); Set<Statement> stmtsToUpdate = new HashSet<Statement>(); for (String rawStmt : rawStmts) { if (rawStmt == null) throw new IllegalStatementException("Got a null statement to add!"); stmtsToUpdate.add(oro.createStatement(rawStmt)); } Logger.log(id + ": "); oro.update(stmtsToUpdate); } @RPCMethod( category = "agents", desc="updates one or several statements (triplets S-P-O) in a specific agent model, in long term memory." ) public void updateForAgent(String id, Set<String> rawStmts) throws IllegalStatementException, AgentNotFoundException { IOntologyBackend oro = getModelForAgent(id); Set<Statement> stmtsToUpdate = new HashSet<Statement>(); for (String rawStmt : rawStmts) { if (rawStmt == null) throw new IllegalStatementException("Got a null statement to add!"); stmtsToUpdate.add(oro.createStatement(rawStmt)); } Logger.log(id + ": "); oro.update(stmtsToUpdate); } @RPCMethod( category = "agents", desc="tries to identify a resource given a set of partially defined " + "statements and restrictions in an specific agent model." ) public Set<String> findForAgent(String id, String varName, Set<String> statements, Set<String> filters) throws IllegalStatementException, OntologyServerException { IOntologyBackend oro = getModelForAgent(id); Logger.log(id + ": "); Logger.log("Searching resources in the ontology...\n"); Set<PartialStatement> stmts = new HashSet<PartialStatement>(); if (varName.startsWith("?")) varName = varName.substring(1); Logger.log(" matching following statements:\n", VerboseLevel.VERBOSE); for (String ps : statements) { Logger.log("\t- " + ps + "\n", VerboseLevel.VERBOSE); stmts.add(oro.createPartialStatement(ps)); } if (filters != null) { Logger.log("with these restrictions:\n", VerboseLevel.VERBOSE); for (String f : filters) Logger.log("\t- " + f + "\n", VerboseLevel.VERBOSE); } Set<RDFNode> raw = oro.find(varName, stmts, filters); Set<String> res = new HashSet<String>(); for (RDFNode n : raw) { try { Resource node = n.as(Resource.class); if (node != null && !node.isAnon()) //node == null means that the current query solution contains no resource named after the given key. res.add(Namespaces.toLightString(node)); } catch (ClassCastException e) { try { Literal l = n.as(Literal.class); res.add(l.getLexicalForm()); } catch (ClassCastException e2) { Logger.log("Failed to convert the result of the 'find' to a string!", VerboseLevel.SERIOUS_ERROR); throw new OntologyServerException("Failed to convert the " + "result of the 'find' to a string!"); } } } return res; } @RPCMethod( category = "agents", desc="tries to identify a resource given a set of partially defined " + "statements in an specific agent model." ) public Set<String> findForAgent(String id, String varName, Set<String> statements) throws IllegalStatementException, OntologyServerException { return findForAgent(id, varName, statements, null); } @RPCMethod( category = "agents", desc="exports the cognitive model of a given agent to an OWL file. The provided path must be writable by the server." ) public void save(String id, String path) throws AgentNotFoundException, OntologyServerException { IOntologyBackend oro = getModelForAgent(id); Logger.log(id + ": ", VerboseLevel.IMPORTANT); oro.save(path); } @RPCMethod( category = "agents", desc="returns a list of properties that helps to differentiate individuals for a specific agent." ) public List<Set<String>> discriminateForAgent(String id, Set<String> rawConcepts) throws AgentNotFoundException, OntologyServerException, NotFoundException, NotComparableException { IOntologyBackend oro = getModelForAgent(id); CategorizationModule catModule = new CategorizationModule(oro); Logger.log(id + ": ", VerboseLevel.IMPORTANT); return catModule.discriminate(rawConcepts); } private IOntologyBackend getModelForAgent(String id) throws AgentNotFoundException { AgentModel a = agents.get(id); if (a == null) throw new AgentNotFoundException("I couldn't find the agent " + id + "."); IOntologyBackend oro = a.model; return oro; } }
package com.opengamma.engine.function.config; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.HashSet; import java.util.List; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.opengamma.OpenGammaRuntimeException; import com.opengamma.engine.function.AbstractFunction; import com.opengamma.engine.function.InMemoryFunctionRepository; /** * Constructs and bootstraps an {@link InMemoryFunctionRepository} based on configuration * provided in a Fudge-encoded stream. */ public class RepositoryFactory { private static final Logger s_logger = LoggerFactory.getLogger(RepositoryFactory.class); public static InMemoryFunctionRepository constructRepository(RepositoryConfiguration configuration) { InMemoryFunctionRepository repository = new InMemoryFunctionRepository(); if (configuration.getFunctions() != null) { for (FunctionConfiguration functionConfig : configuration.getFunctions()) { if (functionConfig instanceof ParameterizedFunctionConfiguration) { addParameterizedFunctionConfiguration(repository, (ParameterizedFunctionConfiguration) functionConfig); } else if (functionConfig instanceof StaticFunctionConfiguration) { addStaticFunctionConfiguration(repository, (StaticFunctionConfiguration) functionConfig); } else { s_logger.warn("Unhandled function configuration {}, ignoring", functionConfig); } } } return repository; } protected static void addParameterizedFunctionConfiguration(InMemoryFunctionRepository repository, ParameterizedFunctionConfiguration functionConfig) { // TODO kirk 2010-02-17 -- This method needs to be WAY more robust. // TODO kirk 2010-05-24 -- One way is to separate out the various error cases // to make them more clear by limiting what goes on in the individual try{} blocks. try { Class<?> definitionClass = Class.forName(functionConfig.getDefinitionClassName()); AbstractFunction functionDefinition = instantiateDefinition(definitionClass, functionConfig.getParameter()); repository.addFunction(functionDefinition); } catch (ClassNotFoundException e) { throw new OpenGammaRuntimeException("Unable to resolve classes", e); } catch (InstantiationException e) { throw new OpenGammaRuntimeException("Unable to instantiate classes", e); } catch (IllegalAccessException e) { throw new OpenGammaRuntimeException("Unable to instantiate classes", e); } catch (SecurityException e) { throw new OpenGammaRuntimeException("Unable to instantiate classes", e); } catch (NoSuchMethodException e) { throw new OpenGammaRuntimeException("No available constructor for " + functionConfig.getDefinitionClassName(), e); } catch (IllegalArgumentException e) { throw new OpenGammaRuntimeException("Arguments to constructor not right constructing " + functionConfig.getDefinitionClassName(), e); } catch (InvocationTargetException e) { throw new OpenGammaRuntimeException("Invocation of constructor failed", e); } } protected static AbstractFunction instantiateDefinition(Class<?> definitionClass, List<String> parameterList) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException { //CSOFF constructors: //CSON for (Constructor<?> constructor : definitionClass.getConstructors()) { final Class<?>[] parameters = constructor.getParameterTypes(); final Object[] args = new Object[parameters.length]; int used = 0; for (int i = 0; i < parameters.length; i++) { if (parameters[i] == String.class) { if (i < parameterList.size()) { args[i] = (String) parameterList.get(i); used++; } else { continue constructors; } } else { if (i == parameters.length - 1) { used = parameterList.size(); if (parameters[i] == String[].class) { args[i] = parameterList.subList(i, used).toArray(new String[used - i]); } else if (parameters[i].isAssignableFrom(List.class)) { args[i] = parameterList.subList(i, used); } else if (parameters[i].isAssignableFrom(Set.class)) { args[i] = new HashSet<String>(parameterList.subList(i, used)); } else { continue constructors; } } else { continue constructors; } } } if (used != parameterList.size()) { continue; } return (AbstractFunction) constructor.newInstance(args); } throw new NoSuchMethodException("No suitable constructor found in class " + definitionClass); } protected static void addStaticFunctionConfiguration(InMemoryFunctionRepository repository, StaticFunctionConfiguration functionConfig) { // TODO kirk 2010-02-17 -- This method needs to be WAY more robust. try { Class<?> definitionClass = Class.forName(functionConfig.getDefinitionClassName()); AbstractFunction functionDefinition = (AbstractFunction) definitionClass.newInstance(); repository.addFunction(functionDefinition); } catch (ClassNotFoundException e) { throw new OpenGammaRuntimeException("Unable to resolve classes", e); } catch (InstantiationException e) { s_logger.error("Exception instantiating function", e); throw new OpenGammaRuntimeException("Unable to instantiate classes", e); } catch (IllegalAccessException e) { throw new OpenGammaRuntimeException("Unable to instantiate classes", e); } } }
package com.mercadopago.android.px.internal.util; import android.content.Context; import android.content.res.Configuration; import android.os.Build; import android.os.LocaleList; import android.support.annotation.NonNull; public final class LocaleUtil { private LocaleUtil() { } public static String getLanguage(@NonNull final Context context) { final Configuration configuration = context.getResources().getConfiguration(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { final LocaleList locales = configuration.getLocales(); if (!locales.isEmpty()) { return locales.get(0).toLanguageTag(); } } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { return configuration.locale.toLanguageTag(); } return configuration.locale.getLanguage(); } }
package com.mercadopago.android.px.services.util; import android.content.Context; import android.content.res.Configuration; import android.os.Build; import android.os.LocaleList; import android.support.annotation.NonNull; public final class LocaleUtil { private LocaleUtil() { } public static String getLanguage(@NonNull final Context context) { final Configuration configuration = context.getResources().getConfiguration(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { final LocaleList locales = configuration.getLocales(); if (!locales.isEmpty()) { return locales.get(0).getLanguage(); } } return configuration.locale.getLanguage(); } }
package com.bq.oss.lib.queries.builder; import java.util.Date; import java.util.Iterator; import java.util.List; import com.bq.oss.lib.queries.BooleanQueryLiteral; import com.bq.oss.lib.queries.DateQueryLiteral; import com.bq.oss.lib.queries.DoubleQueryLiteral; import com.bq.oss.lib.queries.ListQueryLiteral; import com.bq.oss.lib.queries.LongQueryLiteral; import com.bq.oss.lib.queries.QueryNodeImpl; import com.bq.oss.lib.queries.StringQueryLiteral; import com.bq.oss.lib.queries.request.QueryNode; import com.bq.oss.lib.queries.request.QueryOperator; import com.bq.oss.lib.queries.request.ResourceQuery; public class ResourceQueryBuilder { private final ResourceQuery resourceQuery; /** * Constructs a ResourceQueryBuilder with the given ResourceQuery * * @param resourceQuery to create the ResourceQueryBuilder */ public ResourceQueryBuilder(ResourceQuery resourceQuery) { if (resourceQuery == null) { this.resourceQuery = new ResourceQuery(); } else { this.resourceQuery = resourceQuery; } } public ResourceQueryBuilder() { this(null); } /** * Adds a query node with a String value to the {@link ResourceQuery} * * @param field object of the operation * @param value of the node * @param operator one of [$EQ, $NE, $LIKE] * @return ResourceQueryBuilder */ public ResourceQueryBuilder add(String field, String value, QueryOperator operator) { StringQueryLiteral literal = new StringQueryLiteral(value); QueryNodeImpl queryNode = new QueryNodeImpl(operator, field, literal); resourceQuery.addQueryNode(queryNode); return this; } /** * Adds a query node with String value and $EQ operator to the {@link ResourceQuery} * * @param field object of the operation * @param value of the node * @return ResourceQueryBuilder */ public ResourceQueryBuilder add(String field, String value) { return add(field, value, QueryOperator.$EQ); } /** * Adds a query node with a Date value to the {@link ResourceQuery} * * @param field object of the operation * @param value of the node * @param operator one of [$EQ, $NE, $GT, $GTE, $LT, $LTE] * @return ResourceQueryBuilder */ public ResourceQueryBuilder add(String field, Date value, QueryOperator operator) { DateQueryLiteral literal = new DateQueryLiteral(value); QueryNodeImpl queryNode = new QueryNodeImpl(operator, field, literal); resourceQuery.addQueryNode(queryNode); return this; } /** * Adds a query node with a Boolean value to the {@link ResourceQuery} * * @param field object of the operation * @param operator one of [$EQ, $NE] * @return ResourceQueryBuilder */ public ResourceQueryBuilder add(String field, QueryOperator operator) { BooleanQueryLiteral literal = new BooleanQueryLiteral(); QueryNodeImpl queryNode = new QueryNodeImpl(operator, field, literal); resourceQuery.addQueryNode(queryNode); return this; } /** * Adds a query node with a List value to the {@link ResourceQuery} * * @param field object of the operation * @param value of the node * @param operator one of [$EQ, $NE, $IN, $ALL] * @return ResourceQueryBuilder */ public ResourceQueryBuilder add(String field, List value, QueryOperator operator) { ListQueryLiteral literal = new ListQueryLiteral(value); QueryNodeImpl queryNode = new QueryNodeImpl(operator, field, literal); resourceQuery.addQueryNode(queryNode); return this; } /** * Adds a query node with a Double value to the {@link ResourceQuery} * * @param field object of the operation * @param value of the node * @param operator one of [$EQ, $NE, $GT, $GTE, $LT, $LTE] * @return ResourceQueryBuilder */ public ResourceQueryBuilder add(String field, Double value, QueryOperator operator) { DoubleQueryLiteral literal = new DoubleQueryLiteral(value); QueryNodeImpl queryNode = new QueryNodeImpl(operator, field, literal); resourceQuery.addQueryNode(queryNode); return this; } /** * Adds a query node with a Long value to the {@link ResourceQuery} * * @param field object of the operation * @param value of the node * @param operator one of [$EQ, $NE, $GT, $GTE, $LT, $LTE] * @return ResourceQueryBuilder */ public ResourceQueryBuilder add(String field, Long value, QueryOperator operator) { LongQueryLiteral literal = new LongQueryLiteral(value); QueryNodeImpl queryNode = new QueryNodeImpl(operator, field, literal); resourceQuery.addQueryNode(queryNode); return this; } /** * Removes all nodes from the ResourceQuery whose field is given field * * @param field object of the operation * @return ResourceQueryBuilder */ public ResourceQueryBuilder remove(String field) { Iterator<QueryNode> queryNodeIterator = resourceQuery.iterator(); while (queryNodeIterator.hasNext()) { QueryNode queryNode = queryNodeIterator.next(); if (queryNode.getField().matches(field)) { queryNodeIterator.remove(); } } return this; } /** * Builds a ResourceQuery * * @return ResourceQuery */ public ResourceQuery build() { return resourceQuery; } }
package org.quickbundle.modules.lock; import org.quickbundle.base.beans.factory.RmBeanFactory; import org.quickbundle.modules.lock.rmlock.service.IRmLockService; import org.quickbundle.modules.lock.rmlock.util.IRmLockConstants; import org.quickbundle.modules.lock.rmlock.vo.RmLockVo; import org.quickbundle.project.RmProjectHelper; import org.quickbundle.project.listener.RmRequestMonitor; import org.quickbundle.tools.helper.RmDateHelper; import org.quickbundle.tools.helper.RmPopulateHelper; public class RmLockHelper { private static String DEFAULT_LOCK_BS_KEYWORD = "default"; private static IRmLockService getLockService() { return (IRmLockService)RmBeanFactory.getBean(IRmLockConstants.SERVICE_KEY); } /** * try { if(RmLockHelper.lock("1000100000000000001", "2")) { // } else { throw new RuntimeException(": 2"); } } finally { RmLockHelper.unlock("1000100000000000001", "2"); } * @param user_id * @param value * @return */ public static boolean lock(String user_id, String value) { return lock(user_id, value, DEFAULT_LOCK_BS_KEYWORD); } /** * try { if(RmLockHelper.lock("1000100000000000001", "2", "a"); ) { // } else { throw new RuntimeException(": a->2"); } } finally { RmLockHelper.unlock("1000100000000000001", "2", "a"); } * @param user_id null""user_id * @param value * @param bs_keyword * @return */ public static boolean lock(String user_id, String value, String bs_keyword) { RmLockVo vo = new RmLockVo(); vo.setUser_id(user_id); vo.setBs_keyword(bs_keyword); vo.setLock_content(value); vo.setLock_date(RmDateHelper.getSysTimestamp()); if(RmRequestMonitor.getCurrentThreadRequest() != null) { RmPopulateHelper.populate(vo, RmRequestMonitor.getCurrentThreadRequest()); } boolean result = getLockService().executeLock(vo); return result; } /** * * @param user_id * @param value */ public static void unlock(String user_id, String value) { unlock(user_id, value, DEFAULT_LOCK_BS_KEYWORD); } /** * * @param user_id * @param value * @param bs_keyword */ public static void unlock(String user_id, String value, String bs_keyword) { IRmLockService ls = getLockService(); int sum = ls.deleteLock(user_id, value, bs_keyword); if(sum != 1) { // throw new RmLockException(""); } } public static void releaseLock(String user_id) { if(getLockService().queryByCondition("USER_ID='" + user_id + "'", null).size() > 0) { RmProjectHelper.getCommonServiceInstance().doUpdate("delete from RM_LOCK where USER_ID=" + user_id); } } }
package org.rabix.engine.processor.impl; import java.util.Set; import java.util.UUID; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import org.rabix.bindings.model.Job; import org.rabix.engine.event.Event; import org.rabix.engine.event.Event.EventStatus; import org.rabix.engine.event.Event.EventType; import org.rabix.engine.event.Event.PersistentEventType; import org.rabix.engine.event.impl.ContextStatusEvent; import org.rabix.engine.model.ContextRecord; import org.rabix.engine.model.ContextRecord.ContextStatus; import org.rabix.engine.processor.EventProcessor; import org.rabix.engine.processor.handler.EventHandlerException; import org.rabix.engine.processor.handler.HandlerFactory; import org.rabix.engine.repository.EventRepository; import org.rabix.engine.repository.JobRepository; import org.rabix.engine.repository.TransactionHelper; import org.rabix.engine.repository.TransactionHelper.TransactionException; import org.rabix.engine.service.CacheService; import org.rabix.engine.service.ContextRecordService; import org.rabix.engine.service.JobService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.Inject; /** * Event processor implementation */ public class EventProcessorImpl implements EventProcessor { private static final Logger logger = LoggerFactory.getLogger(EventProcessorImpl.class); public final static long SLEEP = 100; private final BlockingQueue<Event> events = new LinkedBlockingQueue<>(); private final BlockingQueue<Event> externalEvents = new LinkedBlockingQueue<>(); private final ExecutorService executorService = Executors.newSingleThreadExecutor(); private final AtomicBoolean stop = new AtomicBoolean(false); private final AtomicBoolean running = new AtomicBoolean(false); private final HandlerFactory handlerFactory; private final ContextRecordService contextRecordService; private final TransactionHelper transactionHelper; private final CacheService cacheService; private final JobRepository jobRepository; private final EventRepository eventRepository; private final JobService jobService; @Inject public EventProcessorImpl(HandlerFactory handlerFactory, ContextRecordService contextRecordService, TransactionHelper transactionHelper, CacheService cacheService, EventRepository eventRepository, JobRepository jobRepository, JobService jobService) { this.handlerFactory = handlerFactory; this.contextRecordService = contextRecordService; this.transactionHelper = transactionHelper; this.cacheService = cacheService; this.eventRepository = eventRepository; this.jobRepository = jobRepository; this.jobService = jobService; } public void start() { executorService.execute(new Runnable() { @Override public void run() { final AtomicReference<Event> eventReference = new AtomicReference<Event>(null); while (!stop.get()) { try { eventReference.set(externalEvents.poll()); if (eventReference.get() == null) { running.set(false); Thread.sleep(SLEEP); continue; } running.set(true); transactionHelper.doInTransaction(new TransactionHelper.TransactionCallback<Void>() { @Override public Void call() throws TransactionException { if (!handle(eventReference.get())) { eventRepository.delete(eventReference.get().getEventGroupId()); return null; } cacheService.flush(eventReference.get().getContextId()); if (checkForReadyJobs(eventReference.get())) { Set<Job> readyJobs = jobRepository.getReadyJobsByGroupId(eventReference.get().getEventGroupId()); jobService.handleJobsReady(readyJobs, eventReference.get().getContextId(), eventReference.get().getProducedByNode()); } eventRepository.delete(eventReference.get().getEventGroupId()); return null; } }); } catch (Exception e) { logger.error("EventProcessor failed to process event {}.", eventReference.get(), e); try { Job job = jobRepository.get(eventReference.get().getContextId()); job = Job.cloneWithMessage(job, "EventProcessor failed to process event:\n" + eventReference.get().toString()); jobRepository.update(job); jobService.handleJobRootFailed(job); } catch (Exception ex) { logger.error("Failed to call jobFailed handler for job after event {} failed.", e, ex); } try { cacheService.clear(eventReference.get().getContextId()); eventRepository.update(eventReference.get().getEventGroupId(), eventReference.get().getPersistentType(), Event.EventStatus.FAILED); invalidateContext(eventReference.get().getContextId()); } catch (Exception ehe) { logger.error("Failed to invalidate Context {}.", eventReference.get().getContextId(), ehe); } } } } }); } private boolean checkForReadyJobs(Event event) { switch (event.getType()) { case INIT: return true; case JOB_STATUS_UPDATE: if (PersistentEventType.JOB_STATUS_UPDATE_COMPLETED.equals(event.getPersistentType())) { return true; } return false; default: break; } return false; } private boolean handle(Event event) throws TransactionException { while (event != null) { try { ContextRecord context = contextRecordService.find(event.getContextId()); if (context != null && (context.getStatus().equals(ContextStatus.FAILED) || context.getStatus().equals(ContextStatus.ABORTED))) { logger.info("Skip event {}. Context {} has been invalidated.", event, context.getId()); return false; } handlerFactory.get(event.getType()).handle(event); } catch (EventHandlerException e) { throw new TransactionException(e); } event = events.poll(); } return true; } /** * Invalidates context */ private void invalidateContext(UUID contextId) throws EventHandlerException { handlerFactory.get(Event.EventType.CONTEXT_STATUS_UPDATE).handle(new ContextStatusEvent(contextId, ContextStatus.FAILED)); } @Override public void stop() { stop.set(true); running.set(false); } public boolean isRunning() { return running.get(); } public void send(Event event) throws EventHandlerException { if (stop.get()) { return; } if (event.getType().equals(EventType.INIT)) { addToQueue(event); return; } handlerFactory.get(event.getType()).handle(event); } public void addToQueue(Event event) { if (stop.get()) { return; } this.events.add(event); } @Override public void persist(Event event) { if (stop.get()) { return; } eventRepository.insert(event.getEventGroupId(), event.getPersistentType(), event, EventStatus.UNPROCESSED); } public void addToExternalQueue(Event event) { if (stop.get()) { return; } this.externalEvents.add(event); } }
package org.gbif.registry; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.actuate.autoconfigure.solr.SolrHealthContributorAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.solr.SolrAutoConfiguration; import org.springframework.boot.context.properties.EnableConfigurationProperties; @SpringBootApplication( scanBasePackages = { "org.gbif.ws.server.interceptor", "org.gbif.ws.server.aspect", "org.gbif.ws.server.filter", "org.gbif.ws.security", "org.gbif.query", "org.gbif.registry"}, exclude = { SolrAutoConfiguration.class, SolrHealthContributorAutoConfiguration.class }) @MapperScan("org.gbif.registry.persistence.mapper") @EnableConfigurationProperties public class RegistryWsApplication { public static void main(String[] args) { SpringApplication.run(RegistryWsApplication.class, args); } }
package net.runelite.client.plugins.skybox; import com.google.inject.Inject; import com.google.inject.Provides; import java.awt.Color; import java.io.IOException; import java.io.InputStream; import net.runelite.api.Client; import net.runelite.api.Constants; import net.runelite.api.GameState; import net.runelite.api.Player; import net.runelite.api.coords.LocalPoint; import net.runelite.api.coords.WorldPoint; import net.runelite.api.events.BeforeRender; import net.runelite.api.events.GameStateChanged; import net.runelite.client.config.ConfigManager; import net.runelite.client.eventbus.Subscribe; import net.runelite.client.plugins.Plugin; import net.runelite.client.plugins.PluginDescriptor; @PluginDescriptor( name = "Skybox", description = "Draws an oldschool styled skybox", enabledByDefault = false, tags = {"sky"} ) public class SkyboxPlugin extends Plugin { @Inject private Client client; @Inject private SkyboxPluginConfig config; private Skybox skybox; @Override public void startUp() throws IOException { try (InputStream in = SkyboxPlugin.class.getResourceAsStream("skybox.txt")) { skybox = new Skybox(in, "skybox.txt"); } } @Override public void shutDown() { client.setSkyboxColor(0); skybox = null; } @Provides SkyboxPluginConfig provideConfig(ConfigManager configManager) { return configManager.getConfig(SkyboxPluginConfig.class); } private int mapChunk(int cx, int cy, int plane) { cx -= client.getBaseX() / 8; cy -= client.getBaseY() / 8; int[][] instanceTemplateChunks = client.getInstanceTemplateChunks()[plane]; // Blending can access this out of bounds, so do a range check if (cx < 0 || cx >= instanceTemplateChunks.length || cy < 0 || cy >= instanceTemplateChunks[cx].length) { return -1; } return instanceTemplateChunks[cx][cy]; } @Subscribe public void onBeforeRender(BeforeRender r) { if (skybox == null || client.getGameState() != GameState.LOGGED_IN) { return; } Player player = client.getLocalPlayer(); if (player == null) { return; } Color overrideColor = WorldPoint.getMirrorPoint(player.getWorldLocation(), true).getY() < Constants.OVERWORLD_MAX_Y ? config.customOverworldColor() : config.customOtherColor(); if (overrideColor != null) { client.setSkyboxColor(overrideColor.getRGB()); return; } int px, py; if (client.getOculusOrbState() == 1) { px = client.getOculusOrbFocalPointX(); py = client.getOculusOrbFocalPointY(); } else { LocalPoint p = player.getLocalLocation(); px = p.getX(); py = p.getY(); } // Inverse of camera location / 2 int spx = -((client.getCameraX() - px) >> 1); int spy = -((client.getCameraY() - py) >> 1); int baseX = client.getBaseX(); int baseY = client.getBaseY(); client.setSkyboxColor(skybox.getColorForPoint( baseX + ((px + spx) / 128.f), baseY + ((py + spy) / 128.f), baseX + (px / 128), baseY + (py / 128), client.getPlane(), client.getTextureProvider().getBrightness(), client.isInInstancedRegion() ? this::mapChunk : null )); } @Subscribe public void onGameStateChanged(GameStateChanged gameStateChanged) { if (gameStateChanged.getGameState() == GameState.LOGIN_SCREEN) { client.setSkyboxColor(0); } } }
package com.apptentive.android.example; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import com.apptentive.android.example.push.RegistrationIntentService; import com.apptentive.android.sdk.Apptentive; /** * This is an example integration of Apptentive. * * @author Sky Kelsey */ public class ExampleActivity extends Activity { private static String LOG_TAG = "Apptentive Example"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // GCM: Start IntentService to register this application. Intent intent = new Intent(this, RegistrationIntentService.class); startService(intent); } @Override protected void onStart() { super.onStart(); Apptentive.onStart(this); } @Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); // Only engage if this window is gaining focus. if (hasFocus) { Apptentive.handleOpenedPushNotification(this); } } @Override protected void onStop() { super.onStop(); Apptentive.onStop(this); } /** * Provide a simple feedback button in your app. */ public void onMessageCenterButtonPressed(@SuppressWarnings("unused") View view) { Apptentive.showMessageCenter(this); } }
package test.xml.mapping; import gov.nih.nci.system.applicationservice.ApplicationException; import gov.nih.nci.system.applicationservice.ApplicationService; import gov.nih.nci.system.client.ApplicationServiceProvider; import gov.nih.nci.system.client.util.xml.JAXBMarshaller; import gov.nih.nci.system.client.util.xml.JAXBUnmarshaller; import gov.nih.nci.system.client.util.xml.Marshaller; import gov.nih.nci.system.client.util.xml.Unmarshaller; import gov.nih.nci.system.client.util.xml.XMLUtility; import gov.nih.nci.system.client.util.xml.caCOREMarshaller; import gov.nih.nci.system.client.util.xml.caCOREUnmarshaller; import gov.nih.nci.system.query.hibernate.HQLCriteria; import java.io.File; import java.io.FileWriter; import java.text.SimpleDateFormat; import java.util.Collection; import java.util.Date; import java.util.List; import javax.xml.XMLConstants; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.Source; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamSource; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import javax.xml.validation.Validator; import junit.framework.TestCase; import org.apache.log4j.Logger; import org.hibernate.criterion.DetachedCriteria; import org.jdom.Element; import org.jdom.input.SAXBuilder; import org.springframework.aop.framework.Advised; import org.w3c.dom.Document; /** * @author Dan Dumitru * */ public abstract class SDKXMLDataTestBase extends TestCase { private static Logger log = Logger.getLogger(SDKXMLDataTestBase.class); protected boolean useGMETags; private String namespaceUriPrefix=null; private String uriPrefix = "gme://caCORE.caCORE/3.2/"; private String filepathPrefix = "c:/temp/"; private String filepathSuffix = "_test.xml"; private ApplicationService appService; private Marshaller marshaller; private Unmarshaller unmarshaller; protected XMLUtility myUtil; protected void setUp() throws Exception { super.setUp(); appService = ApplicationServiceProvider.getApplicationService(); // appService = ApplicationServiceProvider.getApplicationServiceFromUrl(url); // JAXB boolean validate = true; boolean includeXmlDeclaration = true; String namespacePrefix = "gme://caCORE.caCORE/3.2/"; String jaxbContextName = "gov.nih.nci.cacoresdk.domain.inheritance.abstrakt:gov.nih.nci.cacoresdk.domain.inheritance.childwithassociation:gov.nih.nci.cacoresdk.domain.inheritance.childwithassociation.sametable:gov.nih.nci.cacoresdk.domain.inheritance.implicit:gov.nih.nci.cacoresdk.domain.inheritance.multiplechild:gov.nih.nci.cacoresdk.domain.inheritance.multiplechild.sametable:gov.nih.nci.cacoresdk.domain.inheritance.onechild:gov.nih.nci.cacoresdk.domain.inheritance.onechild.sametable:gov.nih.nci.cacoresdk.domain.inheritance.parentwithassociation:gov.nih.nci.cacoresdk.domain.inheritance.parentwithassociation.sametable:gov.nih.nci.cacoresdk.domain.inheritance.twolevelinheritance:gov.nih.nci.cacoresdk.domain.inheritance.twolevelinheritance.sametable:gov.nih.nci.cacoresdk.domain.inheritance.twolevelinheritance.sametablerootlevel:gov.nih.nci.cacoresdk.domain.interfaze:gov.nih.nci.cacoresdk.domain.manytomany.bidirectional:gov.nih.nci.cacoresdk.domain.manytomany.unidirectional:gov.nih.nci.cacoresdk.domain.manytoone.unidirectional:gov.nih.nci.cacoresdk.domain.manytoone.unidirectional.withjoin:gov.nih.nci.cacoresdk.domain.onetomany.bidirectional:gov.nih.nci.cacoresdk.domain.onetomany.bidirectional.withjoin:gov.nih.nci.cacoresdk.domain.onetomany.selfassociation:gov.nih.nci.cacoresdk.domain.onetomany.unidirectional:gov.nih.nci.cacoresdk.domain.onetomany.unidirectional.withjoin:gov.nih.nci.cacoresdk.domain.onetoone.bidirectional:gov.nih.nci.cacoresdk.domain.onetoone.bidirectional.withjoin:gov.nih.nci.cacoresdk.domain.onetoone.multipleassociation:gov.nih.nci.cacoresdk.domain.onetoone.multipleassociation.withjoin:gov.nih.nci.cacoresdk.domain.onetoone.unidirectional:gov.nih.nci.cacoresdk.domain.onetoone.unidirectional.withjoin:gov.nih.nci.cacoresdk.domain.other.datatype:gov.nih.nci.cacoresdk.domain.other.differentpackage:gov.nih.nci.cacoresdk.domain.other.differentpackage.associations:gov.nih.nci.cacoresdk.domain.other.levelassociation:gov.nih.nci.cacoresdk.domain.other.primarykey:gov.nih.nci.cacoresdk.domain.other.validationtype"; //Marshaller marshaller = new JAXBMarshaller(includeXmlDeclaration,jaxbContextName); // Use this constructor if you plan to pass the namespace prefix with each call instead marshaller = new JAXBMarshaller(includeXmlDeclaration,jaxbContextName,namespacePrefix); unmarshaller = new JAXBUnmarshaller(validate,jaxbContextName); // JAXB myUtil = new XMLUtility(marshaller, unmarshaller); useGMETags=Boolean.parseBoolean(System.getProperty("useGMETags")); namespaceUriPrefix=System.getProperty("namespaceUriPrefix"); String outputDir = System.getProperty("outputDir"); if(outputDir!=null){ filepathPrefix=outputDir; } } protected void tearDown() throws Exception { appService = null; super.tearDown(); } protected ApplicationService getApplicationService() { return appService; } public static String getTestCaseName() { return "SDK Base Test Case"; } protected void toXML(Object resultObj) throws Exception { toXML(resultObj,0); } protected void toXML(Object resultObj, int counter) throws Exception { String filename = filepathPrefix + resultObj.getClass().getSimpleName(); if (counter != 0){ filename += ("_test"+counter+".xml"); } else { filename += filepathSuffix; } File myFile = new File(filename); log.info("writing data to file "+myFile.getAbsolutePath()); FileWriter myWriter = new FileWriter(myFile); myUtil.toXML(resultObj, myWriter); myWriter.close(); } protected Object fromXML(Object resultObj) throws Exception { File myFile = new File(filepathPrefix + resultObj.getClass().getSimpleName() + filepathSuffix); Object myObj = (Object) myUtil.fromXML(myFile); return myObj; } protected org.jdom.Document getDocument(String filename) { org.jdom.Document doc; try { SAXBuilder builder = new SAXBuilder(); doc = builder.build(filename); } catch (Exception ex) { throw new RuntimeException("Error reading XML Data file: " + filename,ex); } return doc; } protected boolean validateXMLData(Object resultObj, Class klass) throws Exception { String schemaFilename=klass.getPackage().getName() + ".xsd"; if (useGMETags){ schemaFilename=namespaceUriPrefix+schemaFilename; schemaFilename=schemaFilename.replace(": schemaFilename=schemaFilename.replace("/", "_"); } log.debug("* * * schemaFilename: "+schemaFilename); return validateXMLData(resultObj, klass, schemaFilename); } protected boolean validateXMLData(Object resultObj, Class klass, String schemaFilename) throws Exception { File myFile = new File(filepathPrefix + resultObj.getClass().getSimpleName() + filepathSuffix); log.debug("myFile: "+myFile+"\n\n"); log.debug("myFile absolute path: "+myFile.getAbsolutePath()+"\n\n"); myUtil.fromXML(myFile); log.debug("Has validation exceptions: " +((JAXBUnmarshaller)unmarshaller).hasValidationExceptions() ); return !((JAXBUnmarshaller)unmarshaller).hasValidationExceptions(); // DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder(); // Document document = parser.parse(myFile); // SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); // try { // log.debug("Validating " + klass.getName() + " against the schema......\n\n"); // log.debug("Schema filename is: "+schemaFilename+"\n\n"); // Source schemaFile = new StreamSource(Thread.currentThread().getContextClassLoader().getResourceAsStream(schemaFilename)); // log.debug("Schema filename: "+schemaFile+"\n\n"); // Schema schema = factory.newSchema(schemaFile); // Validator validator = schema.newValidator(); // //validator.validate(new DOMSource(document)); // log.debug(klass.getName() + " has been validated!!!\n\n"); // } catch (Exception e) { // log.error(klass.getName() + " has failed validation!!! Error reason is: \n\n" + e.getMessage(),e); // throw e; // return true; } // TODO :: figure out how to get xpath to work when the XML Data file does not contain a Namespace prefix // protected List<Element> queryXMLData(Object obj, String xpath) // throws JaxenException { /** * Uses xpath to query the generated XSD Verifies that common elements * attributes(name, type) are present Verifies that the element 'name' * attribute matches the class name * * @throws Exception */ protected void validateClassElements(Object resultObj) throws Exception{ validateClassElements(resultObj,Class.forName(getClassName(resultObj)).getSimpleName()); } protected void validateClassElements(Object resultObj, String gmeClassName) throws Exception { String klassName = getClassName(resultObj); org.jdom.Document doc = getDocument(filepathPrefix + resultObj.getClass().getSimpleName() + filepathSuffix); Element klassElt = doc.getRootElement(); if (useGMETags){ assertEquals(gmeClassName, klassElt.getName()); } else{ assertEquals(Class.forName(klassName).getSimpleName(), klassElt.getName()); assertEquals(klassElt.getNamespaceURI(),uriPrefix + Class.forName(klassName).getPackage().getName()); } } /** * Uses xpath to query the generated XSD Verifies that common elements * attributes(name, type) are present Verifies that the element 'name' * attribute matches the class name * * @throws Exception */ protected void validateAttribute(Object resultObj, String attributeName, Object attributeValue) throws Exception { // log.debug("Validating Class attributes from: " + filepathPrefix + resultObj.getClass().getSimpleName() + filepathSuffix); org.jdom.Document doc = getDocument(filepathPrefix + resultObj.getClass().getSimpleName() + filepathSuffix); // TODO :: figure out how to get xpath to work when the XML Data file does not contain a Namespace prefix // String xpath = "" + Class.forName(klassName).getSimpleName(); // log.debug("xpath: " + xpath); // List<Element> elts = queryXMLData(doc, xpath); // assertEquals(1, elts.size()); Element klassElt = doc.getRootElement(); String compareValue = null; if (attributeValue != null) compareValue = attributeValue.toString(); assertEquals(klassElt.getAttributeValue(attributeName),compareValue); } /** * Uses xpath to query the generated XSD Verifies that common elements * attributes(name, type) are present Verifies that the element 'name' * attribute matches the class name * * @throws Exception */ protected void validateDateAttribute(Object resultObj, String attributeName, Date attributeValue) throws Exception { // log.debug("Validating Class attributes from: " + filepathPrefix + resultObj.getClass().getSimpleName() + filepathSuffix); org.jdom.Document doc = getDocument(filepathPrefix + resultObj.getClass().getSimpleName() + filepathSuffix); // TODO :: figure out how to get xpath to work when the XML Data file does not contain a Namespace prefix // String xpath = "" + Class.forName(klassName).getSimpleName(); // log.debug("xpath: " + xpath); // List<Element> elts = queryXMLData(doc, xpath); // assertEquals(1, elts.size()); Element klassElt = doc.getRootElement(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd kk:mm:ss.S"); //e.g.: 2007-10-01T00:00:00.000-07:00 String attributeDate = klassElt.getAttributeValue(attributeName).replace('T', ' '); Date xmlDate = sdf.parse(attributeDate.substring(0, 21)); assertEquals(0,xmlDate.compareTo(attributeValue)); } /** * Uses xpath to query the generated XSD Verifies that common elements * attributes(name, type) are present Verifies that the element 'name' * attribute matches the class name * * @throws Exception */ protected void validateAssociation(Object resultObj, String associatedKlassName, String roleName) throws Exception { // log.debug("Validating Class association from: " + filepathPrefix + resultObj.getClass().getSimpleName() + filepathSuffix); org.jdom.Document doc = getDocument(filepathPrefix + resultObj.getClass().getSimpleName() + filepathSuffix); Element klassElt = doc.getRootElement(); List<Element> children = klassElt.getChildren(); assertNotNull(children); assertEquals(1,countChildren(children,roleName)); Element roleNameElt = locateChild(children,roleName); assertNotNull(roleNameElt); assertEquals(roleNameElt.getName(),roleName); children = roleNameElt.getChildren(); assertNotNull(children); Element associatedKlassElt = locateChild(children,associatedKlassName); assertNotNull(associatedKlassElt); } /** * Uses xpath to query the generated XSD Verifies that common elements * attributes(name, type) are present Verifies that the element 'name' * attribute matches the class name * * @throws Exception */ protected void validateIso90210Element(Object resultObj, String iso90210ElementName, String iso90210ElementAttributeName, Object iso90210ElementAttributeValue) throws Exception { // log.debug("Validating Class association from: " + filepathPrefix + resultObj.getClass().getSimpleName() + filepathSuffix); org.jdom.Document doc = getDocument(filepathPrefix + resultObj.getClass().getSimpleName() + filepathSuffix); Element klassElt = doc.getRootElement(); List<Element> children = klassElt.getChildren(); assertNotNull(children); assertEquals(1,countChildren(children,iso90210ElementName)); Element iso90210Element = locateChild(children,iso90210ElementName); assertNotNull(iso90210Element); assertEquals(iso90210Element.getName(),iso90210ElementName); String compareValue = null; if (iso90210ElementAttributeValue != null) compareValue = iso90210ElementAttributeValue.toString(); assertEquals(iso90210Element.getAttributeValue(iso90210ElementAttributeName),compareValue); } @SuppressWarnings("unchecked") protected Collection search(DetachedCriteria criteria, String type) throws ApplicationException { return appService.query(criteria, type); } @SuppressWarnings("deprecation") protected Collection search(HQLCriteria criteria, String type) throws ApplicationException { return appService.query(criteria, type); } @SuppressWarnings("unchecked") protected Collection search(String path, Object searchObject) throws ApplicationException { return appService.search(path, searchObject); } private Element locateChild(List<Element> eltList, String roleName){ for (Element elt:eltList){ if (elt.getName().equals(roleName)) return elt; } return null; } private int countChildren(List<Element> eltList, String roleName){ int counter=0; for (Element elt:eltList){ if (elt.getName().equals(roleName)) counter++; } return counter; } protected String getClassName(Object resultObj){ String klassName = resultObj.getClass().getName(); if (klassName.indexOf('$') > 0) { return klassName.substring(0, klassName.indexOf('$')); } return klassName; } }
package io.selendroid.driver; import io.selendroid.support.BaseAndroidTest; import io.selendroid.webviewdrivertests.HtmlTestData; import org.junit.Assert; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.TimeoutException; import org.openqa.selenium.WebDriverException; import org.openqa.selenium.WebElement; import java.util.Iterator; import java.util.List; import java.util.concurrent.TimeUnit; import static org.hamcrest.core.IsInstanceOf.instanceOf; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; public class ExecuteAsyncScriptTest extends BaseAndroidTest { private JavascriptExecutor executor; @Before public void asyncSetup() { driver().manage().timeouts().setScriptTimeout(0, TimeUnit.SECONDS); openWebdriverTestPage(HtmlTestData.ABOUT_BLANK); executor = driver(); } @Test public void shouldNotTimeoutIfCallbackInvokedImmediately() { Object result = executor.executeAsyncScript("arguments[arguments.length - 1](123);"); Assert.assertThat(result, instanceOf(Number.class)); assertEquals(123, ((Number) result).intValue()); } @Test public void shouldBeAbleToReturnJavascriptPrimitivesFromAsyncScripts_NeitherNullNorUndefined() { assertEquals(123, ((Number) executor.executeAsyncScript( "arguments[arguments.length - 1](123);")).longValue()); assertEquals("abc", executor.executeAsyncScript("arguments[arguments.length - 1]('abc');")); assertFalse((Boolean) executor.executeAsyncScript("arguments[arguments.length - 1](false);")); assertTrue((Boolean) executor.executeAsyncScript("arguments[arguments.length - 1](true);")); } @Test public void shouldBeAbleToReturnJavascriptPrimitivesFromAsyncScripts_NullAndUndefined() { assertNull(executor.executeAsyncScript("arguments[arguments.length - 1](null)")); assertNull(executor.executeAsyncScript("arguments[arguments.length - 1]()")); } @Test public void shouldBeAbleToReturnAnArrayLiteralFromAnAsyncScript() { Object result = executor.executeAsyncScript("arguments[arguments.length - 1]([]);"); assertNotNull("Expected not to be null!", result); assertThat(result, instanceOf(List.class)); assertTrue(((List<?>) result).isEmpty()); } @Test public void shouldBeAbleToReturnAnArrayObjectFromAnAsyncScript() { Object result = executor.executeAsyncScript("arguments[arguments.length - 1](new Array());"); assertNotNull("Expected not to be null!", result); assertThat(result, instanceOf(List.class)); assertTrue(((List<?>) result).isEmpty()); } @Test public void shouldBeAbleToReturnArraysOfPrimitivesFromAsyncScripts() { Object result = executor.executeAsyncScript( "arguments[arguments.length - 1]([null, 123, 'abc', true, false]);"); assertNotNull(result); assertThat(result, instanceOf(List.class)); Iterator<?> results = ((List<?>) result).iterator(); assertNull(results.next()); assertEquals(123, ((Number) results.next()).longValue()); assertEquals("abc", results.next()); assertTrue((Boolean) results.next()); assertFalse((Boolean) results.next()); assertFalse(results.hasNext()); } @Test public void shouldBeAbleToReturnWebElementsFromAsyncScripts() { Object result = executor.executeAsyncScript("arguments[arguments.length - 1](document.body);"); assertThat(result, instanceOf(WebElement.class)); assertEquals("body", ((WebElement) result).getTagName().toLowerCase()); } @Test public void shouldBeAbleToReturnArraysOfWebElementsFromAsyncScripts() { Object result = executor.executeAsyncScript( "arguments[arguments.length - 1]([document.body, document.body]);"); assertNotNull(result); assertThat(result, instanceOf(List.class)); List<?> list = (List<?>) result; assertEquals(2, list.size()); assertThat(list.get(0), instanceOf(WebElement.class)); assertThat(list.get(1), instanceOf(WebElement.class)); assertEquals("body", ((WebElement) list.get(0)).getTagName().toLowerCase()); assertEquals(list.get(0), list.get(1)); } @Test public void shouldTimeoutIfScriptDoesNotInvokeCallback() { try { // Script is expected to be async and explicitly callback, so this should timeout. executor.executeAsyncScript("return 1 + 2;"); fail("Should have thrown a TimeOutException!"); } catch (TimeoutException exception) { // Do nothing. } } @Test public void shouldTimeoutIfScriptDoesNotInvokeCallbackWithAZeroTimeout() { try { executor.executeAsyncScript("window.setTimeout(function() {}, 0);"); fail("Should have thrown a TimeOutException!"); } catch (TimeoutException exception) { // Do nothing. } } @Test public void shouldNotTimeoutIfScriptCallsbackInsideAZeroTimeout() { executor.executeAsyncScript( "var callback = arguments[arguments.length - 1];" + "window.setTimeout(function() { callback(123); }, 0)"); } @Test public void shouldTimeoutIfScriptDoesNotInvokeCallbackWithLongTimeout() { driver().manage().timeouts().setScriptTimeout(500, TimeUnit.MILLISECONDS); try { executor.executeAsyncScript( "var callback = arguments[arguments.length - 1];" + "window.setTimeout(callback, 1500);"); fail("Should have thrown a TimeOutException!"); } catch (TimeoutException exception) { // Do nothing. } } @Test public void shouldDetectPageLoadsWhileWaitingOnAnAsyncScriptAndReturnAnError() { driver().manage().timeouts().setScriptTimeout(100, TimeUnit.MILLISECONDS); try { executor.executeAsyncScript("window.location = '" + HtmlTestData.JAVASCRIPT_PAGE + "';"); fail(); } catch (WebDriverException expected) { } } @Test public void shouldCatchErrorsWhenExecutingInitialScript() { try { executor.executeAsyncScript("throw Error('you should catch this!');"); fail(); } catch (WebDriverException expected) { } } @Test public void shouldNotTimeoutWithMultipleCallsTheFirstOneBeingSynchronous() { driver().manage().timeouts().setScriptTimeout(10, TimeUnit.MILLISECONDS); assertTrue((Boolean) executor.executeAsyncScript("arguments[arguments.length - 1](true);")); assertTrue((Boolean) executor.executeAsyncScript( "var cb = arguments[arguments.length - 1]; window.setTimeout(function(){cb(true);}, 9);")); } @Test @Ignore("We currently don't propagate causes properly when redirecting through Standalone.") public void shouldCatchErrorsWithMessageAndStacktraceWhenExecutingInitialScript() { String js = "function functionB() { throw Error('errormessage'); };" + "function functionA() { functionB(); };" + "functionA();"; try { executor.executeAsyncScript(js); fail("Expected an exception"); } catch (WebDriverException e) { assertTrue(e.getMessage(), e.getMessage().contains("errormessage")); StackTraceElement [] st = e.getCause().getStackTrace(); boolean seen = false; for (StackTraceElement s: st) { if (s.getMethodName().equals("functionB")) { seen = true; } } assertTrue("Stacktrace has not js method info", seen); } } @Test public void shouldBeAbleToPassMultipleArgumentsToAsyncScripts() { Number result = (Number) executor .executeAsyncScript("arguments[arguments.length - 1](arguments[0] + arguments[1]);", 1, 2); assertEquals(3, result.intValue()); } }
// This file is part of Serleena. // Nicola Mometto, Filippo Sestini, Tobia Tesan, Sebastiano Valle. // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // all copies or substantial portions of the Software. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. package com.kyloth.serleena.sensors; import android.content.Context; import android.os.PowerManager; import com.kyloth.serleena.common.GeoPoint; import com.kyloth.serleena.common.UnregisteredObserverException; import java.util.HashMap; import java.util.Map; /** * Concretizza ILocationManager. * * Fornisce al codice client la posizione dell'utente utilizzando il modulo * GPS del dispositivo con il supporto delle API Android. Assicura la * comunicazione dei dati agli observer registrati mantenendo sveglio il * processore quando necessario. * * @author Filippo Sestini <sestini.filippo@gmail.com> * @version 1.0.0 */ public class WakefulLocationManager implements ILocationManager { private static WakefulLocationManager instance; private PowerManager pm; private WakeupManager wm; private NormalLocationManager nlm; private Map<ILocationObserver, IWakeupObserver> observers; private IWakeupObserver gpsUpdateObserver; private int gpsUpdateInterval; private Map<ILocationObserver, Integer> intervals; private GeoPoint lastKnownLocation; private WakefulLocationManager(Context context) { wm = WakeupManager.getInstance(context); pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE); observers = new HashMap<ILocationObserver, IWakeupObserver>(); intervals = new HashMap<ILocationObserver, Integer>(); final WakefulLocationManager me = this; class GpsWakeup implements IWakeupObserver, ILocationObserver { @Override public void onLocationUpdate(GeoPoint loc) { lastKnownLocation = loc; } @Override public void onWakeup() { me.getSingleUpdate(this); } } gpsUpdateObserver = new GpsWakeup(); } }
package uk.ac.cam.cl.echo.extrusionfinder.server.zernike; import java.awt.geom.Point2D; import java.awt.image.BufferedImage; import java.awt.image.DataBufferByte; public class Zernike { /** * Computes the sum n*(n-1)*...2*1 * @param n a number * @return n! */ private static double factorial(int n) { double x = 1; for (int i=n; i>0; i--) x *= i; return x; } /** * Computes a Zernike moment * @param zps the points to use to compute the Zernike moment * @param zpsSize the number of points in zps * @param n a value * @param m the exponent to raise the position of each ZernikePoint to * @return a Zernike moment */ private static Complex zernikeMoment(ZernikePoint[] zps, int zpsSize, int n, int m) { int p = (n-m)/2; int q = (n+m)/2; Complex v = new Complex(0, 0); double[] gm = new double[p+1]; for (int i=0; i<=p; i+=2) gm[i] = factorial(n-i) / (factorial(i) * factorial(q-i) * factorial(p-i)); for (int i=1; i<=p; i+=2) gm[i] = -1 * factorial(n-i) / (factorial(i) * factorial(q-i) * factorial(p-i)); for (int i=0; i<zpsSize; i++) { double r = zps[i].modulus; Complex z = zps[i].getPosition(m); double c = zps[i].getIntensity(); Complex Vnl = new Complex(0, 0); for (int j=0; j<=p; j++) { Vnl = Vnl.add(z.multiply(gm[j] * Math.pow(r, n-2*j))); } v = v.add(Vnl.conjugate().multiply(c)); } v = v.multiply((n+1)/Math.PI); return v; } /** * Computes Zernike moments of an image to a particular degree using a circle * with the specified radius and center. * @param img the image to use for computing Zernike oments * @param imgWidth the width of img in pixels * @param degree the degree to which to compute the Zernike moments to * @param center the point at which to take Zernike moments from * @param radius the radius of the circle to use * @return a vector of the magitudes of each Zernike moment */ public static double[] zernikeMoments(byte[] img, int imgWidth, int degree, Point2D center, double radius) { int imgHeight = img.length / imgWidth; int zpsSize = (int) (Math.PI*radius*radius); ZernikePoint[] zps = new ZernikePoint[zpsSize]; int totalIntensity = 0; int i=0; for (int y0=0; y0<imgHeight; y0++) { double y = (y0-center.getY())/radius; for (int x0=0; x0<imgWidth; x0++) { double x = (x0-center.getX())/radius; double r = Math.hypot(x, y); if (r <= 1) { int c = img[x0+y0*imgWidth] & 0xFF; if (c > 0) { r = Math.max(r, 1e-9); Complex z = new Complex(x/r, y/r); zps[i] = new ZernikePoint(z, c, degree); totalIntensity += c; i++; } } } } zpsSize = i; for (i=0; i<zpsSize; i++) zps[i].normalizeIntensity(totalIntensity); double[] zvalues = new double[(int)(2*Math.pow(degree,2)+4*degree-Math.pow(-1,degree)+1)/8]; i=0; for (int n=0; n<degree; n++) { for (int m = 0; m <= n; m++) { if ((n - m) % 2 == 0) { Complex z = zernikeMoment(zps, zpsSize, n, m); zvalues[i] = z.modulus(); i++; } } } return zvalues; } /** * Computes Zernike moments of an image to a particular degree using a circle * with the specified radius and center. The image is converted to grayscale * format if it is not already. * @param img the image to use for computing Zernike oments * @param degree the degree to which to compute the Zernike moments to * @param center the point at which to take Zernike moments from * @param radius the radius of the circle to use * @return a vector of the magitudes of each Zernike moment */ public static double[] zernikeMoments(BufferedImage img, int degree, Point2D center, double radius) { if (img.getType() != BufferedImage.TYPE_BYTE_GRAY) { BufferedImage t = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_BYTE_GRAY); t.getGraphics().drawImage(img, 0, 0, null); img = t; } byte[] imgBytes = ((DataBufferByte) img.getData().getDataBuffer()).getData(); return zernikeMoments(imgBytes, img.getWidth(), degree, center, radius); } }
package com.darcye.sqlite; import java.util.ArrayList; import java.util.List; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; /** * a simple class to encapsulate the db operations, remember : * <strong >don't </strong>forget to {@link #closeDB()} when you don't need to connect to database. * @author Darcy yeguozhong@yeah.net * */ public class DbSqlite { private Context mContext; private SQLiteDatabase mSQLiteDatabase; private String dbPath; /** * constructor would create or open the database * @param context * @param dbPath the path of db file */ public DbSqlite(Context context,String dbPath) { this.mContext = context; this.dbPath = dbPath; openDB(); } public DbSqlite(Context context, SQLiteDatabase db){ this.mContext = context; this.mSQLiteDatabase = db; this.dbPath = db.getPath(); openDB(); } public SQLiteDatabase getSQLiteDatabase(){ return mSQLiteDatabase; } Context getContext(){ return mContext; } /** * update a record * * @param table the table to update in * @param values a map from column names to new column values. null is a valid value that will be translated to NULL. * @param whereClause the optional WHERE clause to apply when updating. Passing null will update all rows. * @param whereArgs You may include ?s in the where clause, which will be replaced by the values from whereArgs. The values will be bound as Strings. * @return the number of rows affected , or -1 if an error occurred */ public int update(String table, ContentValues values,String whereClause, String[] whereArgs) { try { openDB(); return mSQLiteDatabase.update(table, values, whereClause, whereArgs); } catch (Exception ex) { ex.printStackTrace(); return -1; } } /** * insert a record * * @param table * @param values * @return the row ID of the newly inserted row, or -1 if an error occurred */ public long insert(String table, ContentValues values) { try { openDB(); return mSQLiteDatabase.insertOrThrow(table, null, values); } catch (Exception ex) { ex.printStackTrace(); return -1; } } /** * * insert or replace a record by if its value of primary key has exsits * * @param table * @param values * @return the row ID of the newly inserted row, or -1 if an error occurred */ public long insertOrReplace(String table, ContentValues values){ try { openDB(); return mSQLiteDatabase.replaceOrThrow(table, null, values); } catch (SQLException ex) { ex.printStackTrace(); throw ex; } } /** * insert mutil records at one time * @param table * @param listVal * @return success return true */ public boolean batchInsert(final String table,final List<ContentValues> listVal){ try { openDB(); DBTransaction.transact(this , new DBTransaction.DBTransactionInterface(){ @Override public void onTransact() { for (ContentValues contentValues : listVal) { mSQLiteDatabase.insertOrThrow(table, null, contentValues); } } }); return true; } catch (SQLException ex) { ex.printStackTrace(); throw ex; } } /** * delele by the condition * * @param table table the table to delete from * @param whereClause whereClause the optional WHERE clause to apply when deleting. Passing null will delete all rows. * @param whereArgs whereArgs You may include ?s in the where clause, which will be replaced by the values from whereArgs. The values will be bound as Strings. * @return the number of rows affected if a whereClause is passed in, 0 otherwise. To remove all rows and get a count pass "1" as the whereClause. */ public int delete(String table, String whereClause, String[] whereArgs) { try { openDB(); return mSQLiteDatabase.delete(table, whereClause, whereArgs); } catch (SQLException ex) { ex.printStackTrace(); throw ex; } } /** * a more flexible query by condition * * @param table The table name to compile the query against. * @param columns A list of which columns to return. Passing null will return all columns, which is discouraged to prevent reading data from storage that isn't going to be used. * @param selection A filter declaring which rows to return, formatted as an SQL WHERE clause (excluding the WHERE itself). Passing null will return all rows for the given table. * @param groupBy A filter declaring how to group rows, formatted as an SQL GROUP BY clause (excluding the GROUP BY itself). Passing null will cause the rows to not be grouped. * @param having A filter declare which row groups to include in the cursor, if row grouping is being used, formatted as an SQL HAVING clause (excluding the HAVING itself). Passing null will cause all row groups to be included, and is required when row grouping is not being used. * @param orderBy How to order the rows, formatted as an SQL ORDER BY clause (excluding the ORDER BY itself). Passing null will use the default sort order, which may be unordered. * @param selectionArgs selectionArgs You may include ?s in selection, which will be replaced by the values from selectionArgs, in order that they appear in the selection. The values will be bound as Strings. * @return if exceptions happen or no match records, then return null */ public List<ResultSet> query(String table, String[] columns, String selection,String[] selectionArgs, String groupBy, String having, String orderBy) { Cursor cursor = null; try { openDB(); cursor = mSQLiteDatabase.query(table, columns, selection, selectionArgs, groupBy, having, orderBy); if(cursor.getCount() < 1){ return null; }else{ List<ResultSet> resultList = new ArrayList<ResultSet>(); parseCursorToResult(cursor, resultList); return resultList; } } catch (SQLException ex) { ex.printStackTrace(); throw ex; } finally { if(cursor!=null) cursor.close(); } } /** * a simple query by condition * * @param table * @param columns * @param selection * @param selectionArgs * @return */ public List<ResultSet> query(String table, String[] columns, String selection, String[] selectionArgs) { return query(table, columns, selection, selectionArgs, null, null, null); } /** * paging query * * @param table * @param columns * @param selection * @param selectionArgs * @param groupBy * @param having * @param orderBy cann't be null if define page and pageSize * @param page first page is 1 * @param pageSize * @return */ public PagingList<ResultSet> pagingQuery(String table, String[] columns, String selection,String[] selectionArgs, String groupBy, String having, String orderBy,int page,int pageSize){ if(orderBy == null && pageSize != 0) throw new SQLException("orderBy cann't be null if define page and pageSize"); String orderWithLimit; if(orderBy != null && pageSize != 0){ orderWithLimit = String.format("%s LIMIT %s , %s", orderBy, (page-1)*pageSize, pageSize); }else{ orderWithLimit = orderBy; } Cursor cursor = null; Cursor totalCursor = null; try { openDB(); PagingList<ResultSet> resultList = new PagingList<ResultSet>(); totalCursor = mSQLiteDatabase.query(table, new String[]{"count(*) as totalSize"}, selection, selectionArgs, groupBy, having,null); if(totalCursor.moveToNext()){ int totalSize = totalCursor.getInt(0); resultList.setTotalSize(totalSize); } cursor = mSQLiteDatabase.query(table, columns, selection, selectionArgs, groupBy, having, orderWithLimit); if(cursor.getCount() < 1){ return resultList; }else{ parseCursorToResult(cursor, resultList); return resultList; } } catch (SQLException ex) { ex.printStackTrace(); throw ex; } finally { if(cursor!=null) cursor.close(); if(totalCursor != null) totalCursor.close(); } } /** * Execute a single SQL statement that is NOT a SELECT/INSERT/UPDATE/DELETE. * * @param sql * @param bindArgs * @return */ public boolean execSQL(String sql, Object... bindArgs) { try { openDB(); mSQLiteDatabase.execSQL(sql, bindArgs); return true; } catch (SQLException ex) { ex.printStackTrace(); throw ex; } } /** * execute raw query sql * * @param sql the SQL query. The SQL string must not be ; terminated * @param bindArgs You may include ?s in where clause in the query, which will be replaced by the values from selectionArgs. The values will be bound as Strings. * @return return result as List or null */ public List<ResultSet> execQuerySQL(String sql, String... bindArgs){ Cursor cursor = null; try{ openDB(); cursor = mSQLiteDatabase.rawQuery(sql, bindArgs); if(cursor.getCount() < 1){ return null; } List<ResultSet> resultList = new ArrayList<ResultSet>(); parseCursorToResult(cursor, resultList); return resultList; }catch(SQLException ex) { ex.printStackTrace(); throw ex; }finally{ if(cursor!=null) cursor.close(); } } /** * open database */ public void openDB() { if (mSQLiteDatabase == null || mSQLiteDatabase.isOpen() == false) mSQLiteDatabase = SQLiteDatabase.openOrCreateDatabase(dbPath, null); } /** * close database */ public void closeDB() { if (mSQLiteDatabase != null && mSQLiteDatabase.isOpen()) { mSQLiteDatabase.close(); } } public String getDbPath() { return dbPath; } /** * set data in cursor to ResultSet List * @param cursor * @param resultList the data will set in it */ private void parseCursorToResult(Cursor cursor,List<ResultSet> resultList){ int columnCount; int columnType; Object columnVal = null; while (cursor.moveToNext()) { columnCount = cursor.getColumnCount(); ResultSet result = new ResultSet(); for (int index = 0; index < columnCount; ++index) { columnType = cursor.getType(index); switch (columnType) { case Cursor.FIELD_TYPE_BLOB: columnVal = cursor.getBlob(index); break; case Cursor.FIELD_TYPE_FLOAT: columnVal = cursor.getFloat(index); break; case Cursor.FIELD_TYPE_INTEGER: columnVal = cursor.getInt(index); break; case Cursor.FIELD_TYPE_NULL: columnVal = null; break; default: columnVal = cursor.getString(index); break; } result.setValue(cursor.getColumnName(index), columnVal); } resultList.add(result); } } }
package com.justjournal.db; import sun.jdbc.rowset.CachedRowSet; import java.util.ArrayList; import java.util.Collection; /** * Access account information for a specific user or all users * of Just Journal. * * @author Lucas Holt * @version 1.0 * @since 1.0 */ public final class UserDao { /** * Add a user to justjournal including their name, username and * password. * * @param user * @return True if successful, false otherwise. */ public static final boolean add(UserTo user) { boolean noError = true; int records = 0; final String sqlStmt = "Insert INTO user (username,password,name) VALUES('" + user.getUserName() + "',sha1('" + user.getPassword() + "'),'" + user.getName() + "');"; try { records = SQLHelper.executeNonQuery(sqlStmt); } catch (Exception e) { noError = false; } if (records != 1) noError = false; return noError; } /** * update the user record with a new first name. * usernames can not be changed. * passwords can be changed via the * <code>com.justjournal.ctl.ChangePasswordSubmit</code> class. * * @param user * @return * @see com.justjournal.ctl.ChangePasswordSubmit */ public static final boolean update(UserTo user) { boolean noError = true; final String sqlStmt = "Update user SET name='" + user.getName() + "' WHERE id='" + user.getId() + "' LIMIT 1;"; try { SQLHelper.executeNonQuery(sqlStmt); } catch (Exception e) { noError = false; } return noError; } /** * Deletes a user from the database. This * should not be called by cancel account. Accounts * should be deactivated. * * @param userId * @return true if successful, false otherwise */ public static final boolean delete(int userId) { boolean noError = true; final String sqlStmt = "DELETE FROM user WHERE id='" + userId + "' LIMIT 1;"; if (userId > 0) { try { SQLHelper.executeNonQuery(sqlStmt); } catch (Exception e) { noError = false; } } else { noError = false; } return noError; } /** * Retrieve a user given the user id. * Does NOT retrieve password or sha1 password. * * @param userId * @return user's info */ public static final UserTo view(int userId) { UserTo user = new UserTo(); CachedRowSet rs = null; String sqlStmt = "SELECT username, name, since FROM user WHERE id='" + userId + "' LIMIT 1;"; try { rs = SQLHelper.executeResultSet(sqlStmt); if (rs.next()) { user.setId(userId); user.setUserName(rs.getString("username")); // username user.setName(rs.getString("name")); // first name user.setSince(rs.getInt("since")); } rs.close(); } catch (Exception e1) { if (rs != null) { try { rs.close(); } catch (Exception e) { // NOTHING TO DO } } } return user; } /** * Retrieve a user give the user name. * Does not retrieve the password or * sha1 password. * * @param userName * @return user's info */ public static final UserTo view(String userName) { UserTo user = new UserTo(); CachedRowSet rs = null; String sqlStmt = "SELECT id, name, since from user WHERE username='" + userName + "' Limit 1;"; try { rs = SQLHelper.executeResultSet(sqlStmt); if (rs.next()) { user.setId(rs.getInt("id")); user.setUserName(userName); user.setName(rs.getString("name")); // first name user.setSince(rs.getInt("since")); } rs.close(); } catch (Exception e1) { if (rs != null) { try { rs.close(); } catch (Exception e) { // NOTHING TO DO } } } return user; } /** * Retrieve the list of all users including their name, * username, sign up year (since), and unique id. * * @return All users of just journal. */ public static final Collection<UserTo> memberList() { ArrayList<UserTo> users = new ArrayList<UserTo>(125); UserTo usr; final String sqlStatement = "call memberlist();"; try { final CachedRowSet RS = SQLHelper.executeResultSet(sqlStatement); while (RS.next()) { usr = new UserTo(); usr.setId(RS.getInt(1)); usr.setUserName(RS.getString(2)); usr.setName(RS.getString(3)); usr.setSince(RS.getInt(4)); users.add(usr); } RS.close(); } catch (Exception e1) { } return users; } }
package com.relteq.sirius.db; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.ByteBuffer; import java.nio.channels.*; import java.sql.*; /** * Administers the Sirius Database */ public class Admin { /** * Initializes the database. * If the database exists, it is dropped and recreated. * @throws SQLException * @throws IOException */ public static void init() throws SQLException, IOException { SQLExec exec = new SQLExec(); Parameters params = Parameters.get(); exec.setSrc("sql" + File.separator + params.getDriver() + File.separator + "sirius-db-schema.sql"); exec.setUrl(params.getUrl()); exec.setDriver(DriverManager.getDriver(exec.getUrl()).getClass().getName()); exec.setUserid(null == params.getUser() ? "" : params.getUser()); exec.setPassword(null == params.getPassword() ? "" : params.getPassword()); SQLExec.OnError onerror = new SQLExec.OnError(); onerror.setValue("continue"); exec.setOnerror(onerror); exec.setPrint(true); exec.execute(); } /** * Executes SQL statements */ public static class SQLExec extends org.apache.tools.ant.taskdefs.SQLExec { public SQLExec() { org.apache.tools.ant.Project project = new org.apache.tools.ant.Project(); project.init(); setProject(project); setTaskType("sql"); setTaskName("sql"); } /** * Sets the resource name of the SQL script to be run * @param name the resource name * @throws IOException */ public void setSrc(String name) throws IOException { int ind[] = {-1, -1}; ind[0] = name.lastIndexOf(File.separator); ind[1] = name.lastIndexOf('.'); if (-1 == ind[1] || ind[1] <= ind[0]) ind[1] = name.length(); File file = File.createTempFile(name.substring(ind[0] + 1, ind[1]), ind[1] >= name.length() ? ".sql" : name.substring(ind[1])); file.deleteOnExit(); InputStream is = Admin.class.getClassLoader().getResourceAsStream(name); OutputStream os = new FileOutputStream(file); copy(is, os); is.close(); os.close(); super.setSrc(file); } /** * Copies an input stream to an output stream * @param is the input stream * @param os the output stream * @throws IOException */ private static void copy(InputStream is, OutputStream os) throws IOException { ReadableByteChannel ich = Channels.newChannel(is); WritableByteChannel och = Channels.newChannel(os); final ByteBuffer buf = ByteBuffer.allocateDirect(16384); while (ich.read(buf) != -1) { buf.flip(); och.write(buf); buf.compact(); } buf.flip(); while (buf.hasRemaining()) och.write(buf); ich.close(); och.close(); } } }
package com.ryong21.encode; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.ryong21.io.Consumer; public class Encoder implements Runnable { private Logger log = LoggerFactory.getLogger(Encoder.class); private volatile int leftSize = 0; private final Object mutex = new Object(); private Speex speex = new Speex(); private int frameSize; private Consumer consumer; private byte[] processedData = new byte[1024]; private short[] rawdata = new short[1024]; private volatile boolean isRunning; public Encoder(Consumer consumer) { super(); this.consumer = consumer; speex.init(); frameSize = speex.getFrameSize(); log.debug("frameSize {}", frameSize); } public void run() { android.os.Process .setThreadPriority(android.os.Process.THREAD_PRIORITY_URGENT_AUDIO); int getSize = 0; while (this.isRunning()) { synchronized (mutex) { while (isIdle()) { try { mutex.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } synchronized (mutex) { short[] temp = new short[frameSize]; for (int i = 0; i < temp.length; i++) { System.arraycopy(rawdata, i * frameSize, temp, 0, frameSize); getSize = speex.encode(temp, 0, processedData, frameSize); // log.error("encoded size {}", getSize); if (getSize > 0) { consumer.putData(System.currentTimeMillis(), processedData, getSize); } } } setIdle(); } } public void putData(short[] data, int size) { synchronized (mutex) { System.arraycopy(data, 0, rawdata, 0, size); this.leftSize = size; mutex.notify(); } } public boolean isIdle() { return leftSize == 0 ? true : false; } public void setIdle() { leftSize = 0; } public void setRunning(boolean isRunning) { synchronized (mutex) { this.isRunning = isRunning; if (this.isRunning) { mutex.notify(); } } } public boolean isRunning() { synchronized (mutex) { return isRunning; } } }
package com.twu.biblioteca; import java.util.ArrayList; import java.util.List; public class Library { private List<Book> availableBooks; private List<Book> issuedBooks; private List<String> availableServices; public String getWelcomeMsg(){ return "Welcome! to Bibloteca."; } public String checkOut(int bookNumber){ try { transferBookFromAvailableToIssued(bookNumber - 1); return "Thank you! Enjoy the book"; } catch (Exception e){ return "That book is not available."; } } public String returnBook(final String bookName){ Book bookToReturn = getIssuedBookByName(bookName); if(bookToReturn!=null){ transferBookFromIssuedToAvailable(bookToReturn); return "Thank you for returning the book."; } return "That is not a valid book to return."; } public List<Book> getAvailableBooks(){ return availableBooks; } public List<String> getAvailableServices() { return availableServices; } public Library(){ availableBooks = new ArrayList<>(); availableBooks.add(new Book("My Book", "xyz", "2000")); availableBooks.add(new Book("My Book2","abc", "2001")); availableBooks.add(new Book("My Book3","xyz", "2002")); availableServices = new ArrayList<>(); availableServices.add("List All books"); availableServices.add("Return Book"); issuedBooks = new ArrayList<>(); } private void transferBookFromIssuedToAvailable(Book issuedBook){ issuedBooks.remove(issuedBook); availableBooks.add(issuedBook); } private void transferBookFromAvailableToIssued(int bookNumber) { Book toBeIssued = availableBooks.remove(bookNumber); issuedBooks.add(toBeIssued); } private Book getIssuedBookByName(String bookName){ for(Book issuedBook : this.issuedBooks) { if (issuedBook.getName().equals(bookName)) { return issuedBook; } } return null; } @Override public String toString() { return "Library{" + "availableBooks=" + availableBooks + '}'; } }
package modelo; public class Main { public static void main(String[] args) throws Exception { Cliente c = new Cliente(); System.out.println(c.getNome() == null); System.out.println(c.getCpf() == null); c.setNome("Nome de Teste c.setCpf("11133355577"); System.out.println(c.getNome().equals("Nome de Teste System.out.println(c.getCpf().equals("11133355577")); System.out.println(c.getTelefonePrincipal() == null); System.out.println(c.getTelefoneContato() == null); c.setTelefonePrincipal(new Telefone("53", "88779977")); c.setTelefoneContato(new Telefone("32549875")); System.out.println(c.getTelefonePrincipal().equals(new Telefone("53", "88779977"))); System.out.println(c.getTelefoneContato().equals(new Telefone("32549875"))); try { c.setCpf("1133355577"); throw new Exception("falhou"); } catch (IllegalArgumentException e) { System.out.println("exception ok"); } System.out.println("Testes OK"); } }
package crystal.model; import java.awt.Image; import java.util.Collection; import java.util.HashMap; import java.util.Map; import javax.swing.ImageIcon; import crystal.Constants; import crystal.model.DataSource.RepoKind; import crystal.model.LocalStateResult.LocalState; import crystal.model.RevisionHistory.Action; import crystal.model.RevisionHistory.Capable; import crystal.model.RevisionHistory.Ease; import crystal.model.RevisionHistory.When; /** * Represents a conflict detection question. * * @author brun * */ public class Relationship implements Result{ /** * Represents a conflict detection answer. * * @author brun * */ public static String SAME = "SAME"; public static String AHEAD = "AHEAD"; public static String BEHIND = "BEHIND"; public static String MERGECLEAN = "MERGE"; public static String MERGECONFLICT = "CONFLICT"; public static String COMPILECONFLICT = "COMPILECONFLICT"; public static String TESTCONFLICT = "TESTCONFLICT"; public static String PENDING = "PENDING"; public static String ERROR = "ERROR"; private static String PATH = "/crystal/client/images/"; private static String SIZE32 = "32X32/"; private static String SIZE16 = "16X16/"; private static String CAPABLE_MUST = "must/"; private static String CAPABLE_MIGHT = "might/"; private static String CAPABLE_CANNOT = "cannot/"; private static String WHEN_NOW = "must/"; private static String WHEN_LATER = "cannot/"; private static Map<String, String> ICON_ADDRESSES = new HashMap<String, String>(); static { ICON_ADDRESSES.put(SAME, "same.png"); ICON_ADDRESSES.put(AHEAD,"ahead.png"); ICON_ADDRESSES.put(BEHIND, "behind.png"); ICON_ADDRESSES.put(MERGECLEAN, "merge.png"); ICON_ADDRESSES.put(MERGECONFLICT, "mergeconflict.png"); ICON_ADDRESSES.put(COMPILECONFLICT, "compileconflict.png"); ICON_ADDRESSES.put(TESTCONFLICT, "testconflict.png"); ICON_ADDRESSES.put(PENDING, "clock.png"); ICON_ADDRESSES.put(ERROR, "error.png"); } // private final ImageIcon _icon; // private final Image _image; private final String _name; // private final DataSource _source; private ImageIcon _icon; private Image _image; private String _committers; private When _when; private Capable _capable; private Ease _ease; private Relationship _consequences; private Action _action; private boolean _ready; public Relationship(String name, ImageIcon icon, Image image) { _name = name.toUpperCase(); if (ICON_ADDRESSES.get(_name) == null) throw new RuntimeException("Trying to create an invalid Relationship"); _ready = false; // _source = source; if (icon != null) _icon = icon; else _icon = new ImageIcon(Constants.class.getResource(PATH + SIZE32 + CAPABLE_MUST + ICON_ADDRESSES.get(PENDING))); if (image != null) _image = image; else _image = new ImageIcon(Constants.class.getResource(PATH + SIZE16 + CAPABLE_MUST + ICON_ADDRESSES.get(PENDING))).getImage(); } public String getName() { return _name; } public void setReady() { _ready = true; _icon = computeIcon(); _image = computeImage(); } public boolean isReady() { return _ready; } /* * Depricated because only images are now compared private int getIconShape() { if (_name.equals(PENDING)) return 1; if (_name.equals(SAME)) return 2; if (_name.equals(ERROR)) return 3; if (_name.equals(AHEAD)) return 4; if (_name.equals(BEHIND)) return 5; if (_name.equals(MERGECLEAN)) return 6; if (_name.equals(TESTCONFLICT)) return 7; if (_name.equals(COMPILECONFLICT)) return 8; if (_name.equals(MERGECONFLICT)) return 9; else return 0; } */ private static int getIconShape(String address) { if (address.indexOf(ICON_ADDRESSES.get(PENDING)) > -1) return 1; else if (address.indexOf(ICON_ADDRESSES.get(SAME)) > -1) return 2; else if (address.indexOf(ICON_ADDRESSES.get(ERROR)) > -1) return 3; else if (address.indexOf(ICON_ADDRESSES.get(AHEAD)) > -1) return 4; else if (address.indexOf(ICON_ADDRESSES.get(BEHIND)) > -1) return 5; else if (address.indexOf(ICON_ADDRESSES.get(MERGECLEAN)) > -1) return 6; else if (address.indexOf(ICON_ADDRESSES.get(TESTCONFLICT)) > -1) return 7; else if (address.indexOf(ICON_ADDRESSES.get(COMPILECONFLICT)) > -1) return 8; else if (address.indexOf(ICON_ADDRESSES.get(MERGECONFLICT)) > -1) return 9; else return 0; } //return 2 if solid // 1 if unsaturated // 0 if hollow private int getIconFill() { if (_capable == Capable.MUST) return 2; else if (_capable == Capable.MIGHT) return 1; else if (_capable == Capable.CANNOT) return 0; else if (_capable == Capable.NOTHING) if (_when == When.NOW) return 2; else if (_when == When.LATER) return 0; else if (_when == When.NOTHING) return 0; else // default icon return 2; else // default icon return 2; } //return 2 if solid // 1 if unsaturated // 0 if hollow private static int getIconFill(String address) { if (address.indexOf(CAPABLE_MUST) > -1) return 2; else if (address.indexOf(CAPABLE_MIGHT) > -1) return 1; else if (address.indexOf(CAPABLE_CANNOT) > -1) return 0; else // default icon System.out.println("oops"); return 2; } private ImageIcon computeIcon() { String iconAddress = PATH + SIZE32; if (getIconFill() == 2) iconAddress += CAPABLE_MUST; else if (getIconFill() == 1) iconAddress += CAPABLE_MIGHT; else if (getIconFill() == 0) iconAddress += CAPABLE_CANNOT; else // default icon iconAddress += CAPABLE_MUST; if (_ready) iconAddress += ICON_ADDRESSES.get(_name); else iconAddress += ICON_ADDRESSES.get(PENDING); return (new ImageIcon(Constants.class.getResource(iconAddress))); } private Image computeImage() { // String imageAddress = PATH + SIZE16 + ICON_ADDRESSES.get(_name); // System.out.println(imageAddress); // return (new ImageIcon(Constants.class.getResource(imageAddress)).getImage()); String iconAddress = PATH + SIZE16; if (getIconFill() == 2) iconAddress += CAPABLE_MUST; else if (getIconFill() == 1) iconAddress += CAPABLE_MIGHT; else if (getIconFill() == 0) iconAddress += CAPABLE_CANNOT; else // default icon iconAddress += CAPABLE_MUST; if (_ready) iconAddress += ICON_ADDRESSES.get(_name); else iconAddress += ICON_ADDRESSES.get(PENDING); // System.out.println(iconAddress); return (new ImageIcon(Constants.class.getResource(iconAddress)).getImage()); } public ImageIcon getIcon() { return _icon; } public Image getImage() { return _image; } public void setCommitters(String committers) { _committers = committers; } public String getCommitters() { return _committers; } public void setWhen(When when) { _when = when; } public When getWhen() { return _when; } public void setCapable(Capable capable) { _capable = capable; } public Capable getCapable() { return _capable; } public void setEase(Ease ease) { _ease = ease; } public Ease getEase() { return _ease; } public void setConsequences(Relationship consequences) { _consequences = consequences; } public Relationship getConsequences() { return _consequences; } public void calculateAction(LocalState localState, Relationship parent) { if ((parent == null) || (localState == LocalState.PENDING)) _action = Action.UNKNOWN; else if (parent.getName().equals(Relationship.SAME)) _action = Action.NOTHING; else if (localState.equals(LocalState.MUST_RESOLVE)) _action = Action.RESOLVE; else if (localState.equals(LocalState.UNCHECKPOINTED)) _action = Action.CHECKPOINT; else if (parent.getName().equals(Relationship.AHEAD)) _action = Action.PUBLISH; else if ((parent.getName().equals(Relationship.BEHIND)) || (parent.getName().equals(Relationship.MERGECLEAN)) || (parent.getName().equals(Relationship.MERGECONFLICT))) _action = Action.SYNC; else _action = null; } public Action getAction() { return _action; } public String getAction(RepoKind rk) { if (rk == RepoKind.HG) { if (_action == Action.RESOLVE) return "hg merge"; else if (_action == Action.CHECKPOINT) return "hg commit"; else if (_action == Action.PUBLISH) return "hg push"; else if (_action == Action.SYNC) return "hg fetch"; else if (_action == Action.NOTHING) return null; else if (_action == Action.UNKNOWN) return "not computed"; else return "cannot compute hg action"; } else return "unsupported repository kind"; } public String getToolTipText() { String answer = ""; if ((_action != null) && (_action != Action.NOTHING)) answer += "Action: " + getAction(RepoKind.HG) + "\n"; if(_consequences != null) answer += "Consequences: new relationship will be " + _consequences.getName() + "\n"; else if ((_committers != null) && (!(_committers.isEmpty()))) answer += "Committers: " + _committers + "\n"; return answer.trim(); } /* * Depricated because only images are now compared @Override public int compareTo(Relationship other) { // handle comparison to null if (other == null) return 1; // handle one or both items not being ready if (_ready && !other._ready) return 1; else if (!_ready && other._ready) return -1; if (!_ready && !other._ready) return 0; // // this is code for all hollow < all unsaturated < all solid // if (getIconFill() > other.getIconFill()) // return 1; // else if (getIconFill() < other.getIconFill()) // return -1; // else // return (getIconShape() - other.getIconShape()); // this is code for using the getIntRepresentation for ordering icons return getIntRepresentation() - other.getIntRepresentation(); } */ /* * Nothing to do: PENDING < SAME < ERROR * Action will succeed: AHEAD < BEHIND < MERGECLEAN * Action will fail: TESTCONFLICT < COMPILECONLFICT < MERGECONFLICT. The latter two categories have solid/unsaturated/hollow versions. I would say that all "action-succeed" icons should be less-prioritized than all "action-fail" icons. In particular, one could order as follows: * nothing-to-do * action-succeed hollow * action-succeed unsaturated * action-succeed solid * action-fail hollow * action-fail unsaturated * action-fail solid * * Depricated because only images are now compared private int getIntRepresentation() { int answer; // 0 -- 3 if (getIconShape() <= 3) answer = getIconShape(); // 4 -- 12 else if (getIconShape() <= 6) answer = getIconShape() + getIconFill() * 3; // 13 -- else // getIconShape() is 7 -- 9 answer = 2 * 3 + getIconShape() + getIconFill() * 3; return answer; } */ private static int getImageIntRepresentation(Relationship r) { if (r == null) return -1; if (r.getIcon() == null) return -1; String address = r.getIcon().toString(); int answer; // 1 -- 3 if (getIconShape(address) <= 3) answer = getIconShape(address); // 4 -- 12 else if (getIconShape(address) <= 6) answer = getIconShape(address) + getIconFill(address) * 3; else // getIconShape() is 7 -- 9 answer = 2 * 3 + getIconShape(address) + getIconFill(address) * 3; return answer; } /* * Compares Images a and b (same way as getIntRepresenation does) and returns the dominant Image. */ private static Relationship compareImages(Relationship a, Relationship b) { if (getImageIntRepresentation(a) > getImageIntRepresentation(b)) return a; else return b; } public static Image getDominant(Collection<Relationship> relationships) { Relationship dominant = null; for (Relationship currentRelationship : relationships) dominant = compareImages(currentRelationship, dominant); return dominant.getImage(); } @Override public String toString() { return _name; } public boolean equals(Object o) { if (o instanceof Relationship) return _name.equals(((Relationship) o)._name); else return false; } public int hashCode() { return _name.hashCode(); } // public DataSource getDataSource() { // return _source; }
package com.rultor.board; import com.amazonaws.services.simpleemail.AmazonSimpleEmailService; import com.amazonaws.services.simpleemail.model.Body; import com.amazonaws.services.simpleemail.model.Content; import com.amazonaws.services.simpleemail.model.Destination; import com.amazonaws.services.simpleemail.model.Message; import com.amazonaws.services.simpleemail.model.SendEmailRequest; import com.amazonaws.services.simpleemail.model.SendEmailResult; import com.jcabi.aspects.Immutable; import com.jcabi.aspects.Loggable; import com.jcabi.immutable.Array; import com.jcabi.log.Logger; import com.rultor.aws.SESClient; import java.io.IOException; import java.util.Collection; import java.util.Map; import javax.validation.constraints.NotNull; import lombok.EqualsAndHashCode; import org.apache.commons.lang.CharUtils; /** * Amazon SES. * * @author Yegor Bugayenko (yegor@tpc2.com) * @version $Id$ * @since 1.0 * @checkstyle ClassDataAbstractionCoupling (500 lines) */ @Immutable @EqualsAndHashCode(of = { "client", "sender", "recipients" }) @Loggable(Loggable.DEBUG) public final class SES implements Billboard { /** * SES client. */ private final transient SESClient client; /** * Sender. */ private final transient String sender; /** * Recipients. */ private final transient Array<String> recipients; /** * Public ctor. * @param src Sender of emails * @param rcpts Recipients * @param key AWS key * @param secret AWS secret * @checkstyle ParameterNumber (4 lines) */ public SES(final String src, final Collection<String> rcpts, final String key, final String secret) { this(src, rcpts, new SESClient.Simple(key, secret)); } /** * Public ctor. * @param src Sender of emails * @param rcpts Recipients * @param clnt SES Client */ public SES(final String src, final Collection<String> rcpts, final SESClient clnt) { this.client = clnt; this.recipients = new Array<String>(rcpts); this.sender = src; } /** * {@inheritDoc} */ @Override public String toString() { return Logger.format( "SES emails from %s to %s accessed with %s", this.sender, this.recipients, this.client ); } /** * {@inheritDoc} */ @Override public void announce(@NotNull(message = "announcement can't be NULL") final Announcement anmt) throws IOException { final AmazonSimpleEmailService aws = this.client.get(); try { String print = String.class.cast(anmt.args().get("emailBody")); if (print == null) { final StringBuilder txt = new StringBuilder(); for (Map.Entry<String, Object> entry : anmt.args().entrySet()) { txt.append(entry.getKey()) .append(':') .append(CharUtils.LF) .append(entry.getValue()) .append(CharUtils.LF) .append(CharUtils.LF); } print = txt.toString(); } final String subject = String.format( "%s: %s", anmt.level(), anmt.args().get("title") ); final Message message = new Message() .withSubject(new Content().withData(subject)) .withBody(new Body().withText(new Content().withData(print))); final SendEmailResult result = aws.sendEmail( new SendEmailRequest() .withSource(this.sender) .withReturnPath(this.sender) .withDestination( new Destination().withToAddresses(this.recipients) ) .withMessage(message) ); Logger.info( this, "#announce(..): sent SES email %s from %s to %s", result.getMessageId(), this.sender, this.recipients ); } finally { aws.shutdown(); } } }
package org.jfree.chart.axis.junit; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Font; import java.awt.GradientPaint; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.chart.axis.Axis; import org.jfree.chart.axis.CategoryAxis; import org.jfree.ui.RectangleInsets; /** * Tests for the {@link Axis} class. */ public class AxisTests extends TestCase { /** * Returns the tests as a test suite. * * @return The test suite. */ public static Test suite() { return new TestSuite(AxisTests.class); } /** * Constructs a new set of tests. * * @param name the name of the tests. */ public AxisTests(String name) { super(name); } /** * Confirm that cloning works. */ public void testCloning() { CategoryAxis a1 = new CategoryAxis("Test"); a1.setAxisLinePaint(Color.red); CategoryAxis a2 = null; try { a2 = (CategoryAxis) a1.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } assertTrue(a1 != a2); assertTrue(a1.getClass() == a2.getClass()); assertTrue(a1.equals(a2)); } /** * Confirm that the equals method can distinguish all the required fields. */ public void testEquals() { Axis a1 = new CategoryAxis("Test"); Axis a2 = new CategoryAxis("Test"); assertTrue(a1.equals(a2)); // visible flag... a1.setVisible(false); assertFalse(a1.equals(a2)); a2.setVisible(false); assertTrue(a1.equals(a2)); // label... a1.setLabel("New Label"); assertFalse(a1.equals(a2)); a2.setLabel("New Label"); assertTrue(a1.equals(a2)); // label font... a1.setLabelFont(new Font("Dialog", Font.PLAIN, 8)); assertFalse(a1.equals(a2)); a2.setLabelFont(new Font("Dialog", Font.PLAIN, 8)); assertTrue(a1.equals(a2)); // label paint... a1.setLabelPaint(new GradientPaint(1.0f, 2.0f, Color.white, 3.0f, 4.0f, Color.black)); assertFalse(a1.equals(a2)); a2.setLabelPaint(new GradientPaint(1.0f, 2.0f, Color.white, 3.0f, 4.0f, Color.black)); assertTrue(a1.equals(a2)); // label insets... a1.setLabelInsets(new RectangleInsets(10.0, 10.0, 10.0, 10.0)); assertFalse(a1.equals(a2)); a2.setLabelInsets(new RectangleInsets(10.0, 10.0, 10.0, 10.0)); assertTrue(a1.equals(a2)); // label angle... a1.setLabelAngle(1.23); assertFalse(a1.equals(a2)); a2.setLabelAngle(1.23); assertTrue(a1.equals(a2)); // axis line visible... a1.setAxisLineVisible(false); assertFalse(a1.equals(a2)); a2.setAxisLineVisible(false); assertTrue(a1.equals(a2)); // axis line stroke... BasicStroke s = new BasicStroke(1.1f); a1.setAxisLineStroke(s); assertFalse(a1.equals(a2)); a2.setAxisLineStroke(s); assertTrue(a1.equals(a2)); // axis line paint... a1.setAxisLinePaint(new GradientPaint(1.0f, 2.0f, Color.red, 3.0f, 4.0f, Color.black)); assertFalse(a1.equals(a2)); a2.setAxisLinePaint(new GradientPaint(1.0f, 2.0f, Color.red, 3.0f, 4.0f, Color.black)); assertTrue(a1.equals(a2)); // tick labels visible flag... a1.setTickLabelsVisible(false); assertFalse(a1.equals(a2)); a2.setTickLabelsVisible(false); assertTrue(a1.equals(a2)); // tick label font... a1.setTickLabelFont(new Font("Dialog", Font.PLAIN, 12)); assertFalse(a1.equals(a2)); a2.setTickLabelFont(new Font("Dialog", Font.PLAIN, 12)); assertTrue(a1.equals(a2)); // tick label paint... a1.setTickLabelPaint(new GradientPaint(1.0f, 2.0f, Color.yellow, 3.0f, 4.0f, Color.black)); assertFalse(a1.equals(a2)); a2.setTickLabelPaint(new GradientPaint(1.0f, 2.0f, Color.yellow, 3.0f, 4.0f, Color.black)); assertTrue(a1.equals(a2)); // tick label insets... a1.setTickLabelInsets(new RectangleInsets(10.0, 10.0, 10.0, 10.0)); assertFalse(a1.equals(a2)); a2.setTickLabelInsets(new RectangleInsets(10.0, 10.0, 10.0, 10.0)); assertTrue(a1.equals(a2)); // tick marks visible flag... a1.setTickMarksVisible(false); assertFalse(a1.equals(a2)); a2.setTickMarksVisible(false); assertTrue(a1.equals(a2)); // tick mark inside length... a1.setTickMarkInsideLength(1.23f); assertFalse(a1.equals(a2)); a2.setTickMarkInsideLength(1.23f); assertTrue(a1.equals(a2)); // tick mark outside length... a1.setTickMarkOutsideLength(1.23f); assertFalse(a1.equals(a2)); a2.setTickMarkOutsideLength(1.23f); assertTrue(a1.equals(a2)); // tick mark stroke... a1.setTickMarkStroke(new BasicStroke(2.0f)); assertFalse(a1.equals(a2)); a2.setTickMarkStroke(new BasicStroke(2.0f)); assertTrue(a1.equals(a2)); // tick mark paint... a1.setTickMarkPaint(new GradientPaint(1.0f, 2.0f, Color.cyan, 3.0f, 4.0f, Color.black)); assertFalse(a1.equals(a2)); a2.setTickMarkPaint(new GradientPaint(1.0f, 2.0f, Color.cyan, 3.0f, 4.0f, Color.black)); assertTrue(a1.equals(a2)); // tick mark outside length... a1.setFixedDimension(3.21f); assertFalse(a1.equals(a2)); a2.setFixedDimension(3.21f); assertTrue(a1.equals(a2)); a1.setMinorTickMarksVisible(true); assertFalse(a1.equals(a2)); a2.setMinorTickMarksVisible(true); assertTrue(a1.equals(a2)); a1.setMinorTickMarkInsideLength(1.23f); assertFalse(a1.equals(a2)); a2.setMinorTickMarkInsideLength(1.23f); assertTrue(a1.equals(a2)); a1.setMinorTickMarkOutsideLength(3.21f); assertFalse(a1.equals(a2)); a2.setMinorTickMarkOutsideLength(3.21f); assertTrue(a1.equals(a2)); } /** * Two objects that are equal are required to return the same hashCode. */ public void testHashCode() { Axis a1 = new CategoryAxis("Test"); Axis a2 = new CategoryAxis("Test"); assertTrue(a1.equals(a2)); int h1 = a1.hashCode(); int h2 = a2.hashCode(); assertEquals(h1, h2); } }
package net.hyperic.sigar.cmd; import net.hyperic.sigar.SigarProxy; import net.hyperic.sigar.SigarException; import net.hyperic.sigar.SigarNotImplementedException; import net.hyperic.sigar.util.PrintfFormat; import java.text.SimpleDateFormat; import java.util.Date; public class Uptime extends SigarCommandBase { private static Object[] loadAvg = new Object[3]; private static PrintfFormat formatter = new PrintfFormat("%.2f, %.2f, %.2f"); public Uptime(Shell shell) { super(shell); } public Uptime() { super(); } public String getUsageShort() { return "Show how long the system has been running"; } public void output(String[] args) throws SigarException { System.out.println(getInfo(this.sigar)); } public static String getInfo(SigarProxy sigar) throws SigarException { double uptime = sigar.getUptime().getUptime(); String loadAverage; try { double[] avg = sigar.getLoadAverage(); loadAvg[0] = new Double(avg[0]); loadAvg[1] = new Double(avg[1]); loadAvg[2] = new Double(avg[2]); loadAverage = "load average: " + formatter.sprintf(loadAvg); } catch (SigarNotImplementedException e) { loadAverage = "(load average unknown)"; } return " " + getCurrentTime() + " up " + formatUptime(uptime) + ", " + loadAverage; } private static String formatUptime(double uptime) { String retval = ""; int days = (int)uptime / (60*60*24); int minutes, hours; if (days != 0) { retval += days + " " + ((days > 1) ? "days" : "day") + ", "; } minutes = (int)uptime / 60; hours = minutes / 60; hours %= 24; minutes %= 60; if (hours != 0) { retval += hours + ":" + minutes; } else { retval += minutes + " min"; } return retval; } private static String getCurrentTime() { return new SimpleDateFormat("h:mm a").format(new Date()); } //pretty close to uptime command, but we don't output number of users yet public static void main(String[] args) throws Exception { new Uptime().processCommand(args); } }
package com.sometrik.framework; import java.util.ArrayList; import com.sometrik.framework.NativeCommand.CommandType; import android.R.color; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ExpandableListAdapter; import android.widget.ExpandableListView; import android.widget.ListView; public class FWList extends ExpandableListView implements NativeCommandHandler{ enum ColumnType { TEXT, NUMERIC, TIMESTAMP }; private FrameWork frame; private FWAdapter adapter; public FWList(final FrameWork frame, final FWAdapter adapter) { super(frame); this.frame = frame; this.adapter = adapter; this.setAdapter((ExpandableListAdapter)adapter); this.setGroupIndicator(null); this.setAnimation(null); System.out.println("FWLIST constructor"); this.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS); // this.setGroupIndicator(frame.getResources().getDrawable(android.R.drawable.ic_menu_more)); setOnGroupClickListener(new OnGroupClickListener(){ @Override public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) { System.out.println("groupClick detected " + groupPosition); if (groupPosition == 0) { System.out.println("column title clicked. ignoring"); } else { System.out.println("row clicked. Sending intChangedEvent of " + (groupPosition - 1)); frame.intChangedEvent(System.currentTimeMillis() / 1000.0, getElementId(), 0, groupPosition - 1); } return true; } }); setOnChildClickListener(new OnChildClickListener(){ @Override public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) { System.out.println("child clicked. Sending intChangedEvent of " + (groupPosition - 1) + " " + (childPosition - 1)); frame.intChangedEvent(System.currentTimeMillis() / 1000.0, getElementId(), childPosition - 1, groupPosition - 1); return true; } }); //This collapses all other than the chosen group setOnGroupExpandListener(new OnGroupExpandListener() { @Override public void onGroupExpand(int groupPosition) { for (int i = 0; i < adapter.getGroupCount(); i++) { if (i != groupPosition) { if (isGroupExpanded(i)) { collapseGroup(i); } } } Log.d("adapterExpansion", "expansionStuff done"); } }); } @Override public void addData(String text, int row, int column, int sheet){ Log.d("FWList", "adding data for row " + row + " column " + column + " sheet " + sheet); ArrayList<String> dataRow = adapter.getDataRow(row, sheet); if (dataRow != null){ Log.d("FWList", "row found adding data"); if (dataRow.size() > column) { Log.d("FWList", "replacing column " + column); dataRow.remove(column); } dataRow.add(column, text); adapter.notifyDataSetChanged(); } else { Log.d("FWList", "creating new row"); dataRow = new ArrayList<String>(); dataRow.add(text); adapter.addItem(row, sheet, dataRow); } } @Override public void onScreenOrientationChange(boolean isLandscape) { // TODO Auto-generated method stub } @Override public void addChild(View view) { // TODO Auto-generated method stub } @Override public void addOption(int optionId, String text) { ColumnType type = ColumnType.values()[optionId - 1]; System.out.println("columnType int: " + ColumnType.values()[optionId - 1]); if (type == ColumnType.TEXT){ adapter.addColumn(text); } adapter.notifyDataSetChanged(); } @Override public void setValue(String v) { adapter.addSheet(v); } @Override public void setValue(int v) { this.expandGroup(v + 1); } @Override public void setViewEnabled(Boolean enabled) { // TODO Auto-generated method stub } @Override public void setStyle(String key, String value) { // TODO Auto-generated method stub } @Override public void setError(boolean hasError, String errorText) { // TODO Auto-generated method stub } @Override public int getElementId() { return getId(); } @Override public void setViewVisibility(boolean visibility) { if (visibility){ this.setVisibility(VISIBLE); } else { this.setVisibility(INVISIBLE); } } @Override public void clear() { adapter.clear(); } }
package database; import java.security.acl.Owner; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.Timestamp; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import server.ConfigurationProperties; import server.InputValidator; import server.PasswordHasher; import dto.CandidateDto; import dto.ElectionDto; import dto.InputValidation; import dto.SecurityValidator; import dto.UserDto; import dto.Validator; import dto.VoteDto; import enumeration.Status; import enumeration.ElectionStatus; public class DatabaseConnector { private static String dbHost; private static String dbPort; private static String dbUser; private static String dbPassword; private static String dbName; private Connection con; public DatabaseConnector() { Connection con = null; //System.out.println(ConfigurationProperties.dbHost()); dbHost = ConfigurationProperties.dbHost(); dbPort = ConfigurationProperties.dbPort(); dbName = ConfigurationProperties.dbSchema(); dbUser = ConfigurationProperties.dbUser(); dbPassword = ConfigurationProperties.dbPassword(); try { Class.forName("com.mysql.jdbc.Driver"); String url = "jdbc:mysql://" + dbHost + ":" + dbPort + "/" + dbName; con = DriverManager.getConnection(url, dbUser, dbPassword); this.con = con; } catch (Exception e) { System.out.println("Db connection failed"); e.printStackTrace(); } } public UserDto selectUserById(int userId) { UserDto u = new UserDto(); PreparedStatement st = null; String query = "SELECT * FROM users WHERE user_id = ?"; try { st = con.prepareStatement(query); st.setInt(1, userId); ResultSet res = st.executeQuery(); if (res.next()) { u.setUser_id(res.getInt(1)); u.setFirst_name(res.getString(2)); u.setLast_name(res.getString(3)); u.setEmail(res.getString(4)); u.setPassword(res.getString(5)); u.setSalt(res.getString(6)); u.setTemp_password(res.getString(7)); u.setTemp_salt(res.getString(8)); u.setActivation_code(res.getString(9)); u.setPublic_key(res.getString(10)); u.setAdministrator_flag(res.getInt(11)); u.setStatus(res.getInt(12)); } } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); } return u; } public Validator checkIfUsernamePasswordMatch(String email, String plainPass) { // 1. validate input Validator result = validateEmailAndPlainInput(email, plainPass); if (!result.isVerified()) { return result; } // 2. validate email result = verifyUserEmail(email); if (!result.isVerified()) { return result; } InputValidator iv = new InputValidator(); PasswordHasher hasher = new PasswordHasher(); // get this user limited info from the database UserDto userDto = selectUserByEmailLimited(email); String dbHash = userDto.getPassword(); String dbSalt = userDto.getSalt(); int statusId = userDto.getStatus(); //int falseLogins = user.getFalseLogins(); int id = userDto.getUser_id(); // 3. check if this user is active // if (statusId != Enumeration.User.USER_STATUSID_ACTIVE) { // result.setVerified(false); // result.setStatus("Error, cannot login, this user account has been locked"); // return result; String plainHash = hasher.sha512(plainPass, dbSalt); // 4. if entered password is correct, return true with welcome message if (plainHash.equals(dbHash)) { //updateDatabaseIntField("USERS", "ID", "FALSELOGINS", id, 0); //unsetActivationCodeAndTempPassword(id); result.setObject(userDto); result.setVerified(true); result.setStatus("Welcome to Certus"); //LoggerCustom.logLoginActivity(email, "Login Successful"); return result; } else { // 5. else record the failed login attempt // int newFalseLogins = falseLogins + 1; // updateDatabaseIntField("USERS", "ID", "FALSELOGINS", id, // newFalseLogins); // // if we reached the max of failed logins, lock the account, sent an // // email // if (newFalseLogins == Enumeration.User.USER_MAX_LOGIN_ATTEMPTS) { // // lock // updateDatabaseIntField("USERS", "ID", "STATUSID", id, // Enumeration.User.USER_STATUSID_LOCKED); // // generate activation code // String activationCode = setActivationCode(id); // // send email with activation code // SendEmail.sendEmailNotification(email, // Enumeration.Strings.ACCOUNT_LOCKED_SUBJECT, // Enumeration.Strings.ACCOUNT_LOCKED_MESSAGE // + activationCode); // LoggerCustom.logLoginActivity(email, "Account locked"); // result.setVerified(false); // result.setStatus("Error, exceeded the maximum number of login attempts, this user account has been locked"); // return result; // } else { // result.setVerified(false); // result.setStatus("Error, the system could not resolve the provided combination of username and password."); // return result; result.setVerified(false); result.setStatus("Error, the system could not resolve the provided combination of username and password."); return result; } } public Validator validateEmailAndPlainInput(String email, String plainPass) { InputValidator iv = new InputValidator(); Validator vResult = new Validator(); Validator vEmail, vPlain; Boolean verified = true; String status = ""; // 1. email vEmail = iv.validateEmail(email, "Email"); verified &= vEmail.isVerified(); status += vEmail.getStatus(); // 2. plain vPlain = iv.validateString(plainPass, "Password"); verified &= vPlain.isVerified(); status += vPlain.getStatus(); vResult.setVerified(verified); vResult.setStatus(status); return vResult; } public Validator verifyUserEmail(String emailToSelect) { Validator v = new Validator(); v.setVerified(false); v.setStatus("Error, the system could not resolve the provided combination of username and password."); PreparedStatement st = null; String query = "SELECT user_id FROM users WHERE email = ?"; try { st = con.prepareStatement(query); st.setString(1, emailToSelect); ResultSet res = st.executeQuery(); if (res.next()) { v.setVerified(true); v.setStatus(""); return v; } } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); } return v; } public UserDto selectUserByEmailLimited(String emailToSelect) { UserDto userDto = new UserDto(); PreparedStatement st = null; String query = "SELECT user_id, first_name, last_name, password, salt, status FROM users WHERE email = ?"; try { st = this.con.prepareStatement(query); st.setString(1, emailToSelect); ResultSet res = st.executeQuery(); if (res.next()) { int user_id = res.getInt(1); String first_name = res.getString(2); String last_name = res.getString(3); String password = res.getString(4); String salt = res.getString(5); int statusId = res.getInt(6); // String salt = res.getString(2); // int falseLogins = res.getInt(4); // int id = res.getInt(5); // int roleId = res.getInt(6); // String acticationCode = res.getString(7); // String activationCodeSalt = res.getString(8); // String tempPassword = res.getString(9); // String tempPasswordSalt = res.getString(10); // int firmId = res.getInt(11); userDto.setUser_id(user_id); userDto.setFirst_name(first_name); userDto.setLast_name(last_name); userDto.setPassword(password); userDto.setSalt(salt); userDto.setStatus(statusId); } else { } } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); } return userDto; } // Election /** * @param id(int) - Election identification number (primary key) * @return Validator : ElectionDto - Details of a particular election * @author Hirosh Wickramasuriya */ public Validator selectElection(int id) { Validator validator = new Validator(); ElectionDto electionDto = new ElectionDto(); PreparedStatement st = null; String query = "SELECT election_id, election_name, start_datetime, close_datetime, status, s.code, s.description, owner_id " + " FROM election e " + " INNER JOIN status_election s " + " ON (e.status = s.status_id) " + " WHERE election_id = ?"; try { st = this.con.prepareStatement(query); st.setInt(1, id); ResultSet res = st.executeQuery(); if (res.next()) { int electionId = res.getInt(1); String electionName = res.getString(2); Timestamp startDatetime = res.getTimestamp(3); Timestamp closeDatetime = res.getTimestamp(4); int statusId = res.getInt(5); String statusCode = res.getString(6); String statusDescription = res.getString(7); int ownerId = res.getInt(8); electionDto.setElectionId(electionId); electionDto.setElectionName(electionName); electionDto.setStartDatetime(startDatetime); electionDto.setCloseDatetime(closeDatetime); electionDto.setStatus(statusId); electionDto.setStatusCode(statusCode); electionDto.setStatusDescription(statusDescription); electionDto.setOwnerId(ownerId); } else { } } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); } validator.setObject(electionDto); return validator; } /** * @param status(ElectionStatus) - specific status to be searched * @return Validator : ArrayList<ElectionDto> - List of elections that matches a specific status * @author Hirosh Wickramasuriya */ public Validator selectElections(ElectionStatus electionStatus) { Validator validator = new Validator(); ArrayList<ElectionDto> elections = new ArrayList<ElectionDto>(); PreparedStatement st = null; String query = "SELECT election_id, election_name, start_datetime, close_datetime, status, s.code, s.description, owner_id" + " FROM election e" + " INNER JOIN status_election s " + " ON (e.status = s.status_id) " + " WHERE status = ?"; try { st = this.con.prepareStatement(query); st.setInt(1, electionStatus.getCode()); ResultSet res = st.executeQuery(); while (res.next()) { int electionId = res.getInt(1); String electionName = res.getString(2); Timestamp startDatetime = res.getTimestamp(3); Timestamp closeDatetime = res.getTimestamp(4); int statusId = res.getInt(5); String statusCode = res.getString(6); String statusDescription = res.getString(7); int ownerId = res.getInt(8); ElectionDto electionDto = new ElectionDto(); electionDto.setElectionId(electionId); electionDto.setElectionName(electionName); electionDto.setStartDatetime(startDatetime); electionDto.setCloseDatetime(closeDatetime); electionDto.setStatus(statusId); electionDto.setStatusCode(statusCode); electionDto.setStatusDescription(statusDescription); electionDto.setOwnerId(ownerId); elections.add(electionDto); } } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); } validator.setObject(elections); return validator; } /** * @param electionOwnerId(int) - user_id of the user who owns this election * @param status(ElectionStatus) - specific status to be searched * @return Validator : ArrayList<ElectionDto> - List of elections owned by the specific user, that matches a specific status * @author Hirosh Wickramasuriya */ public Validator selectElectionsOwnedByUser(int electionOwnerId, ElectionStatus electionStatus) { Validator validator = new Validator(); ArrayList<ElectionDto> elections = new ArrayList<ElectionDto>(); PreparedStatement st = null; String query = "SELECT election_id, election_name, start_datetime, close_datetime, status, s.code, s.description, owner_id" + " FROM election e" + " INNER JOIN status_election s " + " ON (e.status = s.status_id) " + " WHERE owner_id = ?" + " AND status = ?"; try { st = this.con.prepareStatement(query); st.setInt(1, electionOwnerId); st.setInt(2, electionStatus.getCode()); ResultSet res = st.executeQuery(); while (res.next()) { int electionId = res.getInt(1); String electionName = res.getString(2); Timestamp startDatetime = res.getTimestamp(3); Timestamp closeDatetime = res.getTimestamp(4); int statusId = res.getInt(5); String statusCode = res.getString(6); String statusDescription = res.getString(7); int ownerId = res.getInt(8); ElectionDto electionDto = new ElectionDto(); electionDto.setElectionId(electionId); electionDto.setElectionName(electionName); electionDto.setStartDatetime(startDatetime); electionDto.setCloseDatetime(closeDatetime); electionDto.setStatus(statusId); electionDto.setStatusCode(statusCode); electionDto.setStatusDescription(statusDescription); electionDto.setOwnerId(ownerId); elections.add(electionDto); } } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); } validator.setObject(elections); return validator; } /** * @return Validator : ArrayList<ElectionDto> - List of all the elections (regardless of status) * @author Hirosh Wickramasuriya */ public Validator selectElections() { Validator validator = new Validator(); ArrayList<ElectionDto> elections = new ArrayList<ElectionDto>(); PreparedStatement st = null; String query = "SELECT election_id, election_name, start_datetime, close_datetime, status, s.code, s.description, owner_id" + " FROM election e" + " INNER JOIN status_election s " + " ON (e.status = s.status_id) " ; try { st = this.con.prepareStatement(query); ResultSet res = st.executeQuery(); while (res.next()) { int electionId = res.getInt(1); String electionName = res.getString(2); Timestamp startDatetime = res.getTimestamp(3); Timestamp closeDatetime = res.getTimestamp(4); int statusId = res.getInt(5); String statusCode = res.getString(6); String statusDescription = res.getString(7); int ownerId = res.getInt(8); ElectionDto electionDto = new ElectionDto(); electionDto.setElectionId(electionId); electionDto.setElectionName(electionName); electionDto.setStartDatetime(startDatetime); electionDto.setCloseDatetime(closeDatetime); electionDto.setStatus(statusId); electionDto.setStatusCode(statusCode); electionDto.setStatusDescription(statusDescription); electionDto.setOwnerId(ownerId); elections.add(electionDto); } } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); } validator.setObject(elections); return validator; } /** * @param election_owner_id(int) - user_id of the user who owns elections * @return Validator : ArrayList<ElectionDto> - List of all the elections owned by the specific user (regardless of status) * @author Hirosh Wickramasuriya */ public Validator selectElectionsOwnedByUser(int electionOwnerId) { Validator validator = new Validator(); ArrayList<ElectionDto> elections = new ArrayList<ElectionDto>(); PreparedStatement st = null; String query = "SELECT election_id, election_name, start_datetime, close_datetime, status, s.code, s.description, owner_id" + " FROM election e" + " INNER JOIN status_election s " + " ON (e.status = s.status_id) " + " WHERE owner_id = ?" ; try { st = this.con.prepareStatement(query); st.setInt(1, electionOwnerId); ResultSet res = st.executeQuery(); while (res.next()) { int electionId = res.getInt(1); String electionName = res.getString(2); Timestamp startDatetime = res.getTimestamp(3); Timestamp closeDatetime = res.getTimestamp(4); int statusId = res.getInt(5); String statusCode = res.getString(6); String statusDescription = res.getString(7); int ownerId = res.getInt(8); ElectionDto electionDto = new ElectionDto(); electionDto.setElectionId(electionId); electionDto.setElectionName(electionName); electionDto.setStartDatetime(startDatetime); electionDto.setCloseDatetime(closeDatetime); electionDto.setStatus(statusId); electionDto.setStatusCode(statusCode); electionDto.setStatusDescription(statusDescription); electionDto.setOwnerId(ownerId); elections.add(electionDto); } } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); } validator.setObject(elections); return validator; } // Candidates /** * @param id - candidate identification number (primary key) * @return Validator :CandidateDto - Details of a particular candidate * @author Hirosh Wickramasuriya */ public Validator selectCandidate(int id) { Validator validator = new Validator(); CandidateDto candidateDto = new CandidateDto(); PreparedStatement st = null; String query = "SELECT candidate_id, candidate_name, election_id, display_order, status FROM candidate WHERE candidate_id = ?"; try { st = this.con.prepareStatement(query); st.setInt(1, id); ResultSet res = st.executeQuery(); if (res.next()) { int candidateId = res.getInt(1); String candidate_name = res.getString(2); int electionId = res.getInt(3); int displayOrder = res.getInt(4); int statusId = res.getInt(5); candidateDto.setCandidateId(candidateId); candidateDto.setCandidateName(candidate_name); candidateDto.setElectionId(electionId); candidateDto.setDisplayOrder(displayOrder); candidateDto.setStatus(statusId); } else { } } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); } validator.setObject(candidateDto); return validator; } /** * @param electionIdKey - election identification number * @return Validator : ArrayList<CandidateDto>- list of all the candidates under specified election * @author Hirosh Wickramasuriya */ public Validator selectCandidatesOfElection(int electionIdKey) { Validator validator = new Validator(); ArrayList<CandidateDto> candidates = new ArrayList<CandidateDto>(); PreparedStatement st = null; String query = "SELECT candidate_id, candidate_name, election_id, display_order, status FROM candidate WHERE election_id = ?"; try { st = this.con.prepareStatement(query); st.setInt(1, electionIdKey); ResultSet res = st.executeQuery(); while (res.next()) { int candidateId = res.getInt(1); String candidateName = res.getString(2); int electionId = res.getInt(3); int displayOrder = res.getInt(4); int statusId = res.getInt(5); CandidateDto candidateDto = new CandidateDto(); candidateDto.setCandidateId(candidateId); candidateDto.setCandidateName(candidateName); candidateDto.setElectionId(electionId); candidateDto.setDisplayOrder(displayOrder); candidateDto.setStatus(statusId); candidates.add(candidateDto); } } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); } validator.setObject(candidates); return validator; } /** * @param electionIdKey - election identification number * @param candidateStatus - desired status of candidate which required to be returned for given election * @return Validator :ArrayList<CandidateDto> - list of all the candidates that matches the status under specified election * @author Hirosh Wickramasuriya */ public Validator selectCandidatesOfElection(int electionIdKey, Status candidateStatus) { Validator validator = new Validator(); ArrayList<CandidateDto> candidates = new ArrayList<CandidateDto>(); PreparedStatement st = null; String query = "SELECT candidate_id, candidate_name, election_id, display_order, status " + " FROM candidate " + " WHERE election_id = ?" + " AND status = ?"; try { st = this.con.prepareStatement(query); st.setInt(1, electionIdKey); st.setInt(2, candidateStatus.getCode()); ResultSet res = st.executeQuery(); while (res.next()) { int candidateId = res.getInt(1); String candidateName = res.getString(2); int electionId = res.getInt(3); int displayOrder = res.getInt(4); int statusId = res.getInt(5); CandidateDto candidateDto = new CandidateDto(); candidateDto.setCandidateId(candidateId); candidateDto.setCandidateName(candidateName); candidateDto.setElectionId(electionId); candidateDto.setDisplayOrder(displayOrder); candidateDto.setStatus(statusId); candidates.add(candidateDto); } } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); } validator.setObject(candidates); return validator; } /** * @param name - election name * Add new election to db * @author Steven Frink */ public Validator createNewElection(ElectionDto electionDto){ PreparedStatement st=null; InputValidation iv=new InputValidation(); Validator val=new Validator(); try{ val=iv.validateString(electionDto.getElectionName(), "Election name"); if(val.isVerified()){ String query = "INSERT INTO election (election_name, status, owner_id) VALUES (?,?,?)"; int status=0; st=this.con.prepareStatement(query, Statement.RETURN_GENERATED_KEYS); st.setString(1, electionDto.getElectionName()); st.setInt(2, status); st.setInt(3, electionDto.getOwnerId()); int id=st.executeUpdate(); val.setStatus("Election added to DB"); electionDto.setElectionId(id); val.setObject(electionDto); return val; } else{ val.setStatus("Name failed to validate"); return val; } } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); val.setStatus("SQL error"); return val; } } /** * @param candidateList - candidate array list * @param election_id - the election to add candidates to * Add candidates to an election * @author Steven Frink */ public Validator addCandidatesToElection(ArrayList<CandidateDto> candidateList, int election_id){ PreparedStatement st=null; InputValidation iv=new InputValidation(); Validator val = new Validator(); boolean aOK=true; try{ for(int i=0;i<candidateList.size();i++){ val = iv.validateString(candidateList.get(i).getCandidateName(), "Candidate Name"); aOK&=val.isVerified(); } if(aOK){ for(int i=0;i<candidateList.size();i++){ String query="INSERT INTO candidates (candidate_name, election_id, status) VALUES (?,?,?)"; st=this.con.prepareStatement(query,Statement.RETURN_GENERATED_KEYS); st.setString(1,candidateList.get(i).getCandidateName()); st.setInt(2, election_id); st.setInt(3,1); int id=st.executeUpdate(); candidateList.get(i).setCandidateId(id); } val.setStatus("Candidates added to DB"); val.setObject(candidateList); } else{ val.setStatus("Candidate names failed to validate"); } val.setVerified(aOK); return val; } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); val.setVerified(false); val.setStatus("SQL Error"); return val; } } /** * @param candidateDto - candidate object * @author Steven Frink */ public Validator editCandidate(CandidateDto candidateDto){ PreparedStatement st=null; InputValidation iv=new InputValidation(); Validator val = new Validator(); try{ val = iv.validateString(candidateDto.getCandidateName(), "Candidate Name"); boolean valid=true; valid&=val.isVerified(); val=iv.validateInt(candidateDto.getDisplayOrder(), "Display Order"); valid&=val.isVerified(); if(valid){ String query="UPDATE candidate SET (candidate_name, display_order)=(?,?) WHERE candidate_id=?"; st=this.con.prepareStatement(query); st.setString(1, candidateDto.getCandidateName()); st.setInt(2, candidateDto.getDisplayOrder()); st.setInt(3,candidateDto.getCandidateId()); st.execute(); val.setStatus("Candidate information updated"); return val; } else{ val.setStatus("Candidate information did not validate"); val.setVerified(false); return val; } } catch(SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); val.setStatus("SQL Error"); val.setVerified(false); return val; } } public Validator editCandidateStatus(CandidateDto cand){ PreparedStatement st=null; InputValidation iv=new InputValidation(); Validator val = new Validator(); try{ val = iv.validateInt(cand.getStatus(), "Candidate Status"); if(val.isVerified()){ String query="UPDATE candidate SET status=? WHERE candidate_id=?"; st=this.con.prepareStatement(query); st.setInt(1, cand.getCandidateId()); st.execute(); val.setStatus("Candidate status updated"); return val; } else{ val.setStatus("Status failed to verify"); return val; } } catch(SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); val.setStatus("SQL Error"); val.setVerified(false); return val; } } /** * @param electionId - the election to open * Add candidates to an election * @author Steven Frink */ public Validator openElection(int electionId){ PreparedStatement st=null; Validator val=new Validator(); try{ String query="UPDATE election" + " SET status="+ElectionStatus.NEW.getCode() + " WHERE election_id="+electionId; st=this.con.prepareStatement(query); st.execute(); val.setVerified(true); val.setStatus("Election opened"); return val; } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); val.setStatus("SQL Error"); val.setVerified(false); return val; } } /** * @param electionId - the election to close * Close an election * @author Steven Frink */ public Validator closeElection(int electionId){ PreparedStatement st=null; Validator val=new Validator(); try{ String query="UPDATE election" + " SET status="+ ElectionStatus.CLOSED.getCode() + " WHERE election_id="+electionId; st=this.con.prepareStatement(query); st.execute(); val.setVerified(true); val.setStatus("Election closed"); return val; } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); val.setVerified(false); val.setStatus("SQL Error"); return val; } } /** * @param electionId - the election to delete * Delete an election * @author Steven Frink */ public Validator deleteElection(int electionId){ PreparedStatement st=null; Validator val=new Validator(); try{ String query="UPDATE election SET status=7 WHERE election_id="+electionId; st=this.con.prepareStatement(query); st.execute(); val.setStatus("Election deleted"); val.setVerified(true); return val; } catch(SQLException ex){ Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); val.setStatus("SQL Error"); val.setVerified(false); return val; } } /** * @param electionId - the election id to update the status * Delete an election * @author Steven Frink */ public Validator editElectionStatus(int electionId, ElectionStatus electionStatus){ PreparedStatement st=null; Validator val=new Validator(); try{ String query="UPDATE election" + " SET status="+electionStatus.getCode() + " WHERE election_id="+electionId; st=this.con.prepareStatement(query); st.execute(); val.setStatus("Election status updated"); val.setVerified(true); return val; } catch(SQLException ex){ Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); val.setStatus("SQL Error"); val.setVerified(false); return val; } } /** * @param electionDto - the election to edit * Edit an election * @author Steven Frink */ public Validator editElection(ElectionDto electionDto){ PreparedStatement st=null; InputValidation iv=new InputValidation(); Validator val = new Validator(); try{ val = iv.validateString(electionDto.getElectionName(), "Election Name"); if(val.isVerified()){ String query="UPDATE election SET election_name=? WHERE election_id=?"; st=this.con.prepareStatement(query); st.setString(1, electionDto.getElectionName()); st.setInt(2,electionDto.getElectionId()); st.execute(); val.setStatus("Election updated successfully"); return val; } else{ val.setStatus("New election name did not validate"); return val; } } catch(SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); val.setStatus("SQL Error"); val.setVerified(false); return val; } } //Vote /** * @param voteDto - the vote to submit * Submit a vote * @author Steven Frink */ public Validator vote(VoteDto voteDto){ PreparedStatement st=null; InputValidation iv=new InputValidation(); Validator val=new Validator(); boolean valid=true; val=iv.validateInt(voteDto.getUser_id(), "User ID"); valid&=val.isVerified(); val=iv.validateInt(voteDto.getElection_id(), "Election ID"); valid&=val.isVerified(); val=iv.validateString(voteDto.getVote_encrypted(), "Encrypted Vote"); SecurityValidator sec=new SecurityValidator(); try{ if(valid && sec.checkSignature(voteDto.getVote_signature(), voteDto.getUser_id()).isVerified()){ String query="INSERT INTO vote (user_id, election_id, vote_encrypted, vote_signature)" + " VALUES (?,?,?,?)"; st=this.con.prepareStatement(query); st.setInt(1, voteDto.getUser_id()); st.setInt(2, voteDto.getElection_id()); st.setString(3, voteDto.getVote_encrypted()); st.setString(4, voteDto.getVote_signature()); st.execute(); val.setStatus("Vote successfully cast"); val.setVerified(true); return val; } else{ val.setStatus("Information did not validate"); val.setVerified(false); return val; } } catch(SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); val.setStatus("SQL Error"); val.setVerified(false); return val; } } public Validator getPubKeyByUserID(int userId){ PreparedStatement st = null; Validator val=new Validator(); InputValidation iv=new InputValidation(); val=iv.validateInt(userId, "User ID"); String query = "SELECT public_key FROM users WHERE user_id = ?"; try{ if(val.isVerified()){ st = this.con.prepareStatement(query); st.setInt(1, userId); ResultSet res=st.executeQuery(); if (res.next()) { String pubKey = res.getString(1); val.setObject(pubKey); val.setStatus("Public key retrieved"); return val; } else{ val.setVerified(false); val.setStatus("No public key for this user id"); return val; } } else{ val.setStatus("User ID did not validate"); return val; } } catch(SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); val.setVerified(false); val.setStatus("SQL Error"); return val; } } public Validator selectVotesByElectionId(int election_id){ Validator val=new Validator(); InputValidation iv=new InputValidation(); ArrayList<VoteDto> votes=new ArrayList<VoteDto>(); val=iv.validateInt(election_id, "Election ID"); PreparedStatement st=null; try{ if(val.isVerified()){ String query="SELECT user_id, vote_encrypted, vote_signature, timestamp " + " FROM vote " + " WHERE election_id = ?"; st = this.con.prepareStatement(query); st.setInt(1, election_id); ResultSet res=st.executeQuery(); while (res.next()) { int user_id = res.getInt(1); String vote_encrypted = res.getString(2); String vote_signature = res.getString(3); Timestamp t = res.getTimestamp(4); VoteDto vote = new VoteDto(); vote.setUser_id(user_id); vote.setVote_encrypted(vote_encrypted); vote.setVote_signature(vote_signature); vote.setElection_id(election_id); vote.setTimestamp(t); votes.add(vote); } val.setStatus("Successfully retrieved votes"); val.setObject(votes); return val; } else{ val.setStatus("Election ID failed to validate"); return val; } } catch(SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); val.setVerified(false); val.setStatus("SQL Error"); return val; } } public Validator tally(int election_id){ Map<CandidateDto, Integer> t= new HashMap<CandidateDto, Integer>(); PreparedStatement st=null; Validator val=new Validator(); InputValidation iv = new InputValidation(); SecurityValidator sec=new SecurityValidator(); val=iv.validateInt(election_id, "Election ID"); if(val.isVerified()){ Validator voteVal=selectVotesByElectionId(election_id); if(voteVal.isVerified()){ ArrayList<VoteDto> votes = (ArrayList<VoteDto>)voteVal.getObject(); for(int i =0;i<votes.size();i++){ String enc=votes.get(i).getVote_encrypted(); String sig=votes.get(i).getVote_signature(); if(sec.checkSignature(sig, votes.get(i).getUser_id()).isVerified()){ int cand_id=Integer.parseInt(sec.decrypt(enc, getTallierSecretKey()), 16); CandidateDto cand=(CandidateDto)selectCandidate(cand_id).getObject(); if(t.containsKey(cand)){ int total=t.get(cand); total+=1; t.remove(cand); t.put(cand, total); } else{ t.put(cand, 1); } } } val.setStatus("Tally computed"); val.setObject(t); return val; } else{ val.setStatus(voteVal.getStatus()); val.setVerified(voteVal.isVerified()); return val; } } else{ val.setStatus("Election ID failed to verify"); return val; } } }
package database; import java.security.acl.Owner; import java.sql.Blob; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.Timestamp; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import server.ConfigurationProperties; import server.InputValidator; import server.PasswordHasher; import server.SecurityValidator; import dto.CandidateDto; import dto.ElectionDto; import dto.ElectionProgressDto; import dto.InputValidation; import dto.UserDto; import dto.Validator; import dto.VoteDto; import enumeration.Status; import enumeration.ElectionStatus; import enumeration.UserStatus; /** * @author sulo * */ public class DatabaseConnector { private static String dbHost; private static String dbPort; private static String dbUser; private static String dbPassword; private static String dbName; private Connection con; private static String newLine = System.getProperty("line.separator"); public DatabaseConnector() { Connection con = null; // System.out.println(ConfigurationProperties.dbHost()); dbHost = ConfigurationProperties.dbHost(); dbPort = ConfigurationProperties.dbPort(); dbName = ConfigurationProperties.dbSchema(); dbUser = ConfigurationProperties.dbUser(); dbPassword = ConfigurationProperties.dbPassword(); try { Class.forName("com.mysql.jdbc.Driver"); String url = "jdbc:mysql://" + dbHost + ":" + dbPort + "/" + dbName; con = DriverManager.getConnection(url, dbUser, dbPassword); this.con = con; } catch (Exception e) { System.out.println("Db connection failed"); e.printStackTrace(); } } public UserDto selectUserById(int userId) { UserDto u = new UserDto(); PreparedStatement st = null; String query = "SELECT * FROM users WHERE user_id = ?"; try { st = con.prepareStatement(query); st.setInt(1, userId); ResultSet res = st.executeQuery(); if (res.next()) { u.setUserId(res.getInt(1)); u.setFirstName(res.getString(2)); u.setLastName(res.getString(3)); u.setEmail(res.getString(4)); u.setPassword(res.getString(5)); u.setSalt(res.getString(6)); u.setTempPassword(res.getString(7)); u.setTempSalt(res.getString(8)); u.setActivationCode(res.getString(9)); u.setPublicKey(res.getString(10)); u.setAdministratorFlag(res.getInt(11)); u.setStatus(res.getInt(12)); } } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); } return u; } public Validator checkIfUsernamePasswordMatch(String email, String plainPass) { // 1. validate input Validator result = validateEmailAndPlainInput(email, plainPass); if (!result.isVerified()) { return result; } // 2. validate email result = verifyUserEmail(email); if (!result.isVerified()) { return result; } //InputValidator iv = new InputValidator(); //PasswordHasher hasher = new PasswordHasher(); // get this user limited info from the database UserDto userDto = selectUserByEmailLimited(email); String dbHash = userDto.getPassword(); String dbSalt = userDto.getSalt(); int statusId = userDto.getStatus(); // int falseLogins = user.getFalseLogins(); int id = userDto.getUserId(); // 3. check if this user is active // if (statusId != Enumeration.User.USER_STATUSID_ACTIVE) { // result.setVerified(false); // result.setStatus("Error, cannot login, this user account has been locked"); // return result; String plainHash = PasswordHasher.sha512(plainPass, dbSalt); // 4. if entered password is correct, return true with welcome message if (plainHash.equals(dbHash)) { // updateDatabaseIntField("USERS", "ID", "FALSELOGINS", id, 0); // unsetActivationCodeAndTempPassword(id); result.setObject(userDto); result.setVerified(true); result.setStatus("Welcome to Certus"); // LoggerCustom.logLoginActivity(email, "Login Successful"); return result; } else { // 5. else record the failed login attempt // int newFalseLogins = falseLogins + 1; // updateDatabaseIntField("USERS", "ID", "FALSELOGINS", id, // newFalseLogins); // // if we reached the max of failed logins, lock the account, sent // // email // if (newFalseLogins == Enumeration.User.USER_MAX_LOGIN_ATTEMPTS) { // // lock // updateDatabaseIntField("USERS", "ID", "STATUSID", id, // Enumeration.User.USER_STATUSID_LOCKED); // // generate activation code // String activationCode = setActivationCode(id); // // send email with activation code // SendEmail.sendEmailNotification(email, // Enumeration.Strings.ACCOUNT_LOCKED_SUBJECT, // Enumeration.Strings.ACCOUNT_LOCKED_MESSAGE // + activationCode); // LoggerCustom.logLoginActivity(email, "Account locked"); // result.setVerified(false); // result.setStatus("Error, exceeded the maximum number of login attempts, this user account has been locked"); // return result; // } else { // result.setVerified(false); // result.setStatus("Error, the system could not resolve the provided combination of username and password."); // return result; result.setVerified(false); result.setStatus("Error, the system could not resolve the provided combination of username and password."); return result; } } public Validator validateEmailAndPlainInput(String email, String plainPass) { InputValidator iv = new InputValidator(); Validator vResult = new Validator(); Validator vEmail, vPlain; Boolean verified = true; String status = ""; // 1. email vEmail = iv.validateEmail(email, "Email"); verified &= vEmail.isVerified(); status += vEmail.getStatus(); // 2. plain vPlain = iv.validateString(plainPass, "Password"); verified &= vPlain.isVerified(); status += vPlain.getStatus(); vResult.setVerified(verified); vResult.setStatus(status); return vResult; } public Validator verifyUserEmail(String emailToSelect) { Validator v = new Validator(); v.setVerified(false); v.setStatus("Error, the system could not resolve the provided combination of username and password."); PreparedStatement st = null; String query = "SELECT user_id FROM users WHERE email = ?"; try { st = con.prepareStatement(query); st.setString(1, emailToSelect); ResultSet res = st.executeQuery(); if (res.next()) { v.setVerified(true); v.setStatus(""); return v; } } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); } return v; } public UserDto selectUserByEmailLimited(String emailToSelect) { UserDto userDto = new UserDto(); PreparedStatement st = null; String query = "SELECT user_id, first_name, last_name, password, salt, status FROM users WHERE email = ?"; try { st = this.con.prepareStatement(query); st.setString(1, emailToSelect); ResultSet res = st.executeQuery(); if (res.next()) { int user_id = res.getInt(1); String first_name = res.getString(2); String last_name = res.getString(3); String password = res.getString(4); String salt = res.getString(5); int statusId = res.getInt(6); // String salt = res.getString(2); // int falseLogins = res.getInt(4); // int id = res.getInt(5); // int roleId = res.getInt(6); // String acticationCode = res.getString(7); // String activationCodeSalt = res.getString(8); // String tempPassword = res.getString(9); // String tempPasswordSalt = res.getString(10); // int firmId = res.getInt(11); userDto.setUserId(user_id); userDto.setFirstName(first_name); userDto.setLastName(last_name); userDto.setPassword(password); userDto.setSalt(salt); userDto.setStatus(statusId); } else { } } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); } return userDto; } // Election /** * @param id * (int) - Election identification number (primary key) * @return Validator : ElectionDto - Details of a particular election * @author Hirosh Wickramasuriya */ public Validator selectElection(int id) { Validator validator = new Validator(); ElectionDto electionDto = new ElectionDto(); PreparedStatement st = null; String query = "SELECT election_id, election_name, e.description, start_datetime, close_datetime, " + " status, s.code, s.description, owner_id, candidates_string" + " FROM election e " + " INNER JOIN status_election s " + " ON (e.status = s.status_id) " + " WHERE election_id = ?"; try { st = this.con.prepareStatement(query); st.setInt(1, id); ResultSet res = st.executeQuery(); if (res.next()) { int electionId = res.getInt(1); String electionName = res.getString(2); String electionDescription = res.getString(3); Timestamp startDatetime = res.getTimestamp(4); Timestamp closeDatetime = res.getTimestamp(5); int statusId = res.getInt(6); String statusCode = res.getString(7); String statusDescription = res.getString(8); int ownerId = res.getInt(9); String candidatesListString = res.getString(10); electionDto.setElectionId(electionId); electionDto.setElectionName(electionName); electionDto.setElectionDescription(electionDescription); electionDto.setStartDatetime(startDatetime); electionDto.setCloseDatetime(closeDatetime); electionDto.setStatus(statusId); electionDto.setStatusCode(statusCode); electionDto.setStatusDescription(statusDescription); electionDto.setOwnerId(ownerId); electionDto.setCandidatesListString(candidatesListString); Validator vCandidates = selectCandidatesOfElection(electionId); electionDto.setCandidateList( (ArrayList<CandidateDto>) vCandidates.getObject()); validator.setVerified(true); validator.setObject(electionDto); validator.setStatus("Select successful"); } else { validator.setStatus("Election not found"); } } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); validator.setVerified(false); validator.setStatus("Select failed"); } return validator; } /** * @param status * (ElectionStatus) - specific status to be searched * @return Validator : ArrayList<ElectionDto> - List of elections that * matches a specific status * @author Hirosh Wickramasuriya */ public Validator selectElections(ElectionStatus electionStatus) { Validator validator = new Validator(); ArrayList<ElectionDto> elections = new ArrayList<ElectionDto>(); PreparedStatement st = null; String query = "SELECT election_id, election_name, e.description, start_datetime, close_datetime," + " status, s.code, s.description, owner_id, candidates_string " + " FROM election e" + " INNER JOIN status_election s " + " ON (e.status = s.status_id) " + " WHERE status = ?" + " ORDER BY election_id"; try { st = this.con.prepareStatement(query); st.setInt(1, electionStatus.getCode()); ResultSet res = st.executeQuery(); while (res.next()) { int electionId = res.getInt(1); String electionName = res.getString(2); String electionDescription = res.getString(3); Timestamp startDatetime = res.getTimestamp(4); Timestamp closeDatetime = res.getTimestamp(5); int statusId = res.getInt(6); String statusCode = res.getString(7); String statusDescription = res.getString(8); int ownerId = res.getInt(9); String candidatesListString = res.getString(10); ElectionDto electionDto = new ElectionDto(); electionDto.setElectionId(electionId); electionDto.setElectionName(electionName); electionDto.setElectionDescription(electionDescription); electionDto.setStartDatetime(startDatetime); electionDto.setCloseDatetime(closeDatetime); electionDto.setStatus(statusId); electionDto.setStatusCode(statusCode); electionDto.setStatusDescription(statusDescription); electionDto.setOwnerId(ownerId); electionDto.setCandidatesListString(candidatesListString); elections.add(electionDto); } validator.setVerified(true); validator.setObject(elections); validator.setStatus("Successfully selected"); } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); validator.setStatus("Select Failed."); } return validator; } /** * @param status * (ElectionStatus) - specific status to be searched * @return Validator : ArrayList<ElectionDto> - List of elections that * does not match to the status * @author Hirosh Wickramasuriya */ public Validator selectElectionsNotInStatus(ElectionStatus electionStatus) { Validator validator = new Validator(); ArrayList<ElectionDto> elections = new ArrayList<ElectionDto>(); PreparedStatement st = null; String query = "SELECT election_id, election_name, e.description, start_datetime, close_datetime," + " status, s.code, s.description, owner_id, candidates_string " + " FROM election e" + " INNER JOIN status_election s " + " ON (e.status = s.status_id) " + " WHERE status <> ?" + " ORDER BY election_id"; try { st = this.con.prepareStatement(query); st.setInt(1, electionStatus.getCode()); ResultSet res = st.executeQuery(); while (res.next()) { int electionId = res.getInt(1); String electionName = res.getString(2); String electionDescription = res.getString(3); Timestamp startDatetime = res.getTimestamp(4); Timestamp closeDatetime = res.getTimestamp(5); int statusId = res.getInt(6); String statusCode = res.getString(7); String statusDescription = res.getString(8); int ownerId = res.getInt(9); String candidatesListString = res.getString(10); ElectionDto electionDto = new ElectionDto(); electionDto.setElectionId(electionId); electionDto.setElectionName(electionName); electionDto.setElectionDescription(electionDescription); electionDto.setStartDatetime(startDatetime); electionDto.setCloseDatetime(closeDatetime); electionDto.setStatus(statusId); electionDto.setStatusCode(statusCode); electionDto.setStatusDescription(statusDescription); electionDto.setOwnerId(ownerId); electionDto.setCandidatesListString(candidatesListString); elections.add(electionDto); } validator.setVerified(true); validator.setObject(elections); validator.setStatus("Successfully selected"); } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); validator.setStatus("Select Failed."); } return validator; } /** * @param electionOwnerId * (int) - user_id of the user who owns this election * @param status * (ElectionStatus) - specific status to be searched * @return Validator : ArrayList<ElectionDto> - List of elections owned by * the specific user, that matches a specific status * @author Hirosh Wickramasuriya */ public Validator selectElectionsOwnedByUser(int electionOwnerId, ElectionStatus electionStatus) { Validator validator = new Validator(); ArrayList<ElectionDto> elections = new ArrayList<ElectionDto>(); PreparedStatement st = null; String query = "SELECT election_id, election_name, e.description, start_datetime, close_datetime, " + " status, s.code, s.description, owner_id, candidates_string " + " FROM election e" + " INNER JOIN status_election s " + " ON (e.status = s.status_id) " + " WHERE owner_id = ?" + " AND status = ?" + " ORDER BY election_id"; try { st = this.con.prepareStatement(query); st.setInt(1, electionOwnerId); st.setInt(2, electionStatus.getCode()); ResultSet res = st.executeQuery(); while (res.next()) { int electionId = res.getInt(1); String electionName = res.getString(2); String electionDescription = res.getString(3); Timestamp startDatetime = res.getTimestamp(4); Timestamp closeDatetime = res.getTimestamp(5); int statusId = res.getInt(6); String statusCode = res.getString(7); String statusDescription = res.getString(8); int ownerId = res.getInt(9); String candidatesListString = res.getString(10); ElectionDto electionDto = new ElectionDto(); electionDto.setElectionId(electionId); electionDto.setElectionName(electionName); electionDto.setElectionDescription(electionDescription); electionDto.setStartDatetime(startDatetime); electionDto.setCloseDatetime(closeDatetime); electionDto.setStatus(statusId); electionDto.setStatusCode(statusCode); electionDto.setStatusDescription(statusDescription); electionDto.setOwnerId(ownerId); electionDto.setCandidatesListString(candidatesListString); elections.add(electionDto); } validator.setVerified(true); validator.setObject(elections); validator.setStatus("Successfully selected"); } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); validator.setStatus("Select failed"); } return validator; } /** * @return Validator : ArrayList<ElectionDto> - List of all the elections * (regardless of status) * @author Hirosh Wickramasuriya */ public Validator selectElections() { Validator validator = new Validator(); ArrayList<ElectionDto> elections = new ArrayList<ElectionDto>(); PreparedStatement st = null; String query = "SELECT election_id, election_name, e.description, start_datetime, close_datetime," + " status, s.code, s.description, owner_id, candidates_string " + " FROM election e" + " INNER JOIN status_election s " + " ON (e.status = s.status_id)" + " ORDER BY election_id"; try { st = this.con.prepareStatement(query); ResultSet res = st.executeQuery(); while (res.next()) { int electionId = res.getInt(1); String electionName = res.getString(2); String electionDescription = res.getString(3); Timestamp startDatetime = res.getTimestamp(4); Timestamp closeDatetime = res.getTimestamp(5); int statusId = res.getInt(6); String statusCode = res.getString(7); String statusDescription = res.getString(8); int ownerId = res.getInt(9); String candidatesListString = res.getString(10); ElectionDto electionDto = new ElectionDto(); electionDto.setElectionId(electionId); electionDto.setElectionName(electionName); electionDto.setElectionDescription(electionDescription); electionDto.setStartDatetime(startDatetime); electionDto.setCloseDatetime(closeDatetime); electionDto.setStatus(statusId); electionDto.setStatusCode(statusCode); electionDto.setStatusDescription(statusDescription); electionDto.setOwnerId(ownerId); electionDto.setCandidatesListString(candidatesListString); elections.add(electionDto); } validator.setVerified(true); validator.setObject(elections); validator.setStatus("Successfully selected"); } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); validator.setStatus("Select failed"); } return validator; } /** * @param election_owner_id * (int) - user_id of the user who owns elections * @return Validator : ArrayList<ElectionDto> - List of all the elections (not disabled only) * owned by the specific user (regardless of status) * @author Hirosh Wickramasuriya */ public Validator selectElectionsOwnedByUser(int electionOwnerId) { Validator validator = new Validator(); ArrayList<ElectionDto> elections = new ArrayList<ElectionDto>(); PreparedStatement st = null; String query = "SELECT election_id, election_name, e.description, start_datetime, close_datetime," + " status, s.code, s.description, owner_id, candidates_string" + " FROM election e" + " INNER JOIN status_election s " + " ON (e.status = s.status_id) " + " WHERE owner_id = ? " + " AND status <> " + ElectionStatus.DELETED.getCode() + " ORDER BY status, election_id"; try { st = this.con.prepareStatement(query); st.setInt(1, electionOwnerId); ResultSet res = st.executeQuery(); while (res.next()) { int electionId = res.getInt(1); String electionName = res.getString(2); String electionDescription = res.getString(3); Timestamp startDatetime = res.getTimestamp(4); Timestamp closeDatetime = res.getTimestamp(5); int statusId = res.getInt(6); String statusCode = res.getString(7); String statusDescription = res.getString(8); int ownerId = res.getInt(9); String candidatesListString = res.getString(10); ElectionDto electionDto = new ElectionDto(); electionDto.setElectionId(electionId); electionDto.setElectionName(electionName); electionDto.setElectionDescription(electionDescription); electionDto.setStartDatetime(startDatetime); electionDto.setCloseDatetime(closeDatetime); electionDto.setStatus(statusId); electionDto.setStatusCode(statusCode); electionDto.setStatusDescription(statusDescription); electionDto.setOwnerId(ownerId); electionDto.setCandidatesListString(candidatesListString); elections.add(electionDto); } validator.setVerified(true); validator.setObject(elections); validator.setStatus("Successfully selected"); } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); validator.setStatus("Select failed"); } return validator; } public Validator selectAllElectionsForVoter(int user_id) { Validator val = new Validator(); ArrayList<ElectionDto> elecs = new ArrayList<ElectionDto>(); PreparedStatement st = null; String query = "SELECT e.election_id, e.election_name, e.description, e.owner_id, " + "e.start_datetime, e.close_datetime FROM election as e " + "LEFT JOIN vote as v ON e.election_id = v.election_id " + "WHERE (v.user_id is null OR v.user_id != ?) AND e.status = ? " + "GROUP BY e.election_id"; try { st = this.con.prepareStatement(query); st.setInt(1, user_id); st.setInt(2, ElectionStatus.OPEN.getCode()); ResultSet res = st.executeQuery(); while (res.next()) { ElectionDto e = new ElectionDto(); e.setElectionId(res.getInt(1)); e.setCandidateList((ArrayList<CandidateDto>) selectCandidatesOfElection( e.getElectionId() , Status.ENABLED).getObject()); e.setElectionName(res.getString(2)); e.setElectionDescription(res.getString(3)); e.setOwnerId(res.getInt(4)); e.setStartDatetime(res.getTimestamp(5)); e.setCloseDatetime(res.getTimestamp(6)); elecs.add(e); } val.setStatus("Retrieved Elections"); val.setVerified(true); val.setObject(elecs); return val; } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); val.setStatus("Select failed"); val.setVerified(false); return val; } } // Candidates /** * @param id * - candidate identification number (primary key) * @return Validator :CandidateDto - Details of a particular candidate * @author Hirosh Wickramasuriya */ public Validator selectCandidate(int id) { Validator validator = new Validator(); CandidateDto candidateDto = new CandidateDto(); PreparedStatement st = null; String query = "SELECT candidate_id, candidate_name, election_id, display_order, status FROM candidate WHERE candidate_id = ?"; try { st = this.con.prepareStatement(query); st.setInt(1, id); ResultSet res = st.executeQuery(); if (res.next()) { int candidateId = res.getInt(1); String candidate_name = res.getString(2); int electionId = res.getInt(3); int displayOrder = res.getInt(4); int statusId = res.getInt(5); candidateDto.setCandidateId(candidateId); candidateDto.setCandidateName(candidate_name); candidateDto.setElectionId(electionId); candidateDto.setDisplayOrder(displayOrder); candidateDto.setStatus(statusId); validator.setVerified(true); validator.setObject(candidateDto); validator.setStatus("Successfully selected"); } else { validator.setStatus("Candidate not found"); } } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); validator.setStatus("Select failed"); } return validator; } /** * @param electionIdKey * - election identification number * @return Validator : ArrayList<CandidateDto>- list of all the candidates * under specified election * @author Hirosh Wickramasuriya */ public Validator selectCandidatesOfElection(int electionIdKey) { Validator validator = new Validator(); ArrayList<CandidateDto> candidates = new ArrayList<CandidateDto>(); PreparedStatement st = null; String query = "SELECT candidate_id, candidate_name, election_id, display_order, status FROM candidate WHERE election_id = ?"; try { st = this.con.prepareStatement(query); st.setInt(1, electionIdKey); ResultSet res = st.executeQuery(); while (res.next()) { int candidateId = res.getInt(1); String candidateName = res.getString(2); int electionId = res.getInt(3); int displayOrder = res.getInt(4); int statusId = res.getInt(5); CandidateDto candidateDto = new CandidateDto(); candidateDto.setCandidateId(candidateId); candidateDto.setCandidateName(candidateName); candidateDto.setElectionId(electionId); candidateDto.setDisplayOrder(displayOrder); candidateDto.setStatus(statusId); candidates.add(candidateDto); } validator.setVerified(true); validator.setObject(candidates); validator.setStatus("Successfully selected"); } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); validator.setStatus("select failed"); } return validator; } /** * @param electionIdKey * - election identification number * @param candidateStatus * - desired status of candidate which required to be returned * for given election * @return Validator :ArrayList<CandidateDto> - list of all the candidates * that matches the status under specified election * @author Hirosh Wickramasuriya */ public Validator selectCandidatesOfElection(int electionIdKey, Status candidateStatus) { Validator validator = new Validator(); ArrayList<CandidateDto> candidates = new ArrayList<CandidateDto>(); PreparedStatement st = null; String query = "SELECT candidate_id, candidate_name, election_id, display_order, status " + " FROM candidate " + " WHERE election_id = ?" + " AND status = ?"; try { st = this.con.prepareStatement(query); st.setInt(1, electionIdKey); st.setInt(2, candidateStatus.getCode()); ResultSet res = st.executeQuery(); while (res.next()) { int candidateId = res.getInt(1); String candidateName = res.getString(2); int electionId = res.getInt(3); int displayOrder = res.getInt(4); int statusId = res.getInt(5); CandidateDto candidateDto = new CandidateDto(); candidateDto.setCandidateId(candidateId); candidateDto.setCandidateName(candidateName); candidateDto.setElectionId(electionId); candidateDto.setDisplayOrder(displayOrder); candidateDto.setStatus(statusId); candidates.add(candidateDto); } validator.setVerified(true); validator.setObject(candidates); validator.setStatus("Successfully selected"); } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); validator.setVerified(false); validator.setStatus("Select failed"); } return validator; } /** * @param name * - election name Add new election to db * @author Steven Frink */ private int addElectionWithCandidatesString(ElectionDto electionDto) { PreparedStatement st = null; ResultSet rs = null; int newId = 0; try { String query = "INSERT INTO election (election_name, description, status, owner_id, candidates_string) VALUES (?,?,?,?,?)"; int status = ElectionStatus.NEW.getCode(); st = this.con.prepareStatement(query, Statement.RETURN_GENERATED_KEYS); st.setString(1, electionDto.getElectionName()); st.setString(2, electionDto.getElectionDescription()); st.setInt(3, status); st.setInt(4, electionDto.getOwnerId()); st.setString(5, electionDto.getCandidatesListString()); // update query st.executeUpdate(); // get inserted id rs = st.getGeneratedKeys(); rs.next(); newId = rs.getInt(1); } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); } return newId; } // /** // * @param name // * - election name Add new election to db // * @author Steven Frink // */ // public Validator addElectionWithCandidates(ElectionDto electionDto) { // Validator out = new Validator(); // // Validate the election // Validator vElection = electionDto.Validate(); // Validator vCandidates = new Validator(); // if (vElection.isVerified()) { // // insert election // int electionId = addElection(electionDto); // if (electionId > 0) { // // if insert of elections was successful, insert candidate list // vCandidates = addCandidatesToElection(electionDto.getCandidateList(), electionId); // if (vCandidates.isVerified()) { // // if candidates insert was successful // ArrayList<CandidateDto> candidates = (ArrayList<CandidateDto>) vCandidates.getObject(); // electionDto.setElectionId(electionId); // electionDto.setCandidateList(candidates); // out.setVerified(true); // out.setStatus("Election has been successfully inserted"); // out.setObject(electionDto); // } else { // out.setVerified(false); // out.setStatus("Candidates insert failed"); // } else { // out.setVerified(false); // out.setStatus("Election insert failed"); // } else { // out.setVerified(false); // out.setStatus(vElection.getStatus()); // return out; /** * @param electionDto - election details * @return Validator - with ElectionDto object with primary key assigned by the db, upon successful insert * @author Hirosh Wickramasuriya */ public Validator addElection(ElectionDto electionDto) { Validator val = new Validator(); // Validate the election Validator vElection = electionDto.Validate(); if (vElection.isVerified()) { // insert election int electionId = addElectionWithCandidatesString(electionDto); if (electionId > 0) { electionDto.setElectionId(electionId); val.setVerified(true); val.setStatus("Election has been successfully inserted"); val.setObject(electionDto); } else { val.setVerified(false); val.setStatus("Election insert failed"); } } else { val = vElection; } return val; } /** * @param candidateDto * - candidate object * @param election_id * - id of the election which the candidate should be associated * @return Validator - status of the candidate insert operation * @author Hirosh Wickramasuriya */ private Validator addCandidate(CandidateDto candidateDto) { PreparedStatement st = null; ResultSet rs = null; Validator val = new Validator(); int newCandidateId = 0; try { String query = "INSERT INTO candidate (candidate_name, election_id, status, display_order) VALUES (?,?,?,?)"; st = this.con.prepareStatement(query, Statement.RETURN_GENERATED_KEYS); st.setString(1, candidateDto.getCandidateName()); st.setInt(2, candidateDto.getElectionId()); st.setInt(3, Status.ENABLED.getCode()); st.setInt(4, candidateDto.getDisplayOrder()); // run the query and get new candidate id st.executeUpdate(); rs = st.getGeneratedKeys(); rs.next(); newCandidateId = rs.getInt(1); if (newCandidateId > 0) { candidateDto.setCandidateId(newCandidateId); val.setVerified(true); val.setStatus("Candidates inserted successfully"); val.setObject(candidateDto); } else { val.setStatus("Failed to insert candidate"); } } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); val.setVerified(false); val.setStatus("SQL Error"); } return val; } /** * @param electionDto * - election data object * @return validator - status of election update operation * @author Hirosh / Dmitry */ public Validator editElectionWithCandidatesString(ElectionDto electionDto) { Validator out = new Validator(); // 0. check the election status. ElectionDto vElectionCurrent = (ElectionDto) selectElection(electionDto.getElectionId()).getObject(); if (vElectionCurrent.getStatus() == ElectionStatus.NEW.getCode()) { // 1. Validate Election Validator vElection = electionDto.Validate(); if (vElection.isVerified()) { // 2. Update the election details out = editElection(electionDto); } else { out = vElection; } } else { out.setStatus("Election status is " + vElectionCurrent.getStatusCode() + ", does not allow to modify."); } return out; } /** * @param electionDto * - election data object * @return validator - status of election update operation * @author Hirosh / Dmitry */ public Validator openElectionAndPopulateCandidates(int electionId) { Validator val = new Validator(); Validator vElectionStatus = compareElectionStatus(electionId, ElectionStatus.NEW); // Retrieve the election object in the db ElectionDto electionInDb = (ElectionDto)vElectionStatus.getObject(); if (vElectionStatus.isVerified()) { // 1. Validate the election, so that all the candidates get validated Validator vElection = electionInDb.Validate(); if (vElection.isVerified()) { // remove if there are any candidates already for this election deleteCandidates( electionInDb.getElectionId() ); // get the list of candidates Validator vAddCandidates = addCandidates(electionId, electionInDb.getCandidatesListString()); if (vAddCandidates.isVerified()) { Validator vElectionStatusNew = editElectionStatus(electionId, ElectionStatus.OPEN); if (vElectionStatusNew.isVerified()) { val.setVerified(true); val.setStatus("Election has been opened."); } else { val = vElectionStatusNew; } } else { val = vAddCandidates; } } else { val.setStatus(vElection.getStatus()); } } else { val.setStatus("Election status is " + electionInDb.getStatusCode() + ", does not allow to modify."); } return val; } private Validator addCandidates(int electionId, String candidatesListString) { Validator val = new Validator(); // split the list of candidates by new line into an array of string String[] candidateNames = candidatesListString.split(newLine); int displayOrder = 1; boolean status = true; for (String candidateName : candidateNames) { // add each candidate to this election CandidateDto candidateDto = new CandidateDto(); candidateDto.setCandidateName(candidateName); candidateDto.setDisplayOrder(displayOrder); candidateDto.setElectionId(electionId); // add candidate to the election Validator vCandiateInserted = addCandidate(candidateDto); val.setStatus(val.getStatus() + newLine + vCandiateInserted.getStatus()); status &= vCandiateInserted.isVerified(); displayOrder++; } val.setVerified(status); if (status) { val.setVerified(true); val.setStatus("Candidates have been added to the election"); } return val; } /** * @param candidateDto * - candidate object * @author Steven Frink */ private Validator editCandidate(CandidateDto candidateDto) { PreparedStatement st = null; Validator val = new Validator(); try { Validator vCandidate = candidateDto.Validate(); if (vCandidate.isVerified()) { // String query = // "UPDATE candidate SET (candidate_name, display_order)=(?,?) WHERE candidate_id=?"; String query = "UPDATE candidate " + " SET candidate_name = ?, " + " display_order = ?, " + " status = ?" + " WHERE candidate_id = ?"; st = this.con.prepareStatement(query, Statement.RETURN_GENERATED_KEYS); st.setString(1, candidateDto.getCandidateName()); st.setInt(2, candidateDto.getDisplayOrder()); st.setInt(3, candidateDto.getStatus()); st.setInt(4, candidateDto.getCandidateId()); int updateCount = st.executeUpdate(); if (updateCount > 0) { val.setStatus("Candidate updated successfully"); val.setVerified(true); } else { val.setStatus("Failed to update candidate"); } } else { val = vCandidate; } } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); val.setStatus("SQL Error"); val.setVerified(false); } return val; } public Validator editCandidateStatus(CandidateDto cand) { PreparedStatement st = null; //InputValidation iv = new InputValidation(); Validator val = new Validator(); try { //val = iv.validateInt(cand.getStatus(), "Candidate Status"); if (val.isVerified()) { String query = "UPDATE candidate SET status=? WHERE candidate_id=?"; st = this.con.prepareStatement(query); st.setInt(1, cand.getStatus()); st.setInt(2, cand.getCandidateId()); st.execute(); val.setVerified(true); val.setStatus("Candidate status updated"); } else { val.setStatus("Status failed to verify"); } } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); val.setStatus("SQL Error"); } return val; } /** * @param electionId - election identification number * @return boolean - true : if the election is deleted successfully, else false * @author Hirosh Wickramasuriya */ private boolean deleteCandidates(int electionId) { PreparedStatement st = null; ResultSet rs = null; boolean status = false; try { String query = "DELETE FROM candidate WHERE election_id = ?"; st = this.con.prepareStatement(query, Statement.RETURN_GENERATED_KEYS); st.setInt(1, electionId); // update query if (st.executeUpdate() < 0) { // delete failed } else { // delete= sucessful status = true; } } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); } return status; } /** * @param electionId * - the election to open Add candidates to an election * @author Steven Frink */ *//** /* * public Validator openElection(int electionId) { PreparedStatement st = * null; Validator val = new Validator(); * * try { String query = "UPDATE election" + " SET status=" + * ElectionStatus.NEW.getCode() + " WHERE election_id=" + electionId; st = * this.con.prepareStatement(query); st.execute(); val.setVerified(true); * val.setStatus("Election opened"); return val; } catch (SQLException ex) { * Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); * lgr.log(Level.WARNING, ex.getMessage(), ex); val.setStatus("SQL Error"); * val.setVerified(false); return val; } } * @param electionId * - the election to close Close an election * @author Steven Frink */ *//** /* * public Validator closeElection(int electionId) { PreparedStatement st = * null; Validator val = new Validator(); try { String query = * "UPDATE election" + " SET status=" + ElectionStatus.CLOSED.getCode() + * " WHERE election_id=" + electionId; st = * this.con.prepareStatement(query); st.execute(); val.setVerified(true); * val.setStatus("Election closed"); return val; } catch (SQLException ex) { * Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); * lgr.log(Level.WARNING, ex.getMessage(), ex); val.setVerified(false); * val.setStatus("SQL Error"); return val; } } * @param electionId * - the election to delete Delete an election * @author Steven Frink */ /* * public Validator deleteElection(int electionId) { PreparedStatement st = * null; Validator val = new Validator(); try { String query = * "UPDATE election SET status=7 WHERE election_id=" + electionId; st = * this.con.prepareStatement(query); st.execute(); * val.setStatus("Election deleted"); val.setVerified(true); return val; } * catch (SQLException ex) { Logger lgr = * Logger.getLogger(DatabaseConnector.class.getName()); * lgr.log(Level.WARNING, ex.getMessage(), ex); val.setStatus("SQL Error"); * val.setVerified(false); return val; } } */ /** * @param electionId * - the election id to update the status Delete an election * @param electionStatus * - new status of the election * @return validator - validator object with response of update operation * @author Steven Frink */ public Validator editElectionStatus(int electionId, ElectionStatus electionStatus) { PreparedStatement st = null; Validator val = new Validator(); try { String query = "UPDATE election SET status=? WHERE election_id=?"; st = this.con.prepareStatement(query, Statement.RETURN_GENERATED_KEYS); st.setInt(1, electionStatus.getCode()); st.setInt(2, electionId); st.executeUpdate(); int updateCount = st.getUpdateCount(); if (updateCount > 0) { val.setStatus("Election status updated successfully"); val.setVerified(true); } else { val.setStatus("Failed to update the election status"); } } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); val.setStatus("SQL Error"); } return val; } /** * @param electionDto * - the election to edit Edit an election * @author Steven Frink */ public Validator editElection(ElectionDto electionDto) { PreparedStatement st = null; Validator val = new Validator(); try { String query = "UPDATE election SET election_name=?, " + " description = ?, " + " candidates_string = ? " + " WHERE election_id=?"; st = this.con.prepareStatement(query, Statement.RETURN_GENERATED_KEYS); st.setString(1, electionDto.getElectionName()); st.setString(2, electionDto.getElectionDescription()); st.setString(3, electionDto.getCandidatesListString()); st.setInt(4, electionDto.getElectionId()); st.executeUpdate(); int updateCount = st.getUpdateCount(); if (updateCount > 0) { val.setStatus("Election updated successfully"); val.setVerified(true); } else { val.setStatus("Failed to update the election"); } } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); val.setStatus("SQL Error"); } return val; } // Vote /** * @param voteDto * - the vote to submit Submit a vote * @author Steven Frink */ public Validator vote(VoteDto voteDto) { PreparedStatement st = null; Validator val = new Validator(); if (voteDto.Validate().isVerified()) { try { String query = "SELECT user_id, election_id FROM vote WHERE user_id=? AND election_id=?"; st = this.con.prepareStatement(query); st.setInt(1, voteDto.getUserId()); st.setInt(2, voteDto.getElectionId()); ResultSet rs = st.executeQuery(); SecurityValidator sec = new SecurityValidator(); if (!rs.next() && sec.checkSignature(voteDto.getVoteSignature(), voteDto.getVoteEncrypted(), voteDto.getUserId()).isVerified()) { query = "INSERT INTO vote (user_id, election_id, vote_encrypted, vote_signature)" + " VALUES (?,?,?,?)"; st = this.con.prepareStatement(query, Statement.RETURN_GENERATED_KEYS); st.setInt(1, voteDto.getUserId()); st.setInt(2, voteDto.getElectionId()); st.setString(3, voteDto.getVoteEncrypted()); st.setString(4, voteDto.getVoteSignature()); int updateCount = st.executeUpdate(); if (updateCount > 0) { val.setStatus("Vote successfully cast"); val.setVerified(true); } else { val.setStatus("Failed to cast vote"); } } else { val.setStatus("invalid signature for this vote"); } } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); val.setStatus("SQL Error"); } } else { val.setStatus("Vote information did not validate"); } return val; } /** * @param userDto * - userDetails with public key * @return Validator - status of the public key update operation * @author Hirosh Wickramasuriya * */ public Validator editUserPublicKey(UserDto userDto) { PreparedStatement st = null; Validator val = new Validator(); String query = "UPDATE users SET public_key = ? WHERE user_id = ?"; Validator vUserDto = userDto.Validate(); if (vUserDto.isVerified()) { try { st = this.con.prepareStatement(query, Statement.RETURN_GENERATED_KEYS); st.setString(1, userDto.getPublicKey()); st.setInt(2, userDto.getUserId()); int updateCount = st.executeUpdate(); if (updateCount > 0) { val.setStatus("User's public key updated successfully"); val.setVerified(true); } else { val.setStatus("Failed to update the user's public key"); } } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); val.setStatus("SQL Error"); } } else { val = vUserDto; } return val; } /** * @param userDto * - userDto with the userId * @return Validator - with user's public key * @author Steven Frink */ public Validator selectUserPublicKey(UserDto userDto) { PreparedStatement st = null; Validator val = new Validator(); InputValidation iv = new InputValidation(); Validator vUserDto = iv.validateInt(userDto.getUserId(), "User ID"); // Validator vUserDto = userDto.Validate(); if (vUserDto.isVerified()) { String query = "SELECT public_key FROM users WHERE user_id = ?"; try { st = this.con.prepareStatement(query); st.setInt(1, userDto.getUserId()); ResultSet res = st.executeQuery(); if (res.next()) { Blob pubKey = res.getBlob(1); byte[] pk = pubKey.getBytes(1, (int) pubKey.length()); val.setObject(pk); val.setVerified(true); val.setStatus("Public key retrieved"); } else { val.setStatus("No public key for this user id"); } } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); val.setStatus("SQL Error"); } } else { val = vUserDto; // Failed to validate the user id } return val; } public Validator selectVotesByElectionId(int election_id) { Validator val = new Validator(); InputValidation iv = new InputValidation(); ArrayList<VoteDto> votes = new ArrayList<VoteDto>(); Validator vElection = iv.validateInt(election_id, "Election ID"); PreparedStatement st = null; try { if (vElection.isVerified()) { String query = "SELECT user_id, vote_encrypted, vote_signature, timestamp " + " FROM vote " + " WHERE election_id = ?"; st = this.con.prepareStatement(query); st.setInt(1, election_id); ResultSet res = st.executeQuery(); while (res.next()) { int user_id = res.getInt(1); String vote_encrypted = res.getString(2); String vote_signature = res.getString(3); Timestamp t = res.getTimestamp(4); VoteDto vote = new VoteDto(); vote.setUserId(user_id); vote.setVoteEncrypted(vote_encrypted); vote.setVoteSignature(vote_signature); vote.setElectionId(election_id); vote.setTimestamp(t); votes.add(vote); } val.setStatus("Successfully retrieved votes"); val.setObject(votes); val.setVerified(true); } else { val = vElection; // Failed to validate the election id } } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); val.setStatus("SQL Error"); } return val; } public Validator checkCandidateInElection(int electionId, int cand_id){ Validator val=new Validator(); ArrayList<CandidateDto> candidatesOfElection = (ArrayList<CandidateDto>) selectCandidatesOfElection(electionId, Status.ENABLED).getObject(); boolean validCand = false; for (int j = 0; j < candidatesOfElection.size(); j++) { if (candidatesOfElection.get(j).getCandidateId() == cand_id) { validCand = true; break; } } val.setVerified(validCand); return val; } private Map<Integer, CandidateDto> initMap(ElectionDto elec){ Map<Integer, CandidateDto> map = new HashMap<Integer, CandidateDto>(); // initialize the hashmap to have all the candidates for (CandidateDto candidate : elec.getCandidateList()) { map.put(candidate.getCandidateId(), candidate); } return map; } private Map<Integer, CandidateDto> addToMap(Map<Integer, CandidateDto> map, int cand_id){ if (map.containsKey(cand_id)) { // candidateDto is in the Hashmap CandidateDto candidateDto = map.get(cand_id); candidateDto.addVoteCount(); // replace the candidateDto in the Hashmap map.remove(cand_id); map.put(cand_id, candidateDto); // TODO: not sure without these twolines, // value is udpated by reference } else { // this is a new candidateDto to the Hashmap CandidateDto candidateDto = (CandidateDto) selectCandidate(cand_id).getObject(); candidateDto.setVoteCount(1); // First voted counted map.put(cand_id, candidateDto); } return map; } private ElectionDto putResultsInElection(Map<Integer, CandidateDto> map, ElectionDto e){ ArrayList<CandidateDto> candidateResultList = new ArrayList<CandidateDto>(); Iterator<Integer> iterator = map.keySet().iterator(); while (iterator.hasNext()) { Integer key = iterator.next(); CandidateDto candidateResult = map.get(key); candidateResultList.add(candidateResult); } e.setCandidateList(candidateResultList); return e; } private int getDecryptedCandId(VoteDto vote){ String enc = vote.getVoteEncrypted(); String sig = vote.getVoteSignature(); SecurityValidator sec=new SecurityValidator(); if (sec.checkSignature(sig, enc, vote.getUserId()).isVerified()){ byte[] plain=sec.hexStringtoByteArray(sec.decrypt(enc)); String id=new String(plain); int cand_id = Integer.parseInt(id); return cand_id; } else{ return -1; } } /** * @param electionId * @return Validator with ElectionDto that has results * @author Steven Frink/Hirosh Wickramasuriya */ public Validator tally(ElectionDto elec) { Validator val = new Validator(); // get the votes for this election Validator voteVal = selectVotesByElectionId(elec.getElectionId()); if (voteVal.isVerified()) { Map<Integer, CandidateDto> map=initMap(elec); ArrayList<VoteDto> votes = (ArrayList<VoteDto>) voteVal.getObject(); // all the votes for the election // check the validity of each vote, decrypt and count the vote for (int i = 0; i < votes.size(); i++) { int cand_id=getDecryptedCandId(votes.get(i)); if (cand_id!=-1) { map=addToMap(map, cand_id); } } // attach the candidates list with results to the ElectionDto elec=putResultsInElection(map, elec); val.setStatus("Tally computed"); val.setObject(elec); val.setVerified(true); } else { val = voteVal; } return val; } /** * @param electionId * @return Validator with ElectionProgressDto * @author Hirosh Wickramasuriya */ public Validator voteProgressStatusForElection(int electionId) { Validator val = new Validator(); SecurityValidator sec = new SecurityValidator(); ElectionProgressDto electionProgressDto = new ElectionProgressDto(); if (electionId > 0) { electionProgressDto.setElectionId(electionId); Validator valVote = selectVotesByElectionId(electionId); if (valVote.isVerified()) { ArrayList<VoteDto> votes = (ArrayList<VoteDto>) valVote.getObject(); electionProgressDto.setTotalVotes(votes.size()); for (VoteDto voteDto : votes) { // check for the validity if (sec.checkSignature(voteDto).isVerified()) { // valid vote electionProgressDto.addValidVotes(1); } else { // rejected vote electionProgressDto.addRejectedVotes(1); } } // bind the final result to the validator val.setObject(electionProgressDto); val.setStatus("Election progress computed"); val.setVerified(true); } else { val = valVote; } } else { val.setStatus("Invalid Election Id"); } return val; } public Validator publishResults(int electionId) { Validator val = new Validator(); Validator vElectionStatus = compareElectionStatus(electionId, ElectionStatus.CLOSED); if (vElectionStatus.isVerified()) { Validator vResult = computeElectionResults(electionId); if (vResult.isVerified()) { vElectionStatus = editElectionStatus(electionId, ElectionStatus.PUBLISHED); if (vElectionStatus.isVerified()) { val.setStatus("Election results has been published"); val.setVerified(true); } else { val = vElectionStatus; } } else { val = vResult; } } else { val = vElectionStatus; } return val; } /** * @param electionId - election identificatin number * @return Validator - (1) true if the election results computed and the table is populated successfully * (2) false if it failed to compute and populate the election results * @author Hirosh Wickramasuriya */ private Validator computeElectionResults(int electionId) { Validator val = new Validator(); // check the election status Validator vElectionStatus = compareElectionStatus(electionId, ElectionStatus.CLOSED); if (vElectionStatus.isVerified()) { ElectionDto electionDto = (ElectionDto)vElectionStatus.getObject(); // get the tallying results Validator vElectionTally = tally(electionDto); if (vElectionTally.isVerified()) { // Get the results for each candidates electionDto = (ElectionDto)vElectionTally.getObject(); ArrayList<CandidateDto> candidates = electionDto.getCandidateList(); boolean valid = true; for (CandidateDto candidate : candidates) { if (addResult(candidate) > 0) { valid &= true; // result has been added } else { // Failed to add the result deleteResults(electionDto.getElectionId()); // delete existing results if any val.setStatus("Failed to add results"); // set the validator valid &= false; break; } } val.setVerified(valid); if (valid) { val.setStatus("Results added successfully"); } else { val.setStatus("Failed to add results"); } } else { val = vElectionTally; } } else { val = vElectionStatus; } return val; } /** * @param ElectionDto - Election object * @param electionStatus - ElectionStatus enumerated value * @return Validator - the property isVerified() contains whether the given status * matches to the status of the given electionDto * @author Hirosh Wickramasuriya */ private Validator compareElectionStatus(ElectionDto electionDto, ElectionStatus electionStatus) { Validator val = new Validator(); if (electionDto.getStatus() == electionStatus.getCode()) { val.setObject(electionDto); val.setStatus("Status matched"); val.setVerified(true); } else { val.setStatus("Election is not in the " + electionStatus.getLabel() + " status"); } return val; } /** * @param electionId - Election identification number * @param electionStatus - ElectionStatus enumerated value * @return Validator - the property isVerified() contains whether the given status * matches to the status recorded in the database for the given election id * @author Hirosh Wickramasuriya */ private Validator compareElectionStatus(int electionId, ElectionStatus electionStatus) { Validator val = new Validator(); Validator vElection = selectElection(electionId); if (vElection.isVerified()) { val = compareElectionStatus((ElectionDto)vElection.getObject(), electionStatus ); } else { val = vElection; } return val; } /** * @param candidateDto * @return * @author Hirosh Wickramasuriya */ private int addResult(CandidateDto candidateDto) { PreparedStatement st = null; ResultSet rs = null; int newId = 0; try { String query = "INSERT INTO results (election_id, candidate_id, vote_count) VALUES (?,?,?)"; st = this.con.prepareStatement(query, Statement.RETURN_GENERATED_KEYS); st.setInt(1, candidateDto.getElectionId()); st.setInt(2, candidateDto.getCandidateId()); st.setInt(3, candidateDto.getVoteCount()); // update query st.executeUpdate(); // get inserted id rs = st.getGeneratedKeys(); rs.next(); newId = rs.getInt(1); } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); } return newId; } /** * @param electionId - election identification number * @return boolean - true : if the election is deleted successfully, else false * @author Hirosh Wickramasuriya */ private boolean deleteResults(int electionId) { PreparedStatement st = null; ResultSet rs = null; boolean status = false; try { String query = "DELETE FROM results WHERE election_id = ?"; st = this.con.prepareStatement(query, Statement.RETURN_GENERATED_KEYS); st.setInt(1, electionId); // update query if (st.executeUpdate() < 0) { // delete failed } else { // delete= sucessful status = true; } } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); } return status; } /** * @param electionId - election identification number * @return Validator - with ElectionDto having results of each candidates * @author Hirosh Wickramasuriya */ public Validator selectResults(int electionId) { Validator val = new Validator(); ArrayList<CandidateDto> candidates = new ArrayList<CandidateDto>(); PreparedStatement st = null; Validator vElectionStatus = compareElectionStatus(electionId, ElectionStatus.PUBLISHED); if (vElectionStatus.isVerified()) { ElectionDto electionDto = (ElectionDto)vElectionStatus.getObject(); try { // get the results String query = "SELECT r.election_id, r.candidate_id, vote_count, candidate_name, display_order, status" + " FROM results r" + " INNER JOIN candidate c" + " ON (r.candidate_id = c.candidate_id)" + " WHERE r.election_id = ?"; st = this.con.prepareStatement(query); st.setInt(1, electionId); ResultSet res = st.executeQuery(); while (res.next()) { int resElectionId = res.getInt(1); int resCandidateId = res.getInt(2); int resVoteCount = res.getInt(3); String resCandiateName = res.getString(4); int resDisplayOrder = res.getInt(5); int resStatus = res.getInt(6); // populate candidates list CandidateDto candidateDto = new CandidateDto(); candidateDto.setCandidateId(resCandidateId); candidateDto.setCandidateName(resCandiateName); candidateDto.setElectionId(resElectionId); candidateDto.setDisplayOrder(resDisplayOrder); candidateDto.setVoteCount(resVoteCount); candidateDto.setStatus(resStatus); candidates.add(candidateDto); } electionDto.setCandidateList(candidates); // attach candidates list to the election // set the validator val.setVerified(true); val.setObject(electionDto); val.setStatus("Results selected successfully"); } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); val.setStatus("Select failed"); } } else { val = vElectionStatus; } return val; } // User /** * @param userDto * @return Validator with the userDto including the primary key assigned by the db. * @author Hirosh Wickramasuriya */ public Validator addUser(UserDto userDto) { Validator val = new Validator(); PreparedStatement st = null; ResultSet rs = null; int newUserId = 0; // Validate the user Validator vUser = userDto.Validate(); if (vUser.isVerified()) { // insert user String query = "INSERT INTO users (first_name, last_name, email) " + " VALUES (?, ?, ?)"; try { st = this.con.prepareStatement(query, Statement.RETURN_GENERATED_KEYS); st.setString(1, userDto.getFirstName()); st.setString(2, userDto.getLastName()); st.setString(3, userDto.getEmail()); // run the query and get new user id st.executeUpdate(); rs = st.getGeneratedKeys(); rs.next(); newUserId = rs.getInt(1); if (newUserId > 0) { userDto.setUserId(newUserId); val.setVerified(true); val.setStatus("User inserted successfully"); val.setObject(userDto); } else { val.setStatus("Failed to insert user"); } } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); val.setVerified(false); val.setStatus("SQL Error"); } } else { val = vUser; } return val; } /** * @return - Validator with ArrayList<UserDto> all the users in the system * @author Hirosh Wickramasuriya */ public Validator selectAllUsers() { Validator val = new Validator(); ArrayList<UserDto> users = new ArrayList<UserDto>(); PreparedStatement st = null; String query = "SELECT user_id, first_name, last_name, email " + " , u.status, s.description " + " FROM users u" + " INNER JOIN status_user s" + " ON (u.status = s.status_id)" + " ORDER BY user_id"; try { st = this.con.prepareStatement(query); ResultSet res = st.executeQuery(); while (res.next()) { UserDto userDto = new UserDto(); userDto.setUserId(res.getInt(1)); userDto.setFirstName(res.getString(2)); userDto.setLastName(res.getString(3)); userDto.setEmail(res.getString(4)); userDto.setStatus(res.getInt(5)); userDto.setStatusDescription(res.getString(6)); users.add(userDto); } val.setStatus("Retrieved Users"); val.setVerified(true); val.setObject(users); } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); val.setStatus("Select failed"); } return val; } /** * @param - userId - user identificaiton number * @return - Validator with UserDto containing user information for the given user id * @author Hirosh Wickramasuriya */ public Validator selectUser(int userId) { Validator val = new Validator(); UserDto userDto = new UserDto(); PreparedStatement st = null; String query = "SELECT user_id, first_name, last_name, email " + " , u.status, s.description " + " FROM users u" + " INNER JOIN status_user s" + " ON (u.status = s.status_id)" + " WHERE user_id = ?"; try { st = this.con.prepareStatement(query); st.setInt(1, userId); ResultSet res = st.executeQuery(); if (res.next()) { userDto.setUserId(res.getInt(1)); userDto.setFirstName(res.getString(2)); userDto.setLastName(res.getString(3)); userDto.setEmail(res.getString(4)); userDto.setStatus(res.getInt(5)); userDto.setStatusDescription(res.getString(6)); val.setStatus("Retrieved user information"); val.setVerified(true); val.setObject(userDto); } else { val.setStatus("User not found "); } } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); val.setStatus("Select failed"); } return val; } /** * @param userDto * @return with the verified status true upon successful update, false otherwise * @author Hirosh Wickramasuriya */ public Validator editUser(UserDto userDto) { Validator val = new Validator(); PreparedStatement st = null; try { String query = "UPDATE users SET first_name = ?," + " last_name = ?," + " email = ?," + " status = ? " + " WHERE user_id=?"; st = this.con.prepareStatement(query, Statement.RETURN_GENERATED_KEYS); st.setString(1, userDto.getFirstName()); st.setString(2, userDto.getLastName()); st.setString(3, userDto.getEmail()); st.setInt(4, userDto.getStatus()); st.setInt(5, userDto.getUserId()); st.executeUpdate(); int updateCount = st.getUpdateCount(); if (updateCount > 0) { val.setStatus("User updated successfully"); val.setVerified(true); } else { val.setStatus("Failed to update the user"); } } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); val.setStatus("SQL Error"); } return val; } /** * @param userId * @param userStatus - UserStatus enumeration value * @return Validator with status true upon successful update, false otherwise * @author Hirosh Wickramasuriya */ public Validator editUserStatus(int userId, UserStatus userStatus){ Validator val = new Validator(); PreparedStatement st = null; try { String query = "UPDATE users SET status = ? WHERE user_id=?"; st = this.con.prepareStatement(query, Statement.RETURN_GENERATED_KEYS); st.setInt(1, userStatus.getCode()); st.setInt(2, userId); st.executeUpdate(); int updateCount = st.getUpdateCount(); if (updateCount > 0) { val.setStatus("User status updated successfully"); val.setVerified(true); } else { val.setStatus("Failed to update the user status"); } } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); val.setStatus("SQL Error"); } return val; } }
package database_comm; import java.sql.*; import com.microsoft.sqlserver.jdbc.*; public class DatabaseComm { static final String JDBC_DRIVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; static final String DB_URL = "jdbc:mysql://localhost/EMP"; static final String USER = "sa"; static final String PASS = "brianbrian"; //Debug localhost string static final String connectionUrl = "jdbc:sqlserver://150.250.147.167:1433;DatabaseName=REDFOX;user=sa;password=brianbrian;"; //Debug RBMS string //String connectionUrl = "jdbc:sqlserver://rbmsdemo.dyndns.org:1433;DatabaseName=REDFOX;user=Brian;password=brianbrian;"; //Debug item class for SQL connection //TODO remove private static class Item { public String barcode; public String description; public int price; //public int cost; public String toString() { return barcode + ", " + description + ", " + price; } } //TODO make not main public static void main(String[] args) throws ClassNotFoundException, SQLException { Item retrievedItem = getItemFromBarcode("12345678"); System.out.println(retrievedItem); } public static Item getItemFromBarcode(String barcode) throws ClassNotFoundException, SQLException { //I don't know what this line really does //No touch Class.forName(JDBC_DRIVER); System.out.println("Connecting to database..."); Connection con = DriverManager.getConnection(connectionUrl); //Create statement Statement stmt = con.createStatement(); //Create and execute query to find items String query = "SELECT * FROM ITEMS WHERE BARCODE = '" + barcode + "'"; ResultSet rs = stmt.executeQuery(query); //Check if our query got any results if (rs.next()) { //If so, return item with variables assigned Item returnItem = new Item(); returnItem.barcode = barcode; returnItem.description = rs.getString("DESCR"); returnItem.price = (int)(rs.getFloat("PRICE") * 100); return returnItem; } else { //If not, return null System.out.println("Item with barcode " + barcode + " not found"); return null; } } }
package models; import java.io.File; import java.io.IOException; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.List; import org.opentripplanner.analyst.ResultFeature; import play.Logger; import play.libs.Akka; import utils.DataStore; import utils.HashUtils; import akka.actor.ActorRef; import akka.actor.Props; import akka.actor.UntypedActor; import com.conveyal.otpac.JobItemCallback; import com.conveyal.otpac.message.JobSpec; import com.conveyal.otpac.message.JobStatus; import com.conveyal.otpac.message.WorkResult; import com.conveyal.otpac.standalone.StandaloneCluster; import com.conveyal.otpac.standalone.StandaloneExecutive; import com.conveyal.otpac.standalone.StandaloneWorker; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.vividsolutions.jts.geom.Geometry; import controllers.Api; import controllers.Application; import controllers.Tiles; @JsonIgnoreProperties(ignoreUnknown = true) public class Query implements Serializable { private static HashMap<String, List<ResultFeature>> resultsQueue = new HashMap<String, List<ResultFeature>>(); private static final long serialVersionUID = 1L; static DataStore<Query> queryData = new DataStore<Query>("queries"); public String id; public String projectId; public String name; public Integer jobId; public String akkaId; public String mode; public String pointSetId; public String scenarioId; public String status; public Integer totalPoints; public Integer completePoints; @JsonIgnore transient private DataStore<ResultFeature> results; public Query() { } static public Query create() { Query query = new Query(); query.save(); return query; } /** * Get the pointset name. This is used in the UI so that we can display the name of the pointset. */ public String getPointSetName () { SpatialLayer l = SpatialLayer.getPointSetCategory(pointSetId); if (l == null) return null; return l.name; } public void save() { // assign id at save if(id == null || id.isEmpty()) { Date d = new Date(); id = HashUtils.hashString("q_" + d.toString()); Logger.info("created query q " + id); } queryData.save(id, this); Logger.info("saved query q " +id); } public void run() { ActorRef queryActor = Akka.system().actorOf(Props.create(QueryActor.class)); System.out.println(queryActor.path()); queryActor.tell(this, null); akkaId = queryActor.path().name(); save(); } public void delete() throws IOException { queryData.delete(id); Logger.info("delete query q" +id); } @JsonIgnore public synchronized DataStore<ResultFeature> getResults() { if(results == null) { results = new DataStore<ResultFeature>(new File(Application.dataPath, "results"), "r_" + id); } return results; } public Integer getPercent() { if(this.totalPoints != null && this.completePoints != null && this.totalPoints > 0) return Math.round((float)((float)this.completePoints / (float)this.totalPoints) * 100); else return 0; } static public Query getQuery(String id) { return queryData.getById(id); } static public Collection<Query> getQueries(String projectId) { if(projectId == null) return queryData.getAll(); else { Collection<Query> data = new ArrayList<Query>(); for(Query sd : queryData.getAll()) { if(sd.projectId != null && sd.projectId.equals(projectId)) data.add(sd); } return data; } } static void saveQueryResult(String id, ResultFeature rf) { Query q = getQuery(id); if(q == null) return; ArrayList<ResultFeature> writeList = null; synchronized(resultsQueue) { if(!resultsQueue.containsKey(id)) resultsQueue.put(id, new ArrayList<ResultFeature>()); resultsQueue.get(id).add(rf); if(resultsQueue.get(id).size() > 10) { writeList = new ArrayList<ResultFeature>(resultsQueue.get(id)); resultsQueue.get(id).clear(); Logger.info("flushing queue..."); } } if(writeList != null){ for(ResultFeature rf1 : writeList) q.getResults().saveWithoutCommit(rf1.id, rf1); q.getResults().commit(); Tiles.resetQueryCache(id); } } static void updateStatus(String id, JobStatus js) { Query q = getQuery(id); if(q == null) return; synchronized(q) { q.totalPoints = (int)js.total; q.completePoints = (int)js.complete; q.jobId = js.curJobId; q.save(); } Logger.info("status update: " + js.complete + "/" + js.total); } public static class QueryActor extends UntypedActor { public void onReceive(Object message) throws Exception { if (message instanceof Query) { final Query q = (Query)message; SpatialLayer sl = SpatialLayer.getPointSetCategory(q.pointSetId); sl.writeToClusterCache(true); StandaloneCluster cluster = new StandaloneCluster("s3credentials", true, Api.analyst.getGraphService()); StandaloneExecutive exec = cluster.createExecutive(); StandaloneWorker worker = cluster.createWorker(); cluster.registerWorker(exec, worker); String graphTimeZone = Api.analyst.getGraphService().getGraph(q.scenarioId).getTimeZone().getID(); JobSpec js = new JobSpec(q.scenarioId, q.pointSetId + ".json", q.pointSetId + ".json", "2014-12-04", "8:05 AM", graphTimeZone, q.mode, null); // plus a callback that registers how many work items have returned class CounterCallback implements JobItemCallback { @Override public synchronized void onWorkResult(WorkResult res) { Query.saveQueryResult(q.id, res.getResult()); } } CounterCallback callback = new CounterCallback(); js.setCallback(callback); // start the job exec.find(js); JobStatus status = null; // wait for job to complete do { Thread.sleep(500); try { status = exec.getJobStatus().get(0); if(status != null) Query.updateStatus(q.id, status); else Logger.debug("waiting for job status messages, incomplete"); } catch (Exception e) { Logger.debug("waiting for job status messages"); } } while(status == null || !status.isComplete()); cluster.stop(worker); } } } }
package dr.app.tools; import dr.evolution.io.TreeExporter; import dr.evolution.tree.NodeRef; import dr.evolution.tree.Tree; import java.io.PrintStream; import java.text.NumberFormat; import java.util.*; /** * @author Andrew Rambaut * @author Alexei Drummond * @version $Id: NexusExporter.java,v 1.5 2006/09/08 11:34:53 rambaut Exp $ */ public class NexusExporter implements TreeExporter { public static final String DEFAULT_TREE_PREFIX = "TREE"; public static final String SPECIAL_CHARACTERS_REGEX = ".*[\\s\\.;,\"\'].*"; public NexusExporter(PrintStream out) { this.out = out; } /** * Sets the name to use for each tree (will be suffixed by tree number) * * @param treePrefix */ public void setTreePrefix(String treePrefix) { this.treePrefix = treePrefix; } /** * Sets the number format to use for outputting branch lengths * * @param format */ public void setNumberFormat(NumberFormat format) { formatter = format; } /** * @param sorted true if you wish the translation table to be alphabetically sorted. */ public void setSortedTranslationTable(boolean sorted) { this.sorted = sorted; } /** * @param trees the array of trees to export * @param attributes true if the nodes should be annotated with their attributes * @param treeNames Names of the trees */ public void exportTrees(Tree[] trees, boolean attributes, String[] treeNames) { if(!(treeNames==null) && trees.length != treeNames.length) { throw new RuntimeException("Number of trees and number of tree names is not the same"); } Map<String, Integer> idMap = writeNexusHeader(trees[0]); out.println("\t\t;"); for (int i = 0; i < trees.length; i++) { if(treeNames==null) { writeNexusTree(trees[i], treePrefix + i, attributes, idMap); } else { writeNexusTree(trees[i], treeNames[i], attributes, idMap); } } out.println("End;"); } public void exportTrees(Tree[] trees, boolean attributes) { exportTrees(trees, attributes, null); } public void exportTrees(Tree[] trees) { exportTrees(trees, true, null); } /** * Export a tree with all its attributes. * * @param tree the tree to export. */ public void exportTree(Tree tree) { Map<String, Integer> idMap = writeNexusHeader(tree); out.println("\t\t;"); writeNexusTree(tree, treePrefix + 1, true, idMap); out.println("End;"); } public void writeNexusTree(Tree tree, String s, boolean attributes, Map<String, Integer> idMap) { // PAUP marks rooted trees thou String treeAttributes = "[&R] "; // Place tree level attributes in tree comment StringBuilder treeComment = null; { Iterator<String> iter = tree.getAttributeNames(); if (iter != null) { while (iter.hasNext()) { final String name = iter.next(); final String value = tree.getAttribute(name).toString(); if( name.equals("weight") ) { treeAttributes = treeAttributes + "[&W " + value + " ] "; } else { if( treeComment == null ) { treeComment = new StringBuilder(" ["); } else if( treeComment.length() > 2 ) { treeComment.append(", "); } treeComment.append(name).append(" = ").append(value); } } if( treeComment != null ) { treeComment.append("]"); } } } out.print("tree " + s + ((treeComment != null) ? treeComment.toString() : "") + " = " + treeAttributes); writeNode(tree, tree.getRoot(), attributes, idMap); out.println(";"); } public Map<String, Integer> writeNexusHeader(Tree tree) { int taxonCount = tree.getTaxonCount(); List<String> names = new ArrayList<String>(); for (int i = 0; i < tree.getTaxonCount(); i++) { names.add(tree.getTaxonId(i)); } if (sorted) Collections.sort(names); out.println("#NEXUS"); out.println(); out.println("Begin taxa;"); out.println("\tDimensions ntax=" + taxonCount + ";"); out.println("\tTaxlabels"); for (String name : names) { if (name.matches(SPECIAL_CHARACTERS_REGEX)) { name = "'" + name + "'"; } out.println("\t\t" + name); } out.println("\t\t;"); out.println("End;"); out.println(""); out.println("Begin trees;"); // This is needed if the trees use numerical taxon labels out.println("\tTranslate"); Map<String, Integer> idMap = new HashMap<String, Integer>(); int k = 1; for (String name : names) { idMap.put(name, k); if (name.matches(SPECIAL_CHARACTERS_REGEX)) { name = "'" + name + "'"; } if (k < names.size()) { out.println("\t\t" + k + " " + name + ","); } else { out.println("\t\t" + k + " " + name); } k += 1; } return idMap; } private void writeNode(Tree tree, NodeRef node, boolean attributes, Map<String, Integer> idMap) { if (tree.isExternal(node)) { int k = node.getNumber() + 1; if (idMap != null) k = idMap.get(tree.getTaxonId(k - 1)); out.print(k); } else { out.print("("); writeNode(tree, tree.getChild(node, 0), attributes, idMap); for (int i = 1; i < tree.getChildCount(node); i++) { out.print(","); writeNode(tree, tree.getChild(node, i), attributes, idMap); } out.print(")"); } if (attributes) { Iterator iter = tree.getNodeAttributeNames(node); if (iter != null) { boolean first = true; while (iter.hasNext()) { if (first) { out.print("[&"); first = false; } else { out.print(","); } String name = (String) iter.next(); out.print(name + "="); Object value = tree.getNodeAttribute(node, name); printValue(value); } out.print("]"); } } if (!tree.isRoot(node)) { out.print(":"); double length = tree.getBranchLength(node); if (formatter != null) { out.print(formatter.format(length)); } else { out.print(length); } } } private void printValue(Object value) { if (value instanceof Object[]) { out.print("{"); Object[] values = (Object[]) value; for (int i = 0; i < values.length; i++) { if (i > 0) { out.print(","); } printValue(values[i]); } out.print("}"); } else if (value instanceof String) { out.print("\"" + value.toString() + "\""); } else { out.print(value.toString()); } } private final PrintStream out; private NumberFormat formatter = null; private String treePrefix = DEFAULT_TREE_PREFIX; private boolean sorted = false; }
package dr.app.tools; import dr.app.beast.BeastVersion; import dr.app.util.Arguments; import dr.evolution.io.Importer; import dr.evolution.io.NexusImporter; import dr.evolution.io.TreeImporter; import dr.evolution.tree.FlexibleTree; import dr.evolution.tree.MutableTree; import dr.evolution.tree.NodeRef; import dr.evolution.tree.Tree; import dr.evolution.util.TaxonList; import dr.stats.DiscreteStatistics; import dr.util.HeapSort; import dr.util.Version; import org.virion.jam.console.ConsoleApplication; import javax.swing.*; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.PrintStream; import java.util.*; public class TreeAnnotator { private final static Version version = new BeastVersion(); public final static int MAX_CLADE_CREDIBILITY = 0; public final static int MAX_SUM_CLADE_CREDIBILITY = 1; public final static int USER_TARGET_TREE = 2; public final static int KEEP_HEIGHTS = 0; public final static int MEAN_HEIGHTS = 1; public final static int MEDIAN_HEIGHTS = 2; public TreeAnnotator(int burnin, int heightsOption, double posteriorLimit, int targetOption, String targetTreeFileName, String inputFileName, String outputFileName) throws IOException { this.posteriorLimit = posteriorLimit; attributeNames.add("height"); attributeNames.add("length"); System.out.println("Reading trees..."); CladeSystem cladeSystem = new CladeSystem(); boolean firstTree = true; TreeImporter importer = new NexusImporter(new FileReader(inputFileName)); try { while (importer.hasTree()) { Tree tree = importer.importNextTree(); if (firstTree) { setupAttributes(tree); firstTree = false; } if (totalTrees >= burnin) { cladeSystem.add(tree); totalTreesUsed += 1; } totalTrees += 1; } } catch (Importer.ImportException e) { System.err.println("Error Parsing Input Tree: " + e.getMessage()); return; } cladeSystem.calculateCladeCredibilities(totalTreesUsed); System.out.println("Total trees read: " + totalTrees); if (burnin > 0) { System.out.println("Ignoring first " + burnin + " trees."); } MutableTree targetTree; if (targetOption == USER_TARGET_TREE) { if (targetTreeFileName != null) { System.out.println("Reading user specified target tree, " + targetTreeFileName); importer = new NexusImporter(new FileReader(targetTreeFileName)); try { targetTree = new FlexibleTree(importer.importNextTree()); } catch (Importer.ImportException e) { System.err.println("Error Parsing Target Tree: " + e.getMessage()); return; } } else { System.err.println("No user target tree specified."); return; } } else if (targetOption == MAX_CLADE_CREDIBILITY) { System.out.println("Finding maximum credibility tree..."); targetTree = new FlexibleTree(summarizeTrees(burnin, cladeSystem, inputFileName, false)); } else if (targetOption == MAX_SUM_CLADE_CREDIBILITY) { System.out.println("Finding maximum sum clade credibility tree..."); targetTree = new FlexibleTree(summarizeTrees(burnin, cladeSystem, inputFileName, true)); } else { throw new RuntimeException("Unknown target tree option"); } System.out.println("Annotating target tree..."); cladeSystem.annotateTree(targetTree, targetTree.getRoot(), null, heightsOption); System.out.println("Writing annotated tree...."); if (outputFileName != null) { NexusExporter exporter = new NexusExporter(new PrintStream(new FileOutputStream(outputFileName))); exporter.exportTree(targetTree); } else { NexusExporter exporter = new NexusExporter(System.out); exporter.exportTree(targetTree); } } private void setupAttributes(Tree tree) { for (int i = 0; i < tree.getNodeCount(); i++) { NodeRef node = tree.getNode(i); Iterator iter = tree.getNodeAttributeNames(node); while (iter.hasNext()) { String name = (String)iter.next(); attributeNames.add(name); Object value = tree.getNodeAttribute(node, name); } } } private Tree summarizeTrees(int burnin, CladeSystem cladeSystem, String inputFileName, boolean useSumCladeCredibility) throws IOException { Tree bestTree = null; double bestScore = Double.NEGATIVE_INFINITY; System.out.println("Analyzing " + totalTreesUsed + " trees..."); System.out.println("0 25 50 75 100"); System.out.println("| int stepSize = totalTrees / 60; if (stepSize < 1) stepSize = 1; int counter = 0; TreeImporter importer = new NexusImporter(new FileReader(inputFileName)); try { while (importer.hasTree()) { Tree tree = importer.importNextTree(); if (counter >= burnin) { double score = scoreTree(tree, cladeSystem, useSumCladeCredibility); // System.out.println(score); if (score > bestScore) { bestTree = tree; bestScore = score; } } if (counter > 0 && counter % stepSize == 0) { System.out.print("*"); System.out.flush(); } counter++; } } catch (Importer.ImportException e) { System.err.println("Error Parsing Input Tree: " + e.getMessage()); return null; } System.out.println(); System.out.println(); if (useSumCladeCredibility) { System.out.println("Highest Sum Clade Credibility: " + bestScore); } else { System.out.println("Highest Log Clade Credibility: " + bestScore); } return bestTree; } private double scoreTree(Tree tree, CladeSystem cladeSystem, boolean useSumCladeCredibility) { if (useSumCladeCredibility) { return cladeSystem.getSumCladeCredibility(tree, tree.getRoot(), null); } else { return cladeSystem.getLogCladeCredibility(tree, tree.getRoot(), null); } } private class CladeSystem { // Public stuff public CladeSystem() { } /** * adds all the clades in the tree */ public void add(Tree tree) { if (taxonList == null) { taxonList = tree; } // Recurse over the tree and add all the clades (or increment their // frequency if already present). The root clade is added too (for // annotation purposes). addClades(tree, tree.getRoot(), null); } public Map getCladeMap() { return cladeMap; } public Clade getClade(NodeRef node) { return null; } private void addClades(Tree tree, NodeRef node, BitSet bits) { BitSet bits2 = new BitSet(); if (tree.isExternal(node)) { int index = taxonList.getTaxonIndex(tree.getNodeTaxon(node).getId()); bits2.set(index); } else { for (int i = 0; i < tree.getChildCount(node); i++) { NodeRef node1 = tree.getChild(node, i); addClades(tree, node1, bits2); } } addClade(bits2, tree, node); if (bits != null) { bits.or(bits2); } } private void addClade(BitSet bits, Tree tree, NodeRef node) { Clade clade = (Clade) cladeMap.get(bits); if (clade == null) { clade = new Clade(bits); cladeMap.put(bits, clade); } clade.setCount(clade.getCount() + 1); if (attributeNames != null) { if (clade.attributeLists == null) { clade.attributeLists = new List[attributeNames.size()]; for (int i = 0; i < attributeNames.size(); i++) { clade.attributeLists[i] = new ArrayList(); } } for (int i = 0; i < attributeNames.size(); i++) { String attributeName = attributeNames.get(i); Object value; if (attributeName.equals("height")) { value = new Double(tree.getNodeHeight(node)); } else if (attributeName.equals("length")) { value = new Double(tree.getBranchLength(node)); } else { value = tree.getNodeAttribute(node, attributeName); } //if (value == null) { // System.out.println("attribute " + attributeNames[i] + " is null."); if (value != null) { clade.attributeLists[i].add(value); } } } } public void calculateCladeCredibilities(int totalTreesUsed) { Iterator iter = cladeMap.values().iterator(); while (iter.hasNext()) { Clade clade = (Clade) iter.next(); clade.setCredibility(((double) clade.getCount()) / totalTreesUsed); } } public double getSumCladeCredibility(Tree tree, NodeRef node, BitSet bits) { double sum = 0.0; if (tree.isExternal(node)) { int index = taxonList.getTaxonIndex(tree.getNodeTaxon(node).getId()); bits.set(index); } else { BitSet bits2 = new BitSet(); for (int i = 0; i < tree.getChildCount(node); i++) { NodeRef node1 = tree.getChild(node, i); sum += getSumCladeCredibility(tree, node1, bits2); } sum += getCladeCredibility(bits2); if (bits != null) { bits.or(bits2); } } return sum; } public double getLogCladeCredibility(Tree tree, NodeRef node, BitSet bits) { double logCladeCredibility = 0.0; if (tree.isExternal(node)) { int index = taxonList.getTaxonIndex(tree.getNodeTaxon(node).getId()); bits.set(index); } else { BitSet bits2 = new BitSet(); for (int i = 0; i < tree.getChildCount(node); i++) { NodeRef node1 = tree.getChild(node, i); logCladeCredibility += getLogCladeCredibility(tree, node1, bits2); } logCladeCredibility += Math.log(getCladeCredibility(bits2)); if (bits != null) { bits.or(bits2); } } return logCladeCredibility; } private double getCladeCredibility(BitSet bits) { Clade clade = (Clade) cladeMap.get(bits); if (clade == null) { return 0.0; } return clade.getCredibility(); } public void annotateTree(MutableTree tree, NodeRef node, BitSet bits, int heightsOption) { BitSet bits2 = new BitSet(); if (tree.isExternal(node)) { int index = taxonList.getTaxonIndex(tree.getNodeTaxon(node).getId()); bits2.set(index); annotateNode(tree, node, bits2, true, heightsOption); } else { for (int i = 0; i < tree.getChildCount(node); i++) { NodeRef node1 = tree.getChild(node, i); annotateTree(tree, node1, bits2, heightsOption); } annotateNode(tree, node, bits2, false, heightsOption); } if (bits != null) { bits.or(bits2); } } private void annotateNode(MutableTree tree, NodeRef node, BitSet bits, boolean isTip, int heightsOption) { Clade clade = (Clade) cladeMap.get(bits); if (clade == null) { throw new RuntimeException("Clade missing"); } boolean filter = false; if (!isTip) { double posterior = clade.getCredibility(); tree.setNodeAttribute(node, "posterior", new Double(posterior)); if (posterior < posteriorLimit) { filter = true; } } for (int i = 0; i < attributeNames.size(); i++) { String attributeName = attributeNames.get(i); double[] values = new double[clade.attributeLists[i].size()]; HashMap<String, Integer> hashMap = new HashMap<String, Integer>(); if (values.length > 0) { Object v = clade.attributeLists[i].get(0); boolean isHeight = attributeName.equals("height"); boolean isBoolean = v instanceof Boolean; boolean isDiscrete = v instanceof String; double minValue = Double.MAX_VALUE; double maxValue = -Double.MAX_VALUE; for (int j = 0; j < clade.attributeLists[i].size(); j++) { if (!isDiscrete) { values[j] = ((Number) clade.attributeLists[i].get(j)).doubleValue(); if (values[j] < minValue) minValue = values[j]; if (values[j] > maxValue) maxValue = values[j]; } else { String value = (String) clade.attributeLists[i].get(j); if (value.startsWith("\"")) { value = value.replaceAll("\"", ""); } if (hashMap.containsKey(value)) { int count = hashMap.get(value); hashMap.put(value, count + 1); } else { hashMap.put(value, 1); } } } if (isHeight) { if (heightsOption == MEAN_HEIGHTS) { double mean = DiscreteStatistics.mean(values); tree.setNodeHeight(node, mean); } else if (heightsOption == MEDIAN_HEIGHTS) { double median = DiscreteStatistics.median(values); tree.setNodeHeight(node, median); } else { // keep the existing height } } if (!filter) { if (!isDiscrete) annotateMeanAttribute(tree, node, attributeName, values); else annotateModeAttribute(tree, node, attributeName, hashMap); if (!isBoolean && minValue < maxValue && !isDiscrete) { // Basically, if it is a boolean (0, 1) then we don't need the distribution information // Likewise if it doesn't vary. annotateMedianAttribute(tree, node, attributeName + "_median", values); annotateHPDAttribute(tree, node, attributeName + "_95%_HPD", 0.95, values); annotateRangeAttribute(tree, node, attributeName + "_range", values); } } } } } private void annotateMeanAttribute(MutableTree tree, NodeRef node, String label, double[] values) { double mean = DiscreteStatistics.mean(values); tree.setNodeAttribute(node, label, new Double(mean)); } private void annotateMedianAttribute(MutableTree tree, NodeRef node, String label, double[] values) { double median = DiscreteStatistics.median(values); tree.setNodeAttribute(node, label, new Double(median)); } private void annotateModeAttribute(MutableTree tree, NodeRef node, String label, HashMap<String, Integer> values) { String mode = null; int maxCount = 0; int totalCount = 0; for (String key : values.keySet()) { int thisCount = values.get(key); if (thisCount == maxCount) mode.concat("+" + key); else if (thisCount > maxCount) { mode = key; maxCount = thisCount; } totalCount += thisCount; } double freq = (double) maxCount / (double) totalCount; tree.setNodeAttribute(node, label, mode); tree.setNodeAttribute(node, label + ".prob", new Double(freq)); } private void annotateRangeAttribute(MutableTree tree, NodeRef node, String label, double[] values) { double min = DiscreteStatistics.min(values); double max = DiscreteStatistics.max(values); tree.setNodeAttribute(node, label, new Object[]{new Double(min), new Double(max)}); } private void annotateHPDAttribute(MutableTree tree, NodeRef node, String label, double hpd, double[] values) { int[] indices = new int[values.length]; HeapSort.sort(values, indices); double minRange = Double.MAX_VALUE; int hpdIndex = 0; int diff = (int) Math.round(hpd * (double) values.length); for (int i = 0; i <= (values.length - diff); i++) { double minValue = values[indices[i]]; double maxValue = values[indices[i + diff - 1]]; double range = Math.abs(maxValue - minValue); if (range < minRange) { minRange = range; hpdIndex = i; } } double lower = values[indices[hpdIndex]]; double upper = values[indices[hpdIndex + diff - 1]]; tree.setNodeAttribute(node, label, new Object[]{new Double(lower), new Double(upper)}); } class Clade { public Clade(BitSet bits) { this.bits = bits; count = 0; credibility = 0.0; } public int getCount() { return count; } public void setCount(int count) { this.count = count; } public double getCredibility() { return credibility; } public void setCredibility(double credibility) { this.credibility = credibility; } public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final Clade clade = (Clade) o; if (bits != null ? !bits.equals(clade.bits) : clade.bits != null) return false; return true; } public int hashCode() { return (bits != null ? bits.hashCode() : 0); } int count; double credibility; BitSet bits; List[] attributeLists = null; } // Private stuff TaxonList taxonList = null; Map cladeMap = new HashMap(); } int totalTrees = 0; int totalTreesUsed = 0; double posteriorLimit = 0.0; List<String> attributeNames = new ArrayList<String>(); TaxonList taxa = null; public static void printTitle() { System.out.println(); centreLine("TreeAnnotator " + version.getVersionString() + ", " + version.getDateString(), 60); centreLine("MCMC Output analysis", 60); centreLine("by", 60); centreLine("Andrew Rambaut and Alexei J. Drummond", 60); System.out.println(); centreLine("Institute of Evolutionary Biology", 60); centreLine("University of Edinburgh", 60); centreLine("a.rambaut@ed.ac.uk", 60); System.out.println(); centreLine("Department of Computer Science", 60); centreLine("University of Auckland", 60); centreLine("alexei@cs.auckland.ac.nz", 60); System.out.println(); System.out.println(); } public static void centreLine(String line, int pageWidth) { int n = pageWidth - line.length(); int n1 = n / 2; for (int i = 0; i < n1; i++) { System.out.print(" "); } System.out.println(line); } public static void printUsage(Arguments arguments) { arguments.printUsage("treeannotator", "[-burnin <burnin>] [-heights <height_option>] [-limit <posterior_limit>] [-target <target-tree-file-name>] <input-file-name> [<output-file-name>]"); System.out.println(); System.out.println(" Example: treeannotator test.trees out.txt"); System.out.println(" Example: treeannotator -burnin 100 -heights mean test.trees out.txt"); System.out.println(" Example: treeannotator -burnin 100 -target map.tree test.trees out.txt"); System.out.println(); } //Main method public static void main(String[] args) throws IOException { String targetTreeFileName = null; String inputFileName = null; String outputFileName = null; if (args.length == 0) { System.setProperty("com.apple.macos.useScreenMenuBar", "true"); System.setProperty("apple.laf.useScreenMenuBar", "true"); System.setProperty("apple.awt.showGrowBox", "true"); java.net.URL url = LogCombiner.class.getResource("/images/utility.png"); javax.swing.Icon icon = null; if (url != null) { icon = new javax.swing.ImageIcon(url); } final String versionString = version.getVersionString(); String nameString = "TreeAnnotator " + versionString; String aboutString = "<html><center><p>" + versionString + ", " + version.getDateString() + "</p>" + "<p>by<br>" + "Andrew Rambaut and Alexei J. Drummond</p>" + "<p>Institute of Evolutionary Biology, University of Edinburgh<br>" + "<a href=\"mailto:a.rambaut@ed.ac.uk\">a.rambaut@ed.ac.uk</a></p>" + "<p>Department of Computer Science, University of Auckland<br>" + "<a href=\"mailto:alexei@cs.auckland.ac.nz\">alexei@cs.auckland.ac.nz</a></p>" + "<p>Part of the BEAST package:<br>" + "<a href=\"http: "</center></html>"; ConsoleApplication consoleApp = new ConsoleApplication(nameString, aboutString, icon, true); printTitle(); TreeAnnotatorDialog dialog = new TreeAnnotatorDialog(new JFrame()); if (!dialog.showDialog("TreeAnnotator " + versionString)) { return; } int burnin = dialog.getBurnin(); double posteriorLimit = dialog.getPosteriorLimit(); int targetOption = dialog.getTargetOption(); int heightsOption = dialog.getHeightsOption(); targetTreeFileName = dialog.getTargetFileName(); if (targetOption == USER_TARGET_TREE && targetTreeFileName == null) { System.err.println("No target file specified"); return; } inputFileName = dialog.getInputFileName(); if (inputFileName == null) { System.err.println("No input file specified"); return; } outputFileName = dialog.getOutputFileName(); if (outputFileName == null) { System.err.println("No output file specified"); return; } try { new TreeAnnotator(burnin, heightsOption, posteriorLimit, targetOption, targetTreeFileName, inputFileName, outputFileName); } catch (Exception ex) { System.err.println("Exception: " + ex.getMessage()); } System.out.println("Finished - Quit program to exit."); while (true) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } printTitle(); Arguments arguments = new Arguments( new Arguments.Option[]{ //new Arguments.StringOption("target", new String[] { "maxclade", "maxtree" }, false, "an option of 'maxclade' or 'maxtree'"), new Arguments.StringOption("heights", new String[]{"keep", "median", "mean"}, false, "an option of 'keep', 'median' or 'mean'"), new Arguments.IntegerOption("burnin", "the number of states to be considered as 'burn-in'"), new Arguments.RealOption("limit", "the minimum posterior probability for a node to be annoated"), new Arguments.StringOption("target", "target_file_name", "specifies a user target tree to be annotated"), new Arguments.Option("help", "option to print this message") }); try { arguments.parseArguments(args); } catch (Arguments.ArgumentException ae) { System.out.println(ae); printUsage(arguments); System.exit(1); } if (arguments.hasOption("help")) { printUsage(arguments); System.exit(0); } int heights = KEEP_HEIGHTS; if (arguments.hasOption("heights")) { String value = arguments.getStringOption("heights"); if (value.equalsIgnoreCase("mean")) { heights = MEAN_HEIGHTS; } else if (value.equalsIgnoreCase("median")) { heights = MEDIAN_HEIGHTS; } } int burnin = -1; if (arguments.hasOption("burnin")) { burnin = arguments.getIntegerOption("burnin"); } double posteriorLimit = 0.0; if (arguments.hasOption("limit")) { posteriorLimit = arguments.getRealOption("limit"); } int target = MAX_CLADE_CREDIBILITY; if (arguments.hasOption("target")) { target = USER_TARGET_TREE; targetTreeFileName = arguments.getStringOption("target"); } String[] args2 = arguments.getLeftoverArguments(); if (args2.length > 2) { System.err.println("Unknown option: " + args2[2]); System.err.println(); printUsage(arguments); System.exit(1); } if (args2.length == 2) { targetTreeFileName = null; inputFileName = args2[0]; outputFileName = args2[1]; } else { printUsage(arguments); System.exit(1); } new TreeAnnotator(burnin, heights, posteriorLimit, target, targetTreeFileName, inputFileName, outputFileName); System.exit(0); } }
package dr.app.tools; import dr.app.beast.BeastVersion; import dr.app.util.Arguments; import dr.evolution.io.Importer; import dr.evolution.io.NexusImporter; import dr.evolution.io.TreeImporter; import dr.evolution.io.NewickImporter; import dr.evolution.tree.FlexibleTree; import dr.evolution.tree.MutableTree; import dr.evolution.tree.NodeRef; import dr.evolution.tree.Tree; import dr.evolution.util.TaxonList; import dr.stats.DiscreteStatistics; import dr.util.HeapSort; import dr.util.Version; import dr.geo.KernelDensityEstimator2D; import dr.geo.contouring.ContourAttrib; import dr.geo.contouring.ContourGenerator; import dr.geo.contouring.ContourPath; import org.rosuda.JRI.REXP; import org.rosuda.JRI.RVector; import org.rosuda.JRI.Rengine; import org.virion.jam.console.ConsoleApplication; import javax.swing.*; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.PrintStream; import java.util.*; public class TreeAnnotator { private final static Version version = new BeastVersion(); private final static boolean USE_R = true; private final static String HPD_2D_STRING = "80"; private final static double HPD_2D = 0.80; enum Target { MAX_CLADE_CREDIBILITY( "Maximum clade credibility tree"), MAX_SUM_CLADE_CREDIBILITY("Maximum sum of clade credibilities"), USER_TARGET_TREE("User target tree"); String desc; Target(String s) { desc = s; } public String toString() { return desc; } } enum HeightsSummary { KEEP_HEIGHTS("Keep target heights"), MEAN_HEIGHTS("Mean heights"), MEDIAN_HEIGHTS("Median heights"); String desc; HeightsSummary(String s) { desc = s; } public String toString() { return desc; } } // Messages to stderr, output to stdout private static final PrintStream progressStream = System.err; private final String location1Attribute = "longLat1"; private final String location2Attribute = "longLat2"; private final String locationOutputAttribute = "location"; public TreeAnnotator(final int burnin, HeightsSummary heightsOption, double posteriorLimit, Target targetOption, String targetTreeFileName, String inputFileName, String outputFileName ) throws IOException { this.posteriorLimit = posteriorLimit; attributeNames.add("height"); attributeNames.add("length"); CladeSystem cladeSystem = new CladeSystem(); totalTrees = 10000; totalTreesUsed = 0; progressStream.println("Reading trees (bar assumes 10,000 trees)..."); progressStream.println("0 25 50 75 100"); progressStream.println("| int stepSize = totalTrees / 60; if (stepSize < 1) stepSize = 1; if (targetOption != Target.USER_TARGET_TREE) { cladeSystem = new CladeSystem(); FileReader fileReader = new FileReader(inputFileName); TreeImporter importer = new NexusImporter(fileReader); try { totalTrees = 0; while (importer.hasTree()) { Tree tree = importer.importNextTree(); if (totalTrees >= burnin) { cladeSystem.add(tree, false); totalTreesUsed += 1; } if (totalTrees > 0 && totalTrees % stepSize == 0) { progressStream.print("*"); progressStream.flush(); } totalTrees++; } } catch (Importer.ImportException e) { System.err.println("Error Parsing Input Tree: " + e.getMessage()); return; } fileReader.close(); progressStream.println(); progressStream.println(); if( totalTrees < 1 ) { System.err.println("No trees"); return; } if( totalTreesUsed <= 1 ) { if( burnin > 0 ) { System.err.println("No trees to use: burnin too high"); return; } } cladeSystem.calculateCladeCredibilities(totalTreesUsed); progressStream.println("Total trees read: " + totalTrees); if (burnin > 0) { progressStream.println("Ignoring first " + burnin + " trees."); } progressStream.println("Total unique clades: " + cladeSystem.getCladeMap().keySet().size()); progressStream.println(); } MutableTree targetTree = null; switch( targetOption ) { case USER_TARGET_TREE: { if (targetTreeFileName != null) { progressStream.println("Reading user specified target tree, " + targetTreeFileName); NexusImporter importer = new NexusImporter(new FileReader(targetTreeFileName)); try { Tree tree = importer.importNextTree(); if( tree == null ) { NewickImporter x = new NewickImporter(new FileReader(targetTreeFileName)); tree = x.importNextTree(); } if( tree == null ) { System.err.println("No tree in target nexus or newick file " + targetTreeFileName); return; } targetTree = new FlexibleTree(tree); } catch (Importer.ImportException e) { System.err.println("Error Parsing Target Tree: " + e.getMessage()); return; } } else { System.err.println("No user target tree specified."); return; } break; } case MAX_CLADE_CREDIBILITY: { progressStream.println("Finding maximum credibility tree..."); targetTree = new FlexibleTree(summarizeTrees(burnin, cladeSystem, inputFileName, false)); break; } case MAX_SUM_CLADE_CREDIBILITY: { progressStream.println("Finding maximum sum clade credibility tree..."); targetTree = new FlexibleTree(summarizeTrees(burnin, cladeSystem, inputFileName, true)); break; } } progressStream.println("Collecting node information..."); progressStream.println("0 25 50 75 100"); progressStream.println("| stepSize = totalTrees / 60; if (stepSize < 1) stepSize = 1; FileReader fileReader = new FileReader(inputFileName); NexusImporter importer = new NexusImporter(fileReader); // this call increments the clade counts and it shouldn't // this is remedied with removeClades call after while loop below cladeSystem = new CladeSystem(targetTree); totalTreesUsed = 0; try { boolean firstTree = true; int counter = 0; while (importer.hasTree()) { Tree tree = importer.importNextTree(); if (counter >= burnin) { if (firstTree) { setupAttributes(tree); firstTree = false; } cladeSystem.collectAttributes(tree); totalTreesUsed += 1; } if (counter > 0 && counter % stepSize == 0) { progressStream.print("*"); progressStream.flush(); } counter++; } cladeSystem.removeClades(targetTree, targetTree.getRoot(), true); //progressStream.println("totalTreesUsed=" + totalTreesUsed); cladeSystem.calculateCladeCredibilities(totalTreesUsed); } catch (Importer.ImportException e) { System.err.println("Error Parsing Input Tree: " + e.getMessage()); return; } progressStream.println(); progressStream.println(); fileReader.close(); progressStream.println("Annotating target tree..."); cladeSystem.annotateTree(targetTree, targetTree.getRoot(), null, heightsOption); progressStream.println("Writing annotated tree...."); final PrintStream stream = outputFileName != null ? new PrintStream(new FileOutputStream(outputFileName)) : System.out; new NexusExporter(stream).exportTree(targetTree); } private void setupAttributes(Tree tree) { for (int i = 0; i < tree.getNodeCount(); i++) { NodeRef node = tree.getNode(i); Iterator iter = tree.getNodeAttributeNames(node); if (iter != null) { while (iter.hasNext()) { String name = (String) iter.next(); attributeNames.add(name); } } } } private Tree summarizeTrees(int burnin, CladeSystem cladeSystem, String inputFileName, boolean useSumCladeCredibility) throws IOException { Tree bestTree = null; double bestScore = Double.NEGATIVE_INFINITY; progressStream.println("Analyzing " + totalTreesUsed + " trees..."); progressStream.println("0 25 50 75 100"); progressStream.println("| int stepSize = totalTrees / 60; if (stepSize < 1) stepSize = 1; int counter = 0; TreeImporter importer = new NexusImporter(new FileReader(inputFileName)); try { while (importer.hasTree()) { Tree tree = importer.importNextTree(); if (counter >= burnin) { double score = scoreTree(tree, cladeSystem, useSumCladeCredibility); // progressStream.println(score); if (score > bestScore) { bestTree = tree; bestScore = score; } } if (counter > 0 && counter % stepSize == 0) { progressStream.print("*"); progressStream.flush(); } counter++; } } catch (Importer.ImportException e) { System.err.println("Error Parsing Input Tree: " + e.getMessage()); return null; } progressStream.println(); progressStream.println(); if (useSumCladeCredibility) { progressStream.println("Highest Sum Clade Credibility: " + bestScore); } else { progressStream.println("Highest Log Clade Credibility: " + bestScore); } return bestTree; } private double scoreTree(Tree tree, CladeSystem cladeSystem, boolean useSumCladeCredibility) { if (useSumCladeCredibility) { return cladeSystem.getSumCladeCredibility(tree, tree.getRoot(), null); } else { return cladeSystem.getLogCladeCredibility(tree, tree.getRoot(), null); } } private class CladeSystem { // Public stuff public CladeSystem() {} public CladeSystem(Tree targetTree) { this.targetTree = targetTree; add(targetTree, true); } /** * adds all the clades in the tree */ public void add(Tree tree, boolean includeTips) { if (taxonList == null) { taxonList = tree; } // Recurse over the tree and add all the clades (or increment their // frequency if already present). The root clade is added too (for // annotation purposes). addClades(tree, tree.getRoot(), includeTips); } // public Clade getClade(NodeRef node) { // return null; private BitSet addClades(Tree tree, NodeRef node, boolean includeTips) { BitSet bits = new BitSet(); if (tree.isExternal(node)) { int index = taxonList.getTaxonIndex(tree.getNodeTaxon(node).getId()); bits.set(index); if (includeTips) { addClade(bits); } } else { for (int i = 0; i < tree.getChildCount(node); i++) { NodeRef node1 = tree.getChild(node, i); bits.or(addClades(tree, node1, includeTips)); } addClade(bits); } return bits; } private void addClade(BitSet bits) { Clade clade = cladeMap.get(bits); if (clade == null) { clade = new Clade(bits); cladeMap.put(bits, clade); } clade.setCount(clade.getCount() + 1); } public void collectAttributes(Tree tree) { collectAttributes(tree, tree.getRoot()); } private BitSet collectAttributes(Tree tree, NodeRef node) { BitSet bits = new BitSet(); if (tree.isExternal(node)) { int index = taxonList.getTaxonIndex(tree.getNodeTaxon(node).getId()); if (index < 0) { throw new IllegalArgumentException("Taxon, " + tree.getNodeTaxon(node).getId() + ", not found in target tree"); } bits.set(index); } else { for (int i = 0; i < tree.getChildCount(node); i++) { NodeRef node1 = tree.getChild(node, i); bits.or(collectAttributes(tree, node1)); } } collectAttributesForClade(bits, tree, node); return bits; } private void collectAttributesForClade(BitSet bits, Tree tree, NodeRef node) { Clade clade = cladeMap.get(bits); if (clade != null) { if (clade.attributeValues == null) { clade.attributeValues = new ArrayList<Object[]>(); } int i = 0; Object[] values = new Object[attributeNames.size()]; for (String attributeName : attributeNames) { Object value; if (attributeName.equals("height")) { value = tree.getNodeHeight(node); } else if (attributeName.equals("length")) { value = tree.getBranchLength(node); } else if (attributeName.equals(location1Attribute)) { // If this is one of the two specified bivariate location names then // merge this and the other one into a single array. Object value1 = tree.getNodeAttribute(node, attributeName); Object value2 = tree.getNodeAttribute(node, location2Attribute); value = new Object[] { value1, value2 }; } else if (attributeName.equals(location2Attribute)) { // do nothing - already dealt with this... value = null; } else { value = tree.getNodeAttribute(node, attributeName); if (value instanceof String && ((String) value).startsWith("\"")) { value = ((String) value).replaceAll("\"", ""); } } //if (value == null) { // progressStream.println("attribute " + attributeNames[i] + " is null."); values[i] = value; i++; } clade.attributeValues.add(values); //progressStream.println(clade + " " + clade.getCount()); clade.setCount(clade.getCount() + 1); } } public Map getCladeMap() { return cladeMap; } public void calculateCladeCredibilities(int totalTreesUsed) { for (Clade clade : cladeMap.values()) { if (clade.getCount() > totalTreesUsed) { throw new AssertionError("clade.getCount=(" + clade.getCount() + ") should be <= totalTreesUsed = (" + totalTreesUsed + ")"); } clade.setCredibility(((double) clade.getCount()) / (double) totalTreesUsed); } } public double getSumCladeCredibility(Tree tree, NodeRef node, BitSet bits) { double sum = 0.0; if (tree.isExternal(node)) { int index = taxonList.getTaxonIndex(tree.getNodeTaxon(node).getId()); bits.set(index); } else { BitSet bits2 = new BitSet(); for (int i = 0; i < tree.getChildCount(node); i++) { NodeRef node1 = tree.getChild(node, i); sum += getSumCladeCredibility(tree, node1, bits2); } sum += getCladeCredibility(bits2); if (bits != null) { bits.or(bits2); } } return sum; } public double getLogCladeCredibility(Tree tree, NodeRef node, BitSet bits) { double logCladeCredibility = 0.0; if (tree.isExternal(node)) { int index = taxonList.getTaxonIndex(tree.getNodeTaxon(node).getId()); bits.set(index); } else { BitSet bits2 = new BitSet(); for (int i = 0; i < tree.getChildCount(node); i++) { NodeRef node1 = tree.getChild(node, i); logCladeCredibility += getLogCladeCredibility(tree, node1, bits2); } logCladeCredibility += Math.log(getCladeCredibility(bits2)); if (bits != null) { bits.or(bits2); } } return logCladeCredibility; } private double getCladeCredibility(BitSet bits) { Clade clade = cladeMap.get(bits); if (clade == null) { return 0.0; } return clade.getCredibility(); } public void annotateTree(MutableTree tree, NodeRef node, BitSet bits, HeightsSummary heightsOption) { BitSet bits2 = new BitSet(); if (tree.isExternal(node)) { int index = taxonList.getTaxonIndex(tree.getNodeTaxon(node).getId()); bits2.set(index); annotateNode(tree, node, bits2, true, heightsOption); } else { for (int i = 0; i < tree.getChildCount(node); i++) { NodeRef node1 = tree.getChild(node, i); annotateTree(tree, node1, bits2, heightsOption); } annotateNode(tree, node, bits2, false, heightsOption); } if (bits != null) { bits.or(bits2); } } private void annotateNode(MutableTree tree, NodeRef node, BitSet bits, boolean isTip, HeightsSummary heightsOption) { Clade clade = cladeMap.get(bits); assert clade != null : "Clade missing?"; boolean filter = false; if (!isTip) { final double posterior = clade.getCredibility(); tree.setNodeAttribute(node, "posterior", posterior); if (posterior < posteriorLimit) { filter = true; } } int i = 0; for (String attributeName : attributeNames) { if (clade.attributeValues != null && clade.attributeValues.size() > 0) { double[] values = new double[clade.attributeValues.size()]; HashMap<String, Integer> hashMap = new HashMap<String, Integer>(); Object[] v = clade.attributeValues.get(0); if (v[i] != null) { final boolean isHeight = attributeName.equals("height"); boolean isBoolean = v[i] instanceof Boolean; boolean isDiscrete = v[i] instanceof String; double minValue = Double.MAX_VALUE; double maxValue = -Double.MAX_VALUE; final boolean isArray = v[i] instanceof Object[]; boolean isDoubleArray = isArray && ((Object[]) v[i])[0] instanceof Double; // This is Java, friends - first value type does not imply all. if (isDoubleArray) { for(Object n : (Object[])v[i]) { if( ! (n instanceof Double) ) { isDoubleArray = false; break; } } } // todo Handle other types of arrays double[][] valuesArray = null; double[] minValueArray = null; double[] maxValueArray = null; int lenArray = 0; if (isDoubleArray) { lenArray = ((Object[]) v[i]).length; valuesArray = new double[lenArray][clade.attributeValues.size()]; minValueArray = new double[lenArray]; maxValueArray = new double[lenArray]; for (int k = 0; k < lenArray; k++) { minValueArray[k] = Double.MAX_VALUE; maxValueArray[k] = -Double.MAX_VALUE; } } for (int j = 0; j < clade.attributeValues.size(); j++) { Object value = clade.attributeValues.get(j)[i]; if (isDiscrete) { final String s = (String) value; if (hashMap.containsKey(s)) { hashMap.put(s, hashMap.get(s) + 1); } else { hashMap.put(s, 1); } } else if (isBoolean) { values[j] = (((Boolean) value) ? 1.0 : 0.0); } else if (isDoubleArray) { // Forcing to Double[] causes a cast exception. MAS Object[] array = (Object[]) value; for (int k = 0; k < lenArray; k++) { valuesArray[k][j] = ((Double) array[k]); if (valuesArray[k][j] < minValueArray[k]) minValueArray[k] = valuesArray[k][j]; if (valuesArray[k][j] > maxValueArray[k]) maxValueArray[k] = valuesArray[k][j]; } } else { // Ignore other (unknown) types if ( value instanceof Number ) { values[j] = ((Number) value).doubleValue(); if (values[j] < minValue) minValue = values[j]; if (values[j] > maxValue) maxValue = values[j]; } } } if (isHeight) { if (heightsOption == HeightsSummary.MEAN_HEIGHTS) { final double mean = DiscreteStatistics.mean(values); tree.setNodeHeight(node, mean); } else if (heightsOption == HeightsSummary.MEDIAN_HEIGHTS) { final double median = DiscreteStatistics.median(values); tree.setNodeHeight(node, median); } else { // keep the existing height } } if (!filter) { if (!isDiscrete) { if (!isDoubleArray) annotateMeanAttribute(tree, node, attributeName, values); else { for (int k = 0; k < lenArray; k++) { annotateMeanAttribute(tree, node, attributeName + (k + 1), valuesArray[k]); } } } else { annotateModeAttribute(tree, node, attributeName, hashMap); annotateFrequencyAttribute(tree, node, attributeName, hashMap); } if (!isBoolean && minValue < maxValue && !isDiscrete && !isDoubleArray) { // Basically, if it is a boolean (0, 1) then we don't need the distribution information // Likewise if it doesn't vary. annotateMedianAttribute(tree, node, attributeName + "_median", values); annotateHPDAttribute(tree, node, attributeName + "_95%_HPD", 0.95, values); annotateRangeAttribute(tree, node, attributeName + "_range", values); } if (isDoubleArray) { String name = attributeName; if (name.equals(location1Attribute)) { name = locationOutputAttribute; } for (int k = 0; k < lenArray; k++) { if (minValueArray[k] < maxValueArray[k]) { annotateMedianAttribute(tree, node, name + (k + 1) + "_median", valuesArray[k]); annotateRangeAttribute(tree, node, name + (k + 1) + "_range", valuesArray[k]); if (!processBivariateAttributes || lenArray != 2) annotateHPDAttribute(tree, node, name + (k + 1) + "_95%_HPD", 0.95, valuesArray[k]); } } // 2D contours if (processBivariateAttributes && lenArray == 2) { boolean variationInFirst = (minValueArray[0] < maxValueArray[0]); boolean variationInSecond = (minValueArray[1] < maxValueArray[1]); if (variationInFirst && !variationInSecond) annotateHPDAttribute(tree, node, name + "1" + "_95%_HPD", 0.95, valuesArray[0]); if (variationInSecond && !variationInFirst) annotateHPDAttribute(tree, node, name + "2" + "_95%_HPD", 0.95, valuesArray[1]); if (variationInFirst && variationInSecond) annotate2DHPDAttribute(tree, node, name, "_"+HPD_2D_STRING+"%HPD", HPD_2D, valuesArray); } } } } } i++; } } private void annotateMeanAttribute(MutableTree tree, NodeRef node, String label, double[] values) { double mean = DiscreteStatistics.mean(values); tree.setNodeAttribute(node, label, mean); } private void annotateMedianAttribute(MutableTree tree, NodeRef node, String label, double[] values) { double median = DiscreteStatistics.median(values); tree.setNodeAttribute(node, label, median); } private void annotateModeAttribute(MutableTree tree, NodeRef node, String label, HashMap<String, Integer> values) { String mode = null; int maxCount = 0; int totalCount = 0; int countInMode = 1; for (String key : values.keySet()) { int thisCount = values.get(key); if (thisCount == maxCount) { // I hope this is the intention mode = mode.concat("+" + key); countInMode++; } else if (thisCount > maxCount) { mode = key; maxCount = thisCount; countInMode = 1; } totalCount += thisCount; } double freq = (double) maxCount / (double) totalCount * countInMode; tree.setNodeAttribute(node, label, mode); tree.setNodeAttribute(node, label + ".prob", freq); } private void annotateFrequencyAttribute(MutableTree tree, NodeRef node, String label, HashMap<String, Integer> values) { double totalCount = 0; Set keySet = values.keySet(); int length = keySet.size(); String[] name = new String[length]; Double[] freq = new Double[length]; int index = 0; for (String key : values.keySet()) { name[index] = key; freq[index] = new Double(values.get(key)); totalCount += freq[index]; index++; } for (int i=0; i<length; i++) freq[i] /= totalCount; tree.setNodeAttribute(node, label + ".set", name); tree.setNodeAttribute(node, label + ".set.prob", freq); } private void annotateRangeAttribute(MutableTree tree, NodeRef node, String label, double[] values) { double min = DiscreteStatistics.min(values); double max = DiscreteStatistics.max(values); tree.setNodeAttribute(node, label, new Object[]{min, max}); } private void annotateHPDAttribute(MutableTree tree, NodeRef node, String label, double hpd, double[] values) { int[] indices = new int[values.length]; HeapSort.sort(values, indices); double minRange = Double.MAX_VALUE; int hpdIndex = 0; int diff = (int) Math.round(hpd * (double) values.length); for (int i = 0; i <= (values.length - diff); i++) { double minValue = values[indices[i]]; double maxValue = values[indices[i + diff - 1]]; double range = Math.abs(maxValue - minValue); if (range < minRange) { minRange = range; hpdIndex = i; } } double lower = values[indices[hpdIndex]]; double upper = values[indices[hpdIndex + diff - 1]]; tree.setNodeAttribute(node, label, new Object[]{lower, upper}); } // todo Move rEngine to outer class; create once. Rengine rEngine = null; private final String[] rArgs = {"--no-save"}; // private int called = 0; private final String[] rBootCommands = { "library(MASS)", "makeContour = function(var1, var2, prob=0.95, n=50, h=c(1,1)) {" + "post1 = kde2d(var1, var2, n = n, h=h); " + // This had h=h in argument "dx = diff(post1$x[1:2]); " + "dy = diff(post1$y[1:2]); " + "sz = sort(post1$z); " + "c1 = cumsum(sz) * dx * dy; " + "levels = sapply(prob, function(x) { approx(c1, sz, xout = 1 - x)$y }); " + "line = contourLines(post1$x, post1$y, post1$z, level = levels); " + "return(line) }" }; private String makeRString(double[] values) { StringBuffer sb = new StringBuffer("c("); sb.append(values[0]); for (int i = 1; i < values.length; i++) { sb.append(","); sb.append(values[i]); } sb.append(")"); return sb.toString(); } public static final String CORDINATE = "cordinates"; // private String formattedLocation(double loc1, double loc2) { // return formattedLocation(loc1) + "," + formattedLocation(loc2); private String formattedLocation(double x) { return String.format("%5.2f", x); } private void annotate2DHPDAttribute(MutableTree tree, NodeRef node, String preLabel, String postLabel, double hpd, double[][] values) { // Uses R-Java interface, and the HPD routines from 'emdbook' and 'coda' if (rEngine == null) { if (!Rengine.versionCheck()) { throw new RuntimeException("JRI library version mismatch"); } rEngine = new Rengine(rArgs, false, null); if (!rEngine.waitForR()) { throw new RuntimeException("Cannot load R"); } for (String command : rBootCommands) { rEngine.eval(command); } } // todo Need a good method to pick grid size int N = 50; if (USE_R) { REXP x = rEngine.eval("makeContour(" + makeRString(values[0]) + "," + makeRString(values[1]) + "," + hpd + "," + N + ")"); RVector contourList = x.asVector(); int numberContours = contourList.size(); if (numberContours > 1) { System.err.println("Warning: a node has a disjoint "+100*hpd+"% HPD region. This may be an artifact!"); System.err.println("Try decreasing the enclosed mass or increasing the number of samples."); } tree.setNodeAttribute(node, preLabel + postLabel + "_modality", numberContours); StringBuffer output = new StringBuffer(); for (int i = 0; i < numberContours; i++) { output.append("\n<" + CORDINATE + ">\n"); RVector oneContour = contourList.at(i).asVector(); double[] xList = oneContour.at(1).asDoubleArray(); double[] yList = oneContour.at(2).asDoubleArray(); StringBuffer xString = new StringBuffer("{"); StringBuffer yString = new StringBuffer("{"); for (int k = 0; k < xList.length; k++) { xString.append(formattedLocation(xList[k])).append(","); yString.append(formattedLocation(yList[k])).append(","); } xString.append(formattedLocation(xList[0])).append("}"); yString.append(formattedLocation(yList[0])).append("}"); tree.setNodeAttribute(node, preLabel + "1" + postLabel + "_" + (i + 1), xString); tree.setNodeAttribute(node, preLabel + "2" + postLabel + "_" + (i + 1), yString); } } else { // do not use R KernelDensityEstimator2D kde = new KernelDensityEstimator2D(values[0], values[1], N); double thresholdDensity = kde.findLevelCorrespondingToMass(hpd); ContourGenerator contour = new ContourGenerator(kde.getXGrid(), kde.getYGrid(), kde.getKDE(), new ContourAttrib[]{new ContourAttrib(thresholdDensity)}); ContourPath[] paths = null; try { paths = contour.getContours(); } catch (InterruptedException e) { e.printStackTrace(); } tree.setNodeAttribute(node, preLabel + postLabel + "_modality", paths.length); if (paths.length > 1) { System.err.println("Warning: a node has a disjoint "+100*hpd+"% HPD region. This may be an artifact!"); System.err.println("Try decreasing the enclosed mass or increasing the number of samples."); } StringBuffer output = new StringBuffer(); int i=0; for (ContourPath p : paths) { output.append("\n<" + CORDINATE + ">\n"); double[] xList = p.getAllX(); double[] yList = p.getAllY(); StringBuffer xString = new StringBuffer("{"); StringBuffer yString = new StringBuffer("{"); for (int k = 0; k < xList.length; k++) { xString.append(formattedLocation(xList[k])).append(","); yString.append(formattedLocation(yList[k])).append(","); } xString.append(formattedLocation(xList[0])).append("}"); yString.append(formattedLocation(yList[0])).append("}"); tree.setNodeAttribute(node, preLabel + "1" + postLabel + "_" + (i + 1), xString); tree.setNodeAttribute(node, preLabel + "2" + postLabel + "_" + (i + 1), yString); i++; } } } public BitSet removeClades(Tree tree, NodeRef node, boolean includeTips) { BitSet bits = new BitSet(); if (tree.isExternal(node)) { int index = taxonList.getTaxonIndex(tree.getNodeTaxon(node).getId()); bits.set(index); if (includeTips) { removeClade(bits); } } else { for (int i = 0; i < tree.getChildCount(node); i++) { NodeRef node1 = tree.getChild(node, i); bits.or(removeClades(tree, node1, includeTips)); } removeClade(bits); } return bits; } private void removeClade(BitSet bits) { Clade clade = cladeMap.get(bits); if (clade != null) { clade.setCount(clade.getCount() - 1); } } class Clade { public Clade(BitSet bits) { this.bits = bits; count = 0; credibility = 0.0; } public int getCount() { return count; } public void setCount(int count) { this.count = count; } public double getCredibility() { return credibility; } public void setCredibility(double credibility) { this.credibility = credibility; } public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final Clade clade = (Clade) o; return !(bits != null ? !bits.equals(clade.bits) : clade.bits != null); } public int hashCode() { return (bits != null ? bits.hashCode() : 0); } public String toString() { return "clade " + bits.toString(); } int count; double credibility; BitSet bits; List<Object[]> attributeValues = null; } // Private stuff TaxonList taxonList = null; Map<BitSet, Clade> cladeMap = new HashMap<BitSet, Clade>(); Tree targetTree; } int totalTrees = 0; int totalTreesUsed = 0; double posteriorLimit = 0.0; Set<String> attributeNames = new HashSet<String>(); TaxonList taxa = null; static boolean processBivariateAttributes = false; static { try { System.loadLibrary("jri"); processBivariateAttributes = true; System.err.println("JRI loaded. Will process bivariate attributes"); } catch (UnsatisfiedLinkError e) { System.err.print("JRI not available. "); if (!USE_R) { processBivariateAttributes = true; System.err.println("Using Java bivariate attributes"); } else { System.err.println("Will not process bivariate attributes"); } } } public static void printTitle() { progressStream.println(); centreLine("TreeAnnotator " + version.getVersionString() + ", " + version.getDateString(), 60); centreLine("MCMC Output analysis", 60); centreLine("by", 60); centreLine("Andrew Rambaut and Alexei J. Drummond", 60); progressStream.println(); centreLine("Institute of Evolutionary Biology", 60); centreLine("University of Edinburgh", 60); centreLine("a.rambaut@ed.ac.uk", 60); progressStream.println(); centreLine("Department of Computer Science", 60); centreLine("University of Auckland", 60); centreLine("alexei@cs.auckland.ac.nz", 60); progressStream.println(); progressStream.println(); } public static void centreLine(String line, int pageWidth) { int n = pageWidth - line.length(); int n1 = n / 2; for (int i = 0; i < n1; i++) { progressStream.print(" "); } progressStream.println(line); } public static void printUsage(Arguments arguments) { arguments.printUsage("treeannotator", "<input-file-name> [<output-file-name>]"); progressStream.println(); progressStream.println(" Example: treeannotator test.trees out.txt"); progressStream.println(" Example: treeannotator -burnin 100 -heights mean test.trees out.txt"); progressStream.println(" Example: treeannotator -burnin 100 -target map.tree test.trees out.txt"); progressStream.println(); } //Main method public static void main(String[] args) throws IOException { String targetTreeFileName = null; String inputFileName = null; String outputFileName = null; if (args.length == 0) { System.setProperty("com.apple.macos.useScreenMenuBar", "true"); System.setProperty("apple.laf.useScreenMenuBar", "true"); System.setProperty("apple.awt.showGrowBox", "true"); java.net.URL url = LogCombiner.class.getResource("/images/utility.png"); javax.swing.Icon icon = null; if (url != null) { icon = new javax.swing.ImageIcon(url); } final String versionString = version.getVersionString(); String nameString = "TreeAnnotator " + versionString; String aboutString = "<html><center><p>" + versionString + ", " + version.getDateString() + "</p>" + "<p>by<br>" + "Andrew Rambaut and Alexei J. Drummond</p>" + "<p>Institute of Evolutionary Biology, University of Edinburgh<br>" + "<a href=\"mailto:a.rambaut@ed.ac.uk\">a.rambaut@ed.ac.uk</a></p>" + "<p>Department of Computer Science, University of Auckland<br>" + "<a href=\"mailto:alexei@cs.auckland.ac.nz\">alexei@cs.auckland.ac.nz</a></p>" + "<p>Part of the BEAST package:<br>" + "<a href=\"http: "</center></html>"; /*ConsoleApplication consoleApp = */ new ConsoleApplication(nameString, aboutString, icon, true); printTitle(); TreeAnnotatorDialog dialog = new TreeAnnotatorDialog(new JFrame()); if (!dialog.showDialog("TreeAnnotator " + versionString)) { return; } int burnin = dialog.getBurnin(); double posteriorLimit = dialog.getPosteriorLimit(); Target targetOption = dialog.getTargetOption(); HeightsSummary heightsOption = dialog.getHeightsOption(); targetTreeFileName = dialog.getTargetFileName(); if (targetOption == Target.USER_TARGET_TREE && targetTreeFileName == null) { System.err.println("No target file specified"); return; } inputFileName = dialog.getInputFileName(); if (inputFileName == null) { System.err.println("No input file specified"); return; } outputFileName = dialog.getOutputFileName(); if (outputFileName == null) { System.err.println("No output file specified"); return; } try { new TreeAnnotator(burnin, heightsOption, posteriorLimit, targetOption, targetTreeFileName, inputFileName, outputFileName); } catch (Exception ex) { System.err.println("Exception: " + ex.getMessage()); } progressStream.println("Finished - Quit program to exit."); while (true) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } printTitle(); Arguments arguments = new Arguments( new Arguments.Option[]{ //new Arguments.StringOption("target", new String[] { "maxclade", "maxtree" }, false, "an option of 'maxclade' or 'maxtree'"), new Arguments.StringOption("heights", new String[]{"keep", "median", "mean"}, false, "an option of 'keep' (default), 'median' or 'mean'"), new Arguments.IntegerOption("burnin", "the number of states to be considered as 'burn-in'"), new Arguments.RealOption("limit", "the minimum posterior probability for a node to be annoated"), new Arguments.StringOption("target", "target_file_name", "specifies a user target tree to be annotated"), new Arguments.Option("help", "option to print this message") }); try { arguments.parseArguments(args); } catch (Arguments.ArgumentException ae) { progressStream.println(ae); printUsage(arguments); System.exit(1); } if (arguments.hasOption("help")) { printUsage(arguments); System.exit(0); } HeightsSummary heights = HeightsSummary.KEEP_HEIGHTS; if (arguments.hasOption("heights")) { String value = arguments.getStringOption("heights"); if (value.equalsIgnoreCase("mean")) { heights = HeightsSummary.MEAN_HEIGHTS; } else if (value.equalsIgnoreCase("median")) { heights = HeightsSummary.MEDIAN_HEIGHTS; } } int burnin = -1; if (arguments.hasOption("burnin")) { burnin = arguments.getIntegerOption("burnin"); } double posteriorLimit = 0.0; if (arguments.hasOption("limit")) { posteriorLimit = arguments.getRealOption("limit"); } Target target = Target.MAX_CLADE_CREDIBILITY; if (arguments.hasOption("target")) { target = Target.USER_TARGET_TREE; targetTreeFileName = arguments.getStringOption("target"); } final String[] args2 = arguments.getLeftoverArguments(); switch ( args2.length ) { case 2: outputFileName = args2[1]; // fall to case 1: inputFileName = args2[0]; break; default: { System.err.println("Unknown option: " + args2[2]); System.err.println(); printUsage(arguments); System.exit(1); } } new TreeAnnotator(burnin, heights, posteriorLimit, target, targetTreeFileName,inputFileName, outputFileName); System.exit(0); } }
package edu.agh.tunev.model; import java.awt.Shape; import java.awt.geom.AffineTransform; import java.awt.geom.Area; import java.awt.geom.Ellipse2D; import java.awt.geom.Rectangle2D; public final class Common { static Shape createEllipse(double x, double y, double w, double h, double deg) { return AffineTransform.getRotateInstance(deg * Math.PI / 180.0, x, y) .createTransformedShape( new Ellipse2D.Double(x - w / 2, y - h / 2, w, h)); } static double intersectionArea(Shape s1, Shape s2) { final int w = 100; final int h = 100; // Shape e1 = ellipse(250, 250, 200, 100, 0); // Shape e2 = ellipse(250, 250, 200, 100, 0); // 62847.616 // a analityczny wynik: // 200*100*Math.PI == 62831.8530718 // 10x10 -> 10.87% final Area area = new Area(s1); area.intersect(new Area(s2)); Rectangle2D bounds = area.getBounds2D(); final double dx = bounds.getWidth() / w; final double dy = bounds.getHeight() / h; final double tx = -bounds.getMinX(); final double ty = -bounds.getMinY(); final AffineTransform at = AffineTransform.getScaleInstance(1.0 / dx, 1.0 / dy); at.concatenate(AffineTransform.getTranslateInstance(tx, ty)); java.awt.image.BufferedImage image = new java.awt.image.BufferedImage( w, h, java.awt.image.BufferedImage.TYPE_INT_RGB); java.awt.Graphics2D g = image.createGraphics(); g.setPaint(java.awt.Color.WHITE); g.fillRect(0, 0, w, h); g.setPaint(java.awt.Color.BLACK); g.fill(at.createTransformedShape(area)); int num = 0; for (int i = 0; i < w; i++) for (int j = 0; j < h; j++) if ((image.getRGB(i, j) & 0x00ffffff) == 0) num++; return 4 * dx * dy * num; } private Common() { // you shall not instantiate ^-^ } }
package edu.umn.csci5801; import edu.umn.csci5801.model.*; import junit.framework.TestCase; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static org.junit.Assert.*; public class GRADSTest extends TestCase { private String readFile(String fileName) throws IOException { BufferedReader br = new BufferedReader(new FileReader(fileName)); try { StringBuilder sb = new StringBuilder(); String line = br.readLine(); while (line != null) { sb.append(line.replaceAll("\\s", "")); line = br.readLine(); } return sb.toString(); } finally { br.close(); } } private boolean compareStudentRecords(StudentRecord sr1, StudentRecord sr2) { if(!sr1.getStudent().sameStudents(sr2.getStudent())) { // Student return false; } else if(sr1.getDepartment() != sr2.getDepartment()) { // Department return false; } else if(sr1.getDegreeSought() != sr2.getDegreeSought()) { // degreeSought return false; } else if(!sr1.getTermBegan().sameTerm(sr2.getTermBegan())) { // termBegan return false; } else if(!compareProfessorList(sr1.getAdvisors(), sr2.getAdvisors())) { // advisors return false; } else if(!compareProfessorList(sr1.getCommittee(), sr2.getCommittee())) { // committee return false; } else if(!compareCoursesTaken(sr1.getCoursesTaken(), sr2.getCoursesTaken())) { // coursesTaken return false; } else if(!compareMilestonesList(sr1.getMilestonesSet(), sr2.getMilestonesSet())) { // milestonesSet return false; } else if(!compareNotesList(sr1.getNotes(), sr2.getNotes())) { // notes return false; } return true; } private boolean compareNotesList(List<String> l1, List<String> l2) { if(l1.isEmpty() && l2.isEmpty()) { return true; } else if(l1.isEmpty() || l2.isEmpty()) { return false; } if(l1.size() != l2.size()) { return false; } for(int i=0; i< l1.size(); i++) { if(!l2.get(i).equals(l2.get(i))) { return false; } } return true; } private boolean compareMilestonesList(List<CompletedMilestone> l1, List<CompletedMilestone> l2) { if(l1.isEmpty() && l2.isEmpty()) { return true; } else if(l1.isEmpty() || l2.isEmpty()) { return false; } if(l1.size() != l2.size()) { return false; } for(int i=0; i< l1.size(); i++) { if(!l1.get(i).compareCompletedMilestone(l2.get(i))) { return false; } } return true; } private boolean compareProfessorList(List<Professor> l1, List<Professor> l2) { if(l1.isEmpty() && l2.isEmpty()) { return true; } else if(l1.isEmpty() || l2.isEmpty()) { return false; } if(l1.size() != l2.size()) { return false; } for(int i=0; i< l1.size(); i++) { if(!l1.get(i).compareProfessor(l2.get(i))) { return false; } } return true; } private boolean compareCoursesTaken(List<CourseTaken> l1, List<CourseTaken> l2) { if(l1.isEmpty() && l2.isEmpty()) { return true; } else if(l1.isEmpty() || l2.isEmpty()) { return false; } if(l1.size() != l2.size()) { return false; } for(int i=0; i< l1.size(); i++) { if(!l1.get(i).compareCourseTaken(l2.get(i))) { return false; } } return true; } @Test public void testLoadUsers() throws Exception { GRADS grads = new GRADS(); grads.loadUsers("resources/users.txt"); } @Test(expected = IOException.class) public void textExceptionThrownLoadUsers() throws Exception { GRADS grads = new GRADS(); grads.loadUsers("resources/not_a_file.txt"); } @Test public void testLoadCourses() throws Exception { GRADS grads = new GRADS(); grads.loadCourses("resources/courses.txt"); } @Test(expected = IOException.class) public void testExceptionThrownLoadCourses() throws Exception { GRADS grads = new GRADS(); grads.loadCourses("resources/not_a_file.txt"); } @Test public void testLoadRecords() throws Exception { GRADS grads = new GRADS(); grads.loadRecords("resources/students.txt"); } @Test(expected = IOException.class) public void testExceptionThrownLoadRecords() throws Exception { GRADS grads = new GRADS(); grads.loadRecords("resources/not_a_file.txt"); } @Test public void testSetUser() throws Exception { GRADS grads = new GRADS(); grads.loadUsers("resources/users.txt"); grads.setUser("tolas9999"); } @Test public void testGetUser() throws Exception { GRADS grads = new GRADS(); grads.loadUsers("resources/users.txt"); grads.setUser("tolas9999"); assertEquals("tolas9999",grads.getUser()); } @Test public void testGPCGetStudentIDs() throws Exception { GRADS grads = new GRADS(); grads.loadUsers("resources/users.txt"); grads.loadRecords("resources/students.txt"); grads.setUser("tolas9999"); grads.getStudentIDs(); String expectedOutputString = "[\"smith1234\",\"doe5678\",\"nguy0621\",\"gayxx067\",\"bob099\",\"desil1337\",\"hanxx123\",\"zhang9101\"]"; assertEquals(expectedOutputString,readFile("studentids.txt")); } @Test public void testStudentGetStudentIDs() throws Exception { try { GRADS grads = new GRADS(); grads.loadUsers("resources/users.txt"); grads.loadRecords("resources/courses.txt"); grads.setUser("nguy0621"); grads.getStudentIDs(); fail("Should throw Invalid User Exception"); } catch (InvalidUserException e) { assertTrue(e.getMessage().equals("User does not have this access to Student IDs")); } } @Test public void testStudentGetOwnTranscript() throws Exception { GRADS grads = new GRADS(); grads.loadUsers("resources/users.txt"); grads.loadCourses("resources/courses.txt"); grads.loadRecords("resources/students.txt"); grads.setUser("hanxx123"); StudentRecord transcript = grads.getTranscript("hanxx123"); // Compare to: GRADS grads1 = new GRADS(); grads1.loadUsers("resources/users.txt"); grads1.loadRecords("resources/testGPCAddMilestone.txt"); grads1.setUser("tolas9999"); // CSCI GPC StudentRecord compareTranscript = grads1.getTranscript("hanxx123"); assert(compareStudentRecords(transcript, compareTranscript)); } //@Test(expected = InvalidUserException.class) //@Test(expected = Exception.class) @Test(expected = IOException.class) public void testStudentGetOtherTranscript() throws Exception { try { GRADS grads = new GRADS(); grads.loadUsers("resources/users.txt"); grads.loadCourses("resources/courses.txt"); grads.loadRecords("resources/students.txt"); grads.setUser("smith1234"); grads.getTranscript("hanxx123"); fail("Should throw Invalid User Exception"); } catch (InvalidUserException e) { assertTrue(e.getMessage().equals("Invalid user")); } } @Test public void testGPCGetTranscript() throws Exception { GRADS grads = new GRADS(); grads.loadUsers("resources/users.txt"); grads.loadCourses("resources/courses.txt"); grads.loadRecords("resources/students.txt"); grads.setUser("hanxx123"); StudentRecord transcript = grads.getTranscript("hanxx123"); // Compare to: GRADS grads1 = new GRADS(); grads1.loadUsers("resources/users.txt"); grads1.loadRecords("resources/students.txt"); grads1.setUser("tolas9999"); // CSCI GPC StudentRecord compareTranscript = grads1.getTranscript("hanxx123"); assert(compareStudentRecords(transcript, compareTranscript)); } @Test public void testStudentUpdateTranscript() throws Exception { GRADS grads = new GRADS(); grads.loadUsers("resources/users.txt"); grads.loadCourses("resources/courses.txt"); grads.loadRecords("resources/students.txt"); grads.setUser("hanxx123"); StudentRecord studentRecord = grads.getTranscript("hanxx123"); List<Professor> professorList = studentRecord.getAdvisors(); Professor professor = new Professor(Department.MATH, professorList.get(0).getFirstName(), professorList.get(0).getLastName()); professorList.set(0, professor); studentRecord.setAdvisors(professorList); grads.updateTranscript("hanxx123", studentRecord); StudentRecord newTranscript = grads.getTranscript("hanxx123"); // Compare to: GRADS grads1 = new GRADS(); grads1.loadUsers("resources/users.txt"); grads1.loadRecords("resources/testGPCChangeAdvisor.txt"); grads1.setUser("hanxx123"); // CSCI GPC StudentRecord compareTranscript = grads1.getTranscript("hanxx123"); assert(compareStudentRecords(newTranscript, compareTranscript)); } @Test public void testGPCUpdateTranscript() throws Exception { GRADS grads = new GRADS(); grads.loadUsers("resources/users.txt"); grads.loadCourses("resources/courses.txt"); grads.loadRecords("resources/students.txt"); grads.setUser("tolas9999"); StudentRecord studentRecord = grads.getTranscript("hanxx123"); List<Professor> professorList = studentRecord.getAdvisors(); Professor professor = new Professor(Department.MATH, professorList.get(0).getFirstName(), professorList.get(0).getLastName()); professorList.set(0, professor); studentRecord.setAdvisors(professorList); grads.updateTranscript("hanxx123", studentRecord); StudentRecord newTranscript = grads.getTranscript("hanxx123"); // Compare to: GRADS grads1 = new GRADS(); grads1.loadUsers("resources/users.txt"); grads1.loadRecords("resources/testGPCChangeAdvisor.txt"); grads1.setUser("tolas9999"); // CSCI GPC StudentRecord compareTranscript = grads1.getTranscript("hanxx123"); assert(compareStudentRecords(newTranscript, compareTranscript)); } @Test public void testStudentAddNote() throws Exception { GRADS grads = new GRADS(); grads.loadUsers("resources/users.txt"); grads.loadCourses("resources/courses.txt"); grads.loadRecords("resources/students.txt"); grads.setUser("hanxx123"); StudentRecord studentRecord = grads.getTranscript("hanxx123"); studentRecord.addNote("note4"); grads.updateTranscript("hanxx123", studentRecord); StudentRecord newTranscript = grads.getTranscript("hanxx123"); // Compare to: GRADS grads1 = new GRADS(); grads1.loadUsers("resources/users.txt"); grads1.loadRecords("resources/testAddNote.txt"); grads1.setUser("hanxx123"); // CSCI GPC StudentRecord compareTranscript = grads1.getTranscript("hanxx123"); assert(compareStudentRecords(newTranscript, compareTranscript)); } @Test public void testGPCAddNote() throws Exception { GRADS grads = new GRADS(); grads.loadUsers("resources/users.txt"); grads.loadCourses("resources/courses.txt"); grads.loadRecords("resources/students.txt"); grads.setUser("tolas9999"); StudentRecord studentRecord = grads.getTranscript("hanxx123"); studentRecord.addNote("note4"); grads.updateTranscript("hanxx123", studentRecord); StudentRecord newTranscript = grads.getTranscript("hanxx123"); // Compare to: GRADS grads1 = new GRADS(); grads1.loadUsers("resources/users.txt"); grads1.loadRecords("resources/testAddNote.txt"); grads1.setUser("tolas9999"); // CSCI GPC StudentRecord compareTranscript = grads1.getTranscript("hanxx123"); assert(compareStudentRecords(newTranscript, compareTranscript)); } @Test public void testStudentGenerateOwnProgressSummary() throws Exception { GRADS grads = new GRADS(); grads.loadUsers("resources/users.txt"); grads.loadCourses("resources/courses.txt"); grads.loadRecords("resources/students.txt"); grads.setUser("zhang9101"); grads.generateProgressSummary("zhang9101"); } @Test public void testStudentGenerateOtherProgressSummary() throws Exception { try { GRADS grads = new GRADS(); grads.loadUsers("resources/users.txt"); grads.loadCourses("resources/courses.txt"); grads.loadRecords("resources/students.txt"); grads.setUser("zhang9101"); grads.generateProgressSummary("doe5678"); fail("Student can't generate another student's progress summary"); } catch (InvalidUserException e) { assertTrue(e.getMessage().equals("Invalid user")); } } @Test public void testGPCGenerateProgressSummary() throws Exception { GRADS grads = new GRADS(); grads.loadUsers("resources/users.txt"); grads.loadCourses("resources/courses.txt"); grads.loadRecords("resources/students.txt"); grads.setUser("tolas9999"); grads.generateProgressSummary("zhang9101"); } @Test public void testStudentSimulateOwnCourses() throws Exception { GRADS grads = new GRADS(); List<CourseTaken> coursesTaken = Arrays.asList(); grads.loadUsers("resources/users.txt"); grads.loadCourses("resources/courses.txt"); grads.loadRecords("resources/students.txt"); grads.setUser("zhang9101"); grads.simulateCourses("zhang9101", coursesTaken); } @Test public void testStudentSimulateOtherCourses() throws Exception { try { GRADS grads = new GRADS(); List<CourseTaken> coursesTaken = Arrays.asList(); grads.loadUsers("resources/users.txt"); grads.loadCourses("resources/courses.txt"); grads.loadRecords("resources/students.txt"); grads.setUser("zhang9101"); grads.simulateCourses("doe5678", coursesTaken); } catch (InvalidUserException e) { assertTrue(e.getMessage().equals("Invalid user")); } } @Test public void testGPCSimulateCourses() throws Exception { GRADS grads = new GRADS(); List<CourseTaken> coursesTaken = Arrays.asList(); grads.loadUsers("resources/users.txt"); grads.loadCourses("resources/courses.txt"); grads.loadRecords("resources/students.txt"); grads.setUser("tolas9999"); grads.simulateCourses("zhang9101", coursesTaken); } @Test //GPA below PhD req, rest met public void testPhDSimulateCoursesLowGPA() throws Exception { GRADS grads = new GRADS(); List<CourseTaken> coursesTaken = Arrays.asList(); grads.loadUsers("resources/users.txt"); grads.loadCourses("resources/courses.txt"); grads.loadRecords("resources/students.txt"); grads.setUser("smith1234"); grads.simulateCourses("smith1234", coursesTaken); } @Test //GPA below Master req, rest met public void testMasterSimulateCoursesLowGPA() throws Exception { GRADS grads = new GRADS(); List<CourseTaken> coursesTaken = Arrays.asList(); grads.loadUsers("resources/users.txt"); grads.loadCourses("resources/courses.txt"); grads.loadRecords("resources/studentsJohnMastersA.txt"); grads.setUser("smith1234"); grads.simulateCourses("smith1234", coursesTaken); } @Test //PhD doesn't meet thesis credit, rest met public void testPhDSimulateCoursesThesisCredit() throws Exception { GRADS grads = new GRADS(); List<CourseTaken> coursesTaken = Arrays.asList(); grads.loadUsers("resources/users.txt"); grads.loadCourses("resources/courses.txt"); grads.loadRecords("resources/studentsJanePhd.txt"); grads.setUser("doe5678"); grads.simulateCourses("doe5678", coursesTaken); } @Test //All requirements met public void testMasterSimulateCoursesAllMet() throws Exception { GRADS grads = new GRADS(); List<CourseTaken> coursesTaken = Arrays.asList(); grads.loadUsers("resources/users.txt"); grads.loadCourses("resources/courses.txt"); grads.loadRecords("resources/students.txt"); grads.setUser("doe5678"); grads.simulateCourses("doe5678", coursesTaken); } @Test //PhD adds courses to meet necessary requirements public void testPhDSimulateCoursesNewCourse() throws Exception { GRADS grads = new GRADS(); Term f15 = new Term(); f15.setSemester("FALL"); f15.setYear(2015); Course csci8980 = new Course("Special Advanced Topics in Computer Science", "csci8980", "3"); CourseTaken csci8980f15 = new CourseTaken(csci8980, f15, Grade.B); Course math5335 = new Course("MATH 5335", "math5335", "4"); CourseTaken math5335f15 = new CourseTaken(math5335, f15, Grade.A); Course math5336 = new Course("MATH 5336", "math5336", "3"); CourseTaken math5336f15 = new CourseTaken(math5336, f15, Grade.A); Course csci5512 = new Course("Artificial Intelligence II", "csci5512", "3", CourseArea.APPLICATIONS); CourseTaken csci5512f15 = new CourseTaken(csci5512, f15, Grade.B); Course cs8970 = new Course("Computer Science Colloquium", "csci8970", "1"); CourseTaken cs8970f15 = new CourseTaken(cs8970, f15, Grade.S); grads.loadUsers("resources/users.txt"); grads.loadCourses("resources/courses.txt"); grads.loadRecords("resources/students.txt"); List<CourseTaken> coursesTaken = Arrays.asList(csci8980f15, math5335f15, math5336f15, csci5512f15, cs8970f15); grads.setUser("zhang9101"); grads.simulateCourses("zhang9101", coursesTaken); } @Test //MastersA adds courses to meet necessary requirements except 8000 level public void testMasterSimulateCoursesNewCourse() throws Exception { } @Test //MastersA doesn't meet credits, 8000-level, or Colloquium public void testMasterSimulateCoursesNew() throws Exception { } @Test public void testGPCAddMilestone() throws Exception { GRADS grads = new GRADS(); grads.loadUsers("resources/users.txt"); grads.loadCourses("resources/courses.txt"); grads.loadRecords("resources/students.txt"); grads.setUser("tolas9999"); StudentRecord studentRecord = grads.getTranscript("zhang9101"); studentRecord.addMilestonesSet(new CompletedMilestone(Milestone.PRELIM_COMMITTEE_APPOINTED, new Term(Semester.FALL, 2014))); grads.updateTranscript("zhang9101", studentRecord); StudentRecord newTranscript = grads.getTranscript("zhang9101"); // Compare to: GRADS grads1 = new GRADS(); grads1.loadUsers("resources/users.txt"); grads1.loadRecords("resources/testGPCAddMilestone.txt"); grads1.setUser("tolas9999"); // CSCI GPC StudentRecord compareTranscript = grads1.getTranscript("zhang9101"); assert(compareStudentRecords(newTranscript, compareTranscript)); } @Test public void testGPCChangeMilestone() throws Exception { GRADS grads = new GRADS(); grads.loadUsers("resources/users.txt"); grads.loadCourses("resources/courses.txt"); grads.loadRecords("resources/students.txt"); grads.setUser("tolas9999"); StudentRecord studentRecord = grads.getTranscript("hanxx123"); List<CompletedMilestone> milestoneList = studentRecord.getMilestonesSet(); int year = milestoneList.get(0).getTerm().getYear() - 1; Milestone milestone = milestoneList.get(0).getMilestone(); Term term = new Term(milestoneList.get(0).getTerm().getSemester(), year); milestoneList.set(0, new CompletedMilestone(milestone, term)); studentRecord.setMilestonesSet(milestoneList); grads.updateTranscript("hanxx123", studentRecord); StudentRecord newTranscript = grads.getTranscript("hanxx123"); // Compare to: GRADS grads1 = new GRADS(); grads1.loadUsers("resources/users.txt"); grads1.loadRecords("resources/testGPCChangeMilestone.txt"); grads1.setUser("tolas9999"); // CSCI GPC StudentRecord compareTranscript = grads1.getTranscript("hanxx123"); assert(compareStudentRecords(newTranscript, compareTranscript)); } @Test public void testGPCChangeAdvisor() throws Exception { GRADS grads = new GRADS(); grads.loadUsers("resources/users.txt"); grads.loadCourses("resources/courses.txt"); grads.loadRecords("resources/students.txt"); grads.setUser("tolas9999"); StudentRecord studentRecord = grads.getTranscript("desil1337"); studentRecord.addAdvisor(new Professor(Department.COMPUTER_SCIENCE, "Will", "Smith")); grads.updateTranscript("desil1337", studentRecord); StudentRecord newTranscript = grads.getTranscript("desil1337"); // Compare to: GRADS grads1 = new GRADS(); grads1.loadUsers("resources/users.txt"); grads1.loadRecords("resources/testAddAdvisor.txt"); grads1.setUser("tolas9999"); // CSCI GPC StudentRecord compareTranscript = grads1.getTranscript("desil1337"); assert(compareStudentRecords(newTranscript, compareTranscript)); } @Test //PhD or Plan B student public void testStudentAuthorizedChangeAdvisor() throws Exception { GRADS grads = new GRADS(); grads.loadUsers("resources/users.txt"); grads.loadCourses("resources/courses.txt"); grads.loadRecords("resources/students.txt"); grads.setUser("desil1337"); StudentRecord studentRecord = grads.getTranscript("desil1337"); studentRecord.addAdvisor(new Professor(Department.COMPUTER_SCIENCE, "Will", "Smith")); grads.updateTranscript("desil1337", studentRecord); StudentRecord newTranscript = grads.getTranscript("desil1337"); // Compare to: GRADS grads1 = new GRADS(); grads1.loadUsers("resources/users.txt"); grads1.loadRecords("resources/testAddAdvisor.txt"); grads1.setUser("desil1337"); // CSCI GPC StudentRecord compareTranscript = grads1.getTranscript("desil1337"); assert(compareStudentRecords(newTranscript, compareTranscript)); } @Test //PhD or Plan B student public void testStudentUnauthorizedChangeAdvisor() throws Exception { } @Test //PhD, Plan A, or Plan C public void testGPCChangeCommittee() throws Exception { } @Test //PhD, Plan A, or Plan C public void testStudentAuthorizedChangeCommittee() throws Exception { } @Test //PhD, Plan A, or Plan C public void testStudentUnauthorizedChangeCommittee() throws Exception { } @Test public void testGPCChangeGrade() throws Exception { } @Test public void testStudentChangeGrade() throws Exception { } @Test public void testGPCAllowCourse() throws Exception { } @Test public void testStudentAllowCourse() throws Exception { } }
package xi.linker; import static xi.go.VM.UTF8; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.Writer; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.Map.Entry; import stefan.Cout; import xi.ast.Expr; import xi.ast.LetIn; import xi.ast.Module; import xi.ast.Name; import xi.ast.stefan.LazyTree; /** * A linker for the SK output. * * @author Leo */ public class Linker { /** Definition map. */ final Map<String, Expr> defs = new HashMap<String, Expr>(); /** * Constructor. * * @param ins * SKLib inputs * @throws IOException * I/O exception */ public Linker(final List<Reader> ins) throws IOException { final Map<String, Expr> module = new HashMap<String, Expr>(); final AstSKParser parser = new AstSKParser(module); for (final Reader r : ins) { // keeps the possibility to overwrite functions in other files parser.read(r); defs.putAll(module); module.clear(); } } public Expr link(final String startSym) { final Map<String, Expr> required = new HashMap<String, Expr>(); final Queue<String> queue = new ArrayDeque<String>(); queue.add(startSym); while (!queue.isEmpty()) { final String sym = queue.poll(); if (!required.containsKey(sym)) { final Expr body = defs.get(sym); if (body == null) { throw new IllegalArgumentException("Symbol '" + sym + "' not found."); } required.put(sym, body); for (final Name n : body.freeVars()) { queue.add(n.toString()); } } } final Expr start = required.remove(startSym); final Module mod = new Module(false); for (final Entry<String, Expr> e : required.entrySet()) { mod.addDefinition(Name.valueOf(e.getKey()), e.getValue()); } final LetIn let = new LetIn(mod, start); return let.unLambda(); } public static void main(final String[] args) throws Exception { String start = "main"; final ArrayList<Reader> inputs = new ArrayList<Reader>(); Writer out = new OutputStreamWriter(System.out); boolean invalid = false; for (int i = 0; i < args.length; i++) { if (args[i].equals("-help")) { invalid = true; break; } if (args[i].equals("-start")) { if (i == args.length - 1) { invalid = true; break; } start = args[++i]; } else if ("-out".equals(args[i])) { if (i == args.length - 1) { invalid = true; break; } out = new OutputStreamWriter(new FileOutputStream(args[i]), UTF8); } else if ("-".equals(args[i])) { inputs.add(new InputStreamReader(System.in)); } else { final File f = new File(args[i]); if (!f.isFile()) { invalid = true; break; } inputs.add(new InputStreamReader(new FileInputStream(f), UTF8)); } } if (invalid) { System.err.println("Usage: sasln [-help] [-start <start_sym>] " + "[-out <dest_file>] <sklib>...\n" + "\t<start_sym>: function name used as entry point," + " default is 'main'.\n" + "\t<dest_file>: File to write to, default is STDOUT.\n" + "\t<sklib>: a file containing an SK library," + " '-' means STDIN.\n"); return; } if (inputs.isEmpty()) { inputs.add(new InputStreamReader(System.in)); } final Linker linker = new Linker(inputs); final Expr linked = linker.link(start); final Module mod = new Module(false); mod.addDefinition(Name.valueOf("main"), linked); Cout.module(LazyTree.create(mod), out); } }
package foam.nanos.dig; import foam.core.*; import foam.core.PropertyInfo; import foam.dao.AbstractSink; import foam.dao.ArraySink; import foam.dao.DAO; import foam.lib.csv.*; import foam.lib.json.*; import foam.lib.parse.*; import foam.nanos.boot.NSpec; import foam.nanos.http.WebAgent; import foam.nanos.logger.Logger; import foam.nanos.notification.email.EmailMessage; import foam.nanos.notification.email.EmailService; import java.io.*; import java.nio.CharBuffer; import java.util.*; import java.util.Iterator; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.ServletException; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamReader; import org.apache.commons.text.StringEscapeUtils; public class DigWebAgent implements WebAgent { public DigWebAgent() {} public void execute(X x) { HttpServletRequest req = x.get(HttpServletRequest.class); HttpServletResponse response = x.get(HttpServletResponse.class); final PrintWriter out = x.get(PrintWriter.class); CharBuffer buffer_ = CharBuffer.allocate(65535); String data = req.getParameter("data"); String daoName = req.getParameter("dao"); String command = req.getParameter("cmd"); String format = req.getParameter("format"); String id = req.getParameter("id"); Logger logger = (Logger) x.get("logger"); DAO nSpecDAO = (DAO) x.get("nSpecDAO"); String [] email = req.getParameterValues("email"); String subject = req.getParameter("subject"); response.setContentType("text/html"); if ( command == null || "".equals(command) ) command = "put"; if ( format == null ) format = "json"; try { if ( "put".equals(command) && ( data == null || "".equals(data) ) ) { out.println("<form method=post><span>DAO:</span>"); out.println("<span><select name=dao id=dao style=margin-left:35 onchange=changeDao()>"); //gets all ongoing nanopay services nSpecDAO.orderBy(NSpec.NAME).select(new AbstractSink() { public void put(FObject o, Detachable d) { NSpec s = (NSpec) o; if ( s.getServe() && s.getName().endsWith("DAO") ) { out.println("<option value=" + s.getName() + ">" + s.getName() + "</option>"); } } }); out.println("</select></span>"); out.println("<br><br><span id=formatSpan>Format:<select name=format id=format onchange=changeFormat() style=margin-left:25><option value=csv>CSV</option><option value=xml>XML</option><option value=json selected>JSON</option><option value=html>HTML</option><option value=jsonj>JSON/J</option></select></span>"); out.println("<br><br><span>Command:<select name=cmd id=cmd width=150 style=margin-left:5 onchange=changeCmd(this.value)><option value=put selected>PUT</option><option value=select>SELECT</option><option value=remove>REMOVE</option><option value=help>HELP</option></select></span>"); out.println("<br><br><span id=emailSpan style=display:none;>Email:<input name=email style=margin-left:30;width:350></input></span>"); out.println("<br><br><span id=subjectSpan style=display:none;>Subject:<input name=subject style=margin-left:20;width:350></input></span>"); out.println("<br><br><span id=idSpan style=display:none;>ID:<input id=id name=id style=margin-left:52></input></span>"); out.println("<br><br><span id=dataSpan>Data:<br><textarea rows=20 cols=120 name=data></textarea></span>"); out.println("<br><span id=urlSpan style=display:none;> URL : </span>"); out.println("<input id=builtUrl size=120 style=margin-left:20;display:none;/ >"); out.println("<br><br><button type=submit >Submit</button></form>"); out.println("<script>function changeCmd(cmdValue) { if ( cmdValue != 'put' ) {document.getElementById('dataSpan').style.cssText = 'display: none'; } else { document.getElementById('dataSpan').style.cssText = 'display: inline-block'; } if ( cmdValue == 'remove' ) { document.getElementById('idSpan').style.cssText = 'display: inline-block'; document.getElementById('formatSpan').style.cssText = 'display:none';} else { document.getElementById('idSpan').style.cssText = 'display: none'; document.getElementById('formatSpan').style.cssText = 'display: inline-block'; document.getElementById('id').value = '';} if ( cmdValue == 'select' ) {document.getElementById('emailSpan').style.cssText = 'display: inline-block'; document.getElementById('subjectSpan').style.cssText = 'display: inline-block'; document.getElementById('urlSpan').style.cssText = 'display: inline-block';document.getElementById('builtUrl').style.cssText = 'display: inline-block'; var vbuiltUrl = document.location.protocol + '//' + document.location.host + '/service/dig?dao=' + document.getElementById('dao').value + '&format=' + document.getElementById('format').options[document.getElementById('format').selectedIndex].value + '&cmd=' + document.getElementById('cmd').options[document.getElementById('cmd').selectedIndex].value + '&email='; document.getElementById('builtUrl').value=vbuiltUrl;}else {document.getElementById('emailSpan').style.cssText = 'display:none'; document.getElementById('subjectSpan').style.cssText ='display:none';document.getElementById('urlSpan').style.cssText = 'display:none';document.getElementById('builtUrl').style.cssText = 'display:none';}}</script>"); out.println("<script>function changeDao() {var vbuiltUrl = document.location.protocol + '//' + document.location.host + '/service/dig?dao=' + document.getElementById('dao').value + '&format=' + document.getElementById('format').options[document.getElementById('format').selectedIndex].value + '&cmd=' + document.getElementById('cmd').options[document.getElementById('cmd').selectedIndex].value + '&email='; document.getElementById('builtUrl').value=vbuiltUrl;}</script>"); out.println("<script>function changeFormat() {var vbuiltUrl = document.location.protocol + '//' + document.location.host + '/service/dig?dao=' + document.getElementById('dao').value + '&format=' + document.getElementById('format').options[document.getElementById('format').selectedIndex].value + '&cmd=' + document.getElementById('cmd').options[document.getElementById('cmd').selectedIndex].value + '&email='; document.getElementById('builtUrl').value=vbuiltUrl;}</script>"); out.println(); return; } if ( daoName == null || "".equals(daoName) ) { throw new RuntimeException("Input DaoName"); } DAO dao = (DAO) x.get(daoName); if ( dao == null ) { throw new RuntimeException("DAO not found"); } dao = dao.inX(x); FObject obj = null; ClassInfo cInfo = dao.getOf(); Class objClass = cInfo.getObjClass(); if ( "put".equals(command) ) { if ( "json".equals(format) ) { JSONParser jsonParser = new JSONParser(); jsonParser.setX(x); //let FObjectArray parse first Object o = null; o = jsonParser.parseStringForArray(data, objClass); if ( o != null ) { Object[] objs = (Object[]) o; for ( int j = 0 ; j < objs.length ; j++ ) { obj = (FObject) objs[j]; dao.put(obj); } out.println("Success"); return; } String dataArray[] = data.split("\\{\"class\":\"" + cInfo.getId()); for ( int i = 0 ; i < dataArray.length ; i++ ) { o = jsonParser.parseString(data, objClass); if ( o == null ) { out.println("Parse Error : "); String message = getParsingError(x, buffer_.toString()); logger.error(message + ", input: " + buffer_.toString()); out.println(message); out.flush(); return; } obj = (FObject) o; dao.put(obj); } } else if ( "xml".equals(format) ) { XMLSupport xmlSupport = new XMLSupport(); XMLInputFactory factory = XMLInputFactory.newInstance(); StringReader reader = new StringReader(data); XMLStreamReader xmlReader = factory.createXMLStreamReader(reader); List<FObject> objList = xmlSupport.fromXML(x, xmlReader, objClass); if ( objList.size() == 0 ) { out.println("Parse Error : "); String message = getParsingError(x, buffer_.toString()); logger.error(message + ", input: " + buffer_.toString()); out.println(message); out.flush(); return; } Iterator i = objList.iterator(); while ( i.hasNext() ) { obj = (FObject)i.next(); obj = dao.put(obj); } } else if ( "csv".equals(format) ) { CSVSupport csvSupport = new CSVSupport(); csvSupport.setX(x); // convert String into InputStream InputStream is = new ByteArrayInputStream(data.getBytes()); ArraySink arraySink = new ArraySink(); csvSupport.inputCSV(is, arraySink, cInfo); List list = arraySink.getArray(); if ( list.size() == 0 ) { out.println("Parse Error : "); String message = getParsingError(x, buffer_.toString()); logger.error(message + ", input: " + buffer_.toString()); out.println(message); out.flush(); return; } for ( int i = 0 ; i < list.size() ; i++ ) { dao.put((FObject) list.get(i)); } } else if ( "html".equals(format) || "jsonj".equals(format) ) { out.println("Please pick the follwed format - CSV, JSON, XML when put."); } out.println("Success"); } else if ( "select".equals(command) ) { ArraySink sink = (ArraySink) dao.select(new ArraySink()); System.err.println("objects selected: " + sink.getArray().size()); if ( "json".equals(format) ) { foam.lib.json.Outputter outputterJson = new foam.lib.json.Outputter(OutputterMode.NETWORK); outputterJson.output(sink.getArray().toArray()); response.setContentType("application/json"); if ( email.length != 0 && !email[0].equals("") && email[0] != null ) { output(x, outputterJson.toString()); } else { out.println(outputterJson.toString()); } } else if ( "xml".equals(format) ) { XMLSupport xmlSupport = new XMLSupport(); if ( email.length != 0 && !email[0].equals("") && email[0] != null ) { String xmlData = "<textarea style=\"width:700;height:400;\" rows=10 cols=120>" + xmlSupport.toXMLString(sink.getArray()) + "</textarea>"; output(x, xmlData); } else { out.println(StringEscapeUtils.escapeXml11(xmlSupport.toXMLString(sink.getArray()))); } } else if ( "csv".equals(format) ) { foam.lib.csv.Outputter outputterCsv = new foam.lib.csv.Outputter(OutputterMode.NETWORK); outputterCsv.output(sink.getArray().toArray()); List a = sink.getArray(); for ( int i = 0 ; i < a.size() ; i++ ) { outputterCsv.put((FObject) a.get(i), null); } response.setContentType("text/plain"); if ( email.length != 0 && !email[0].equals("") && email[0] != null ) { output(x, outputterCsv.toString()); } else { out.println(outputterCsv.toString()); } } else if ( "html".equals(format) ) { foam.lib.html.Outputter outputterHtml = new foam.lib.html.Outputter(OutputterMode.NETWORK); outputterHtml.outputStartHtml(); outputterHtml.outputStartTable(); List a = sink.getArray(); for ( int i = 0 ; i < a.size() ; i++ ) { if ( i == 0 ) { outputterHtml.outputHead((FObject) a.get(i)); } outputterHtml.put((FObject) a.get(i), null); } outputterHtml.outputEndTable(); outputterHtml.outputEndHtml(); if ( email.length != 0 && !email[0].equals("") && email[0] != null ) { output(x, outputterHtml.toString()); } else { out.println(outputterHtml.toString()); } } else if ( "jsonj".equals(format) ) { foam.lib.json.Outputter outputterJson = new foam.lib.json.Outputter(OutputterMode.NETWORK); List a = sink.getArray(); String dataToString = ""; response.setContentType("application/json"); for ( int i = 0 ; i < a.size() ; i++ ) { outputterJson.output(a.get(i)); } String dataArray[] = outputterJson.toString().split("\\{\"class\":\"" + cInfo.getId()); for ( int k = 1 ; k < dataArray.length; k++ ) { dataToString += "p({\"class\":\"" + cInfo.getId() + dataArray[k] + ")\n"; } if ( email.length != 0 && !email[0].equals("") && email[0] != null ) { output(x, dataToString); } else { out.println(dataToString); } } } else if ( "help".equals(command) ) { out.println("Help: <br><br>" ); /*List<PropertyInfo> props = cInfo.getAxiomsByClass(PropertyInfo.class); out.println(daoName + "<br><br>"); out.println("<table>"); for( PropertyInfo pi : props ) { out.println("<tr>"); out.println("<td width=200>" + pi.getName() + "</td>"); out.println("<td width=200>" + pi.getValueClass().getSimpleName() + "</td>"); out.println("</tr>"); } out.println("</table>");*/ out.println("<input type=hidden id=classInfo style=margin-left:30;width:350 value=" + cInfo.getId() + "></input>"); out.println("<script>var vurl = document.location.protocol + '//' + document.location.host + '/?path=' + document.getElementById('classInfo').value + '#docs'; window.open(vurl);</script>"); } else if ( "remove".equals(command) ) { PropertyInfo idProp = (PropertyInfo) cInfo.getAxiomByName("id"); Object idObj = idProp.fromString(id); FObject targetFobj = dao.find(idObj); if ( targetFobj == null ) { throw new RuntimeException("Unknown ID"); } else { dao.remove(targetFobj); out.println("Success"); } } else { out.println("Unknown command: " + command); } if ( ! "put".equals(command) ) { data = ""; } if ( ! "remove".equals(command) ) { id = ""; } out.println(); } catch (Throwable t) { out.println("Error " + t); out.println("<pre>"); t.printStackTrace(out); out.println("</pre>"); t.printStackTrace(); } } protected void output(X x, String data) { HttpServletRequest req = x.get(HttpServletRequest.class); String [] email = req.getParameterValues("email"); String subject = req.getParameter("subject"); if ( email.length == 0 ) { PrintWriter out = x.get(PrintWriter.class); out.print(data); } else { EmailService emailService = (EmailService) x.get("email"); EmailMessage message = new EmailMessage(); message.setFrom("info@nanopay.net"); message.setReplyTo("noreply@nanopay.net"); message.setTo(email); message.setSubject(subject); String newData = data; message.setBody(newData); emailService.sendEmail(message); } } /** * Gets the result of a failing parsing of a buffer * @param buffer the buffer that failed to be parsed * @return the error message */ protected String getParsingError(X x, String buffer) { //Parser parser = new foam.lib.json.ExprParser(); PStream ps = new StringPStream(); ParserContext psx = new ParserContextImpl(); ((StringPStream) ps).setString(buffer); psx.set("X", x == null ? new ProxyX() : x); ErrorReportingPStream eps = new ErrorReportingPStream(ps); //ps = eps.apply(parser, psx); return eps.getMessage(); } }
package eco.game; import static org.lwjgl.opengl.GL11.GL_ALPHA_TEST; import static org.lwjgl.opengl.GL11.GL_BLEND; import static org.lwjgl.opengl.GL11.GL_DEPTH_BUFFER_BIT; import static org.lwjgl.opengl.GL11.GL_DEPTH_TEST; import static org.lwjgl.opengl.GL11.GL_GREATER; import static org.lwjgl.opengl.GL11.GL_LEQUAL; import static org.lwjgl.opengl.GL11.GL_MODELVIEW; import static org.lwjgl.opengl.GL11.GL_NEAREST; import static org.lwjgl.opengl.GL11.GL_NICEST; import static org.lwjgl.opengl.GL11.GL_ONE_MINUS_SRC_ALPHA; import static org.lwjgl.opengl.GL11.GL_PERSPECTIVE_CORRECTION_HINT; import static org.lwjgl.opengl.GL11.GL_PROJECTION; import static org.lwjgl.opengl.GL11.GL_QUADS; import static org.lwjgl.opengl.GL11.GL_SRC_ALPHA; import static org.lwjgl.opengl.GL11.GL_TEXTURE_2D; import static org.lwjgl.opengl.GL11.glAlphaFunc; import static org.lwjgl.opengl.GL11.glBegin; import static org.lwjgl.opengl.GL11.glBlendFunc; import static org.lwjgl.opengl.GL11.glClear; import static org.lwjgl.opengl.GL11.glClearDepth; import static org.lwjgl.opengl.GL11.glColor3f; import static org.lwjgl.opengl.GL11.glColor4f; import static org.lwjgl.opengl.GL11.glDepthFunc; import static org.lwjgl.opengl.GL11.glDisable; import static org.lwjgl.opengl.GL11.glEnable; import static org.lwjgl.opengl.GL11.glEnd; import static org.lwjgl.opengl.GL11.glHint; import static org.lwjgl.opengl.GL11.glLoadIdentity; import static org.lwjgl.opengl.GL11.glMatrixMode; import static org.lwjgl.opengl.GL11.glOrtho; import static org.lwjgl.opengl.GL11.glPopMatrix; import static org.lwjgl.opengl.GL11.glPushMatrix; import static org.lwjgl.opengl.GL11.glRotatef; import static org.lwjgl.opengl.GL11.glScalef; import static org.lwjgl.opengl.GL11.glTexCoord2f; import static org.lwjgl.opengl.GL11.glTranslatef; import static org.lwjgl.opengl.GL11.glVertex2f; import static org.lwjgl.opengl.GL11.glVertex3f; import static org.lwjgl.opengl.GL11.glViewport; import java.awt.Font; import java.io.IOException; import java.io.InputStream; import java.nio.FloatBuffer; import org.lwjgl.BufferUtils; import org.lwjgl.LWJGLException; import org.lwjgl.opengl.Display; import org.lwjgl.opengl.DisplayMode; import org.lwjgl.opengl.GL11; import org.lwjgl.util.glu.GLU; import org.newdawn.slick.Color; import org.newdawn.slick.TrueTypeFont; import org.newdawn.slick.opengl.TextureLoader; import org.newdawn.slick.util.Log; import org.newdawn.slick.util.ResourceLoader; /** * This class does all the rendering. * * @author phil * */ public class Render{ public static float rot; public static final float rotSpeed = 0.05f; public static volatile boolean shouldRender = true; static TextureAtlas atlas; static TrueTypeFont font; public static final float tilesize = 0.2f; public static volatile boolean mesh = false; public static Camera camera = new Camera(-World.mapsize / 2f * tilesize, -8f, World.mapsize / 2f * tilesize); public static volatile float[] vertexes; public static volatile float[] textures; public static volatile FloatBuffer vertex = null; public static volatile FloatBuffer texture = null; public static volatile int buffersize; public static boolean overhead = false; public static float heightConstant = 0.025f; public static boolean multithreading = false; public static boolean multiThreadStructures = false; public static final Object lock = new Object(); /* Main draw function */ public static void draw() { /* Gets ready to draw */ glClear(GL11.GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadIdentity(); initFrustrum(); GL11.glEnable(GL11.GL_DEPTH_TEST); /* Look through the camera */ camera.look(); /* Bind the textureatlas */ atlas.bind(); int mapsize = World.mapsize; rot += 0.05f; float offset = mapsize * tilesize / 2f; glTranslatef(-offset, 0f, -offset); glRotatef(rot, 0.0f, 1.0f, 0.0f); glTranslatef(offset, 0f, offset); /* Array rendering */ synchronized(lock){ if (multithreading) { if (vertexes != null && textures != null){ vertex = BufferUtils.createFloatBuffer(buffersize); vertex.put(vertexes, 0, buffersize); texture = BufferUtils.createFloatBuffer(buffersize * 2 / 3); texture.put(textures, 0, buffersize * 2 / 3); texture.flip(); vertex.flip(); GL11.glDisableClientState(GL11.GL_NORMAL_ARRAY); GL11.glDisableClientState(GL11.GL_COLOR_ARRAY); GL11.glEnableClientState(GL11.GL_VERTEX_ARRAY); GL11.glEnableClientState(GL11.GL_TEXTURE_COORD_ARRAY); GL11.glVertexPointer(3, 0, vertex); GL11.glTexCoordPointer(2, 0, texture); GL11.glDrawArrays(GL11.GL_QUADS, 0, buffersize / 3); GL11.glDisableClientState(GL11.GL_VERTEX_ARRAY); GL11.glDisableClientState(GL11.GL_TEXTURE_COORD_ARRAY); } } } /* DisplayList rendering */ if (!multithreading || true) { /* Call the display list */ GL11.glCallList(DisplayLists.getIndex()); /* Render structures */ for (int x = 0; x < mapsize; x++) { for (int y = 0; y < mapsize; y++) { if (World.structures[x][y] == 1) { try { World.cities.get(new Point(x, y)).updatePop( (int) World.popdensity[x][y]); drawCity((-x) * tilesize, World.noise[x][y] * heightConstant, (-y) * tilesize, 1, World.cities.get(new Point(x, y))); } catch (Exception e) { World.cities.put(new Point(x, y), new City( new Point(x, y), false)); } } if (World.structures[x][y] == 2) { try { World.cities.get(new Point(x, y)).updatePop( (int) World.popdensity[x][y]); drawCity((-x) * tilesize, World.noise[x][y] * heightConstant, (-y) * tilesize, 2, World.cities.get(new Point(x, y))); } catch (Exception e) { World.cities.put(new Point(x, y), new City( new Point(x, y), true)); } } if (World.structures[x][y] == 4) { try { World.cities.get(new Point(x, y)).updatePop(0); drawCity((-x) * tilesize, World.noise[x][y] * heightConstant, (-y) * tilesize, 2, World.cities.get(new Point(x, y))); } catch (Exception e) { World.cities.put(new Point(x, y), new City( new Point(x, y), true)); } } if (World.structures[x][y] == 3) { drawStructure((-x) * tilesize, World.noise[x][y] * heightConstant, (-y) * tilesize, 10); } if (World.decorations[x][y] == 1){ drawStructure((-x) * tilesize, 48 * heightConstant, (-y) * tilesize, 12); } if (World.decorations[x][y] == 2){ //drawStructure((-x) * tilesize, (Math.max(48,World.noise[x][y] + 20)) // * heightConstant, (-y) * tilesize, 13); //Cloud drawing } if (World.decorations[x][y] == 3){ drawStructure((-x) * tilesize, World.noise[x][y] * heightConstant, (-y) * tilesize, 14); } if (World.decorations[x][y] == 4){ drawStructure((-x) * tilesize, World.noise[x][y] * heightConstant, (-y) * tilesize, 15); } } } } /* Draw city names */ for (int x = 0; x < mapsize; x++) { for (int y = 0; y < mapsize; y++) { try { if (World.structures[x][y] == 1) { drawCityName((-x) * tilesize, World.noise[x][y] * heightConstant, (-y) * tilesize, World.cities.get(new Point(x, y))); } if (World.structures[x][y] == 2) { drawCityName((-x) * tilesize, World.noise[x][y] * heightConstant, (-y) * tilesize, World.cities.get(new Point(x, y))); } } catch (Exception e) { } } } /* Gets ready for orthogonal drawing */ initOrtho(); GL11.glDisable(GL11.GL_DEPTH_TEST); /* Draw the menu bar */ GL11.glDisable(GL11.GL_TEXTURE_2D); glColor3f(169f / 255f, 145f / 255f, 126f / 255f); glBegin(GL_QUADS); glVertex2f(0, Main.height); glVertex2f(Main.width, Main.height); glVertex2f(Main.width, 6f * Main.height / 8f); glVertex2f(0, 6f * Main.height / 8f); glEnd(); glColor3f(1f, 1f, 1f); glColor3f(157f / 255f, 130f / 255f, 117f / 255f); glBegin(GL_QUADS); glVertex2f(10, Main.height - 00); glVertex2f(Main.width - 10, Main.height - 00); glVertex2f(Main.width - 10, (6f * Main.height / 8f) + 10); glVertex2f(10, (6f * Main.height / 8f) + 10); glEnd(); glColor3f(1f, 1f, 1f); glColor3f(169f / 255f, 145f / 255f, 126f / 255f); glBegin(GL_QUADS); glVertex2f(0, (6f * Main.height / 8f)); glVertex2f(20, (6f * Main.height / 8f)); glVertex2f(20, (6f * Main.height / 8f) + 20); glVertex2f(0, (6f * Main.height / 8f) + 20); glEnd(); glColor3f(1f, 1f, 1f); glColor3f(169f / 255f, 145f / 255f, 126f / 255f); glBegin(GL_QUADS); glVertex2f(Main.width, (6f * Main.height / 8f)); glVertex2f(Main.width - 20, (6f * Main.height / 8f)); glVertex2f(Main.width - 20, (6f * Main.height / 8f) + 20); glVertex2f(Main.width, (6f * Main.height / 8f) + 20); glEnd(); glColor3f(1f, 1f, 1f); GL11.glEnable(GL11.GL_TEXTURE_2D); UIManager.render(); UIManager.render2(); /* Draw all the messages */ for (Message message : Message.getMessages()) { Render.drawString(message.getMessage(), message.getX(), message.getY()); } } /* Draw the main menu */ public static void drawMainMenu() { /* Get ready to draw */ glClear(GL11.GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadIdentity(); initOrtho(); /* Colors */ Treble<Float, Float, Float> backColor = Util .convertColor(new Treble<Float, Float, Float>(157f, 130f, 117f)); Treble<Float, Float, Float> borderColor = Util .convertColor(new Treble<Float, Float, Float>(169f, 145f, 126f)); /* Draw the background */ glDisable(GL11.GL_TEXTURE_2D); glColor3f(borderColor.getX(), borderColor.getY(), borderColor.getZ()); glBegin(GL_QUADS); glVertex2f(0, 0); glVertex2f(0, Main.height); glVertex2f(Main.width, Main.height); glVertex2f(Main.width, 0); glEnd(); glColor3f(backColor.getX(), backColor.getY(), backColor.getZ()); glBegin(GL_QUADS); glVertex2f(10, 10); glVertex2f(10, Main.height - 10); glVertex2f(Main.width - 10, Main.height - 10); glVertex2f(Main.width - 10, 10); glEnd(); glColor3f(borderColor.getX(), borderColor.getY(), borderColor.getZ()); glBegin(GL_QUADS); glVertex2f(0, 0); glVertex2f(20, 0); glVertex2f(20, 20); glVertex2f(0, 20); glVertex2f(Main.width, 0); glVertex2f(Main.width - 20, 0); glVertex2f(Main.width - 20, 20); glVertex2f(Main.width, 20); glVertex2f(0, Main.height); glVertex2f(20, Main.height); glVertex2f(20, Main.height - 20); glVertex2f(0, Main.height - 20); glVertex2f(Main.width, Main.height); glVertex2f(Main.width - 20, Main.height); glVertex2f(Main.width - 20, Main.height - 20); glVertex2f(Main.width, Main.height - 20); glEnd(); glColor3f(1f, 1f, 1f); glEnable(GL11.GL_TEXTURE_2D); float centx = Main.width / 2f; float size = 128; float pad = 0; /* Bind the textures */ atlas.getTexture().bind(); /* Draw the title */ glBegin(GL_QUADS); glTexCoord2f(atlas.getCoord(0, false), atlas.getCoord(4, false)); glVertex2f(centx - (size / 2) - size - pad, 30); glTexCoord2f(atlas.getCoord(0, true), atlas.getCoord(4, false)); glVertex2f(centx + (size / 2) - size - pad, 30); glTexCoord2f(atlas.getCoord(0, true), atlas.getCoord(4, true)); glVertex2f(centx + (size / 2) - size - pad, 30 + size); glTexCoord2f(atlas.getCoord(0, false), atlas.getCoord(4, true)); glVertex2f(centx - (size / 2) - size - pad, 30 + size); glTexCoord2f(atlas.getCoord(1, false), atlas.getCoord(4, false)); glVertex2f(centx - (size / 2), 30); glTexCoord2f(atlas.getCoord(1, true), atlas.getCoord(4, false)); glVertex2f(centx + (size / 2), 30); glTexCoord2f(atlas.getCoord(1, true), atlas.getCoord(4, true)); glVertex2f(centx + (size / 2), 30 + size); glTexCoord2f(atlas.getCoord(1, false), atlas.getCoord(4, true)); glVertex2f(centx - (size / 2), 30 + size); glTexCoord2f(atlas.getCoord(2, false), atlas.getCoord(4, false)); glVertex2f(centx - (size / 2) + size + pad, 30); glTexCoord2f(atlas.getCoord(2, true), atlas.getCoord(4, false)); glVertex2f(centx + (size / 2) + size + pad, 30); glTexCoord2f(atlas.getCoord(2, true), atlas.getCoord(4, true)); glVertex2f(centx + (size / 2) + size + pad, 30 + size); glTexCoord2f(atlas.getCoord(2, false), atlas.getCoord(4, true)); glVertex2f(centx - (size / 2) + size + pad, 30 + size); glEnd(); glColor3f(1.0f, 1.0f, 1.0f); /* Draw the buttons */ UIManager.renderMenu(); /* Draw all the text */ UIManager.renderMenu2(); drawString("Generation Settings", ((Main.width / 2) + 280), 224); /* Draw all the messages */ for (Message message : Message.getMessages()) { Render.drawString(message.getMessage(), message.getX(), message.getY()); } } /* Draw a structure that faces the camera */ public static void drawStructure(float x, float y, float z, int texpos) { glPushMatrix(); float offset = (tilesize / 2); int tex = texpos % 8; int tey = texpos / 8; glTranslatef(x, 0, z); glRotatef(-rot, 0f, 1f, 0f); glTranslatef(-x, 0, -z); glBegin(GL_QUADS); glTexCoord2f(atlas.getCoord(tex, false), atlas.getCoord(tey, false)); glVertex3f(x - offset, y + offset * 2, z); glTexCoord2f(atlas.getCoord(tex, true), atlas.getCoord(tey, false)); glVertex3f(x + offset, y + offset * 2, z); glTexCoord2f(atlas.getCoord(tex, true), atlas.getCoord(tey, true)); glVertex3f(x + offset, y, z); glTexCoord2f(atlas.getCoord(tex, false), atlas.getCoord(tey, true)); glVertex3f(x - offset, y, z); glEnd(); glPopMatrix(); } /* Draw a city structure */ public static void drawCity(float x, float y, float z, int type, City city) { glPushMatrix(); int texpos = 0; int texpos2 = 0; if (type == 1) { texpos = 8; texpos2 = 11; } if (type == 2) { texpos = 9; texpos2 = 25; } float offset = (tilesize / 8); int tex = texpos % 8; int tey = texpos / 8; int tex2 = texpos2 % 8; int tey2 = texpos2 / 8; int texposr = 15; int texr = texposr % 8; int teyr = texposr / 8; for (int i = 0; i < 4; i++) { for (int k = 0; k < 4; k++) { float tempx = x + ((i * offset) * 2.0f) - (offset * 3.0f); float tempz = z + ((k * offset) * 2.0f) - (offset * 3.0f); float centx = x + ((i * offset) * 2.0f) - (offset * 3.0f); float centz = z + ((k * offset) * 2.0f) - (offset * 3.0f); glPushMatrix(); glTranslatef(centx, 0, centz); glRotatef(-rot, 0f, 1f, 0f); glTranslatef(-centx, 0, -centz); if (city.getBuilding(i, k) == 1) { glBegin(GL_QUADS); glTexCoord2f(atlas.getCoord(tex, false), atlas.getCoord(tey, false)); glVertex3f(tempx - offset, y + offset * 4, tempz); glTexCoord2f(atlas.getCoord(tex, true), atlas.getCoord(tey, false)); glVertex3f(tempx + offset, y + offset * 4, tempz); glTexCoord2f(atlas.getCoord(tex, true), atlas.getCoord(tey, true)); glVertex3f(tempx + offset, y, tempz); glTexCoord2f(atlas.getCoord(tex, false), atlas.getCoord(tey, true)); glVertex3f(tempx - offset, y, tempz); glEnd(); } else if (city.getBuilding(i, k) == 2) { glBegin(GL_QUADS); glTexCoord2f(atlas.getCoord(tex2, false), atlas.getCoord(tey2, false)); glVertex3f(tempx - offset, y + offset * 4, tempz); glTexCoord2f(atlas.getCoord(tex2, true), atlas.getCoord(tey2, false)); glVertex3f(tempx + offset, y + offset * 4, tempz); glTexCoord2f(atlas.getCoord(tex2, true), atlas.getCoord(tey2, true)); glVertex3f(tempx + offset, y, tempz); glTexCoord2f(atlas.getCoord(tex2, false), atlas.getCoord(tey2, true)); glVertex3f(tempx - offset, y, tempz); glEnd(); } else if (city.getBuilding(i, k) == -1){ glBegin(GL_QUADS); glTexCoord2f(atlas.getCoord(texr, false), atlas.getCoord(teyr, false)); glVertex3f(tempx - offset, y + offset * 4, tempz); glTexCoord2f(atlas.getCoord(texr, true), atlas.getCoord(teyr, false)); glVertex3f(tempx + offset, y + offset * 4, tempz); glTexCoord2f(atlas.getCoord(texr, true), atlas.getCoord(teyr, true)); glVertex3f(tempx + offset, y, tempz); glTexCoord2f(atlas.getCoord(texr, false), atlas.getCoord(teyr, true)); glVertex3f(tempx - offset, y, tempz); glEnd(); } glPopMatrix(); } } glPopMatrix(); } /* Draw a city nameplate */ public static void drawCityName(float x, float y, float z, City city) { String name = city.getName(); if (name.equals("")) { return; } GL11.glShadeModel(GL11.GL_FLAT); GL11.glDisable(GL11.GL_DEPTH_TEST); GL11.glDisable(GL11.GL_CULL_FACE); GL11.glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); GL11.glDisable(GL11.GL_ALPHA_TEST); GL11.glDepthMask(false); glPushMatrix(); int width = font.getWidth(city.getName()); width /= 2f; int height = font.getHeight(city.getName()); height /= 2; float size = 0.005f; glTranslatef(0, 0, z); glScalef(size, -size, size); float xpos = (x * (1f / size)) - 0; float ypos = y * (-1f / size) - 50; glTranslatef(xpos, ypos, 0); glRotatef(-rot, 0f, 1f, 0f); glTranslatef(-xpos, -ypos, 0); if (city.getName().contains(City.capitalEpithet)) { glColor3f(173f / 255f, 93f / 255f, 93f / 255f); font.drawString((x * (1f / size)) - width, y * (-1f / size) - 50, city.getName(), new Color(245f / 255f, 63f / 255f, 63f / 255f, 2f)); } else { font.drawString((x * (1f / size)) - width, y * (-1f / size) - 50, city.getName(), new Color(1f, 1f, 1f, 2f)); } glDisable(GL11.GL_TEXTURE_2D); glBegin(GL_QUADS); glTranslatef(0, 0, z - 1); glColor4f(0f, 0f, 0f, 0.25f); glVertex2f(xpos - width, ypos - height + 6); glVertex2f(xpos + width, ypos - height + 6); glVertex2f(xpos + width, ypos + height + 6); glVertex2f(xpos - width, ypos + height + 6); glEnd(); glColor4f(1f, 1f, 1f, 1f); glEnable(GL11.GL_TEXTURE_2D); GL11.glEnable(GL11.GL_DEPTH_TEST); GL11.glDepthMask(true); GL11.glEnable(GL11.GL_ALPHA_TEST); glPopMatrix(); } /* Draw a string */ public static void drawString(String message, float x, float y) { font.drawString(x, y, message); } /* Draw the paused overlay */ public static void drawPaused() { glLoadIdentity(); initOrtho(); float centerX = Display.getWidth() / 2f; float centerY = Display.getHeight() / 2f; float textWidth = font.getWidth("Paused") / 2f; float textHeight = font.getHeight("Paused") / 2f; Treble<Float, Float, Float> pauseColor = Util .convertColor(new Treble<Float, Float, Float>(186f, 179f, 178f)); glDisable(GL11.GL_TEXTURE_2D); glBegin(GL_QUADS); glColor4f(pauseColor.getX(), pauseColor.getY(), pauseColor.getZ(), 0.05f); glVertex2f(0f, 0f); glVertex2f(Display.getWidth(), 0f); glVertex2f(Display.getWidth(), Display.getHeight()); glVertex2f(0f, Display.getHeight()); glEnd(); glColor4f(1f, 1f, 1f, 1f); glEnable(GL11.GL_TEXTURE_2D); glDisable(GL_DEPTH_TEST); font.drawString(centerX - textWidth, centerY - textHeight, "Paused"); glEnable(GL_DEPTH_TEST); } /* Draw the gameover overlay */ public static void drawGameOver(String reason) { float centerX = Display.getWidth() / 2f; float centerY = Display.getHeight() / 2f; float textWidth = font.getWidth("Game Over") / 2f; float textHeight = font.getHeight("Game Over") / 2f; float textWidth2 = font.getWidth(reason) / 2f; Treble<Float, Float, Float> pauseColor = Util .convertColor(new Treble<Float, Float, Float>(168f, 78f, 78f)); glDisable(GL11.GL_TEXTURE_2D); glBegin(GL_QUADS); glColor4f(pauseColor.getX(), pauseColor.getY(), pauseColor.getZ(), 0.15f); glVertex2f(0f, 0f); glVertex2f(Display.getWidth(), 0f); glVertex2f(Display.getWidth(), Display.getHeight()); glVertex2f(0f, Display.getHeight()); glEnd(); glColor4f(1f, 1f, 1f, 1f); glEnable(GL11.GL_TEXTURE_2D); glDisable(GL_DEPTH_TEST); font.drawString(centerX - textWidth, centerY - textHeight, "Game Over"); font.drawString(centerX - textWidth2, centerY - textHeight + 30, reason); glEnable(GL_DEPTH_TEST); } /* Creates the display */ public static void initDisplay() { try { Display.setDisplayMode(new DisplayMode(Main.width, Main.height)); } catch (LWJGLException e) { e.printStackTrace(); } Display.setTitle("Eco " + Main.vn); try { Display.create(); } catch (LWJGLException e) { e.printStackTrace(); } Display.setVSyncEnabled(true); } /* Creates the openGl context */ public static void init() { Log.setVerbose(false); /* Creates textureatlas */ try { if (Main.isInEclipse) { atlas = new TextureAtlas( TextureLoader.getTexture( "PNG", ResourceLoader .getResourceAsStream("assets/textureatlas.png"), GL_NEAREST)); } else { atlas = new TextureAtlas( TextureLoader.getTexture( "PNG", ResourceLoader .getResourceAsStream("../assets/textureatlas.png"), GL_NEAREST)); } } catch (IOException e) { e.printStackTrace(); } /* Creates the icon */ try { /* * Display.setIcon(new ByteBuffer[] { new ImageIOImageData() * .imageToByteBuffer( ImageIO.read(new File("../assets/icon.png")), * false, false, null) }); */ } catch (Exception e) { e.printStackTrace(); } atlas.getTexture().bind(); glEnable(GL_TEXTURE_2D); glEnable(GL_DEPTH_TEST); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_ALPHA_TEST); glAlphaFunc(GL_GREATER, 0.0f); glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); GL11.glTexParameteri(GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL11.GL_REPEAT); GL11.glTexParameteri(GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL11.GL_REPEAT); initFrustrum(); GL11.glClearColor(152f / 255f, 242f / 255f, 255f / 255f, 1.0f); /* Creates the font */ try { InputStream inputStream; if (Main.isInEclipse) { inputStream = ResourceLoader .getResourceAsStream("assets/font.ttf"); } else { inputStream = ResourceLoader .getResourceAsStream("../assets/font.ttf"); } Font awtFont = Font.createFont(Font.TRUETYPE_FONT, inputStream); awtFont = awtFont.deriveFont(16f); // set font size font = new TrueTypeFont(awtFont, true); } catch (Exception e) { e.printStackTrace(); } DisplayLists.init(); } /* Creates a frustrum projection */ public static void initFrustrum() { glMatrixMode(GL_PROJECTION); glLoadIdentity(); GLU.gluPerspective(Main.fov / 2f, Main.windowwidth / Main.windowheight, 0.1f, 100000000000000f); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); glEnable(GL_BLEND); } /* Creates an orthogonal projection */ public static void initOrtho() { glClearDepth(1); glViewport(0, 0, Display.getWidth(), Display.getHeight()); glMatrixMode(GL_MODELVIEW); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0, Main.width, Main.height, 0, 1, -1); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } }
package test; import org.junit.Before; import org.junit.Test; import org.junit.Assert; import core.Field; public class FieldTest extends Assert { private Field field; @Before public void setUp() throws Exception { for (Field.StartCellStyle scs : Field.StartCellStyle.values()) { field = new Field(-1, -1, '*', scs); assertEquals(Field.getMinWidth(), field.getWidthCount()); assertEquals(Field.getMinHeight(), field.getHeightCount()); field = new Field(-1, Field.getMinHeight(), '?', scs); assertEquals(Field.getMinWidth(), field.getWidthCount()); assertEquals(Field.getMinHeight(), field.getHeightCount()); field = new Field(Field.getMinWidth(), -1, '@', scs); assertEquals(Field.getMinWidth(), field.getWidthCount()); assertEquals(Field.getMinHeight(), field.getHeightCount()); field = new Field(128, 128, '!', scs); assertEquals(Field.getMaxWidth(), field.getWidthCount()); assertEquals(Field.getMaxHeight(), field.getHeightCount()); field = new Field(128, Field.getMaxHeight(), '#', scs); assertEquals(Field.getMaxWidth(), field.getWidthCount()); assertEquals(Field.getMaxHeight(), field.getHeightCount()); field = new Field(Field.getMaxWidth(), 128, '$', scs); assertEquals(Field.getMaxWidth(), field.getWidthCount()); assertEquals(Field.getMaxHeight(), field.getHeightCount()); field = new Field(3, 4, '%', scs); assertEquals(3, field.getWidthCount()); assertEquals(4, field.getHeightCount()); } } @Test public void setCell() { assertFalse(field.setCell(0, 0, 'X')); assertFalse(field.setCell(0, 0, Field.getDefFigureValue())); assertFalse(field.setCell(1, 0, Field.getDefFigureValue())); assertFalse(field.setCell(0, 1, Field.getDefFigureValue())); assertFalse(field.setCell(field.getWidthCount() + 1, field.getHeightCount() + 1, 'O')); assertFalse(field.setCell(field.getWidthCount() + 1, field.getHeightCount() + 1, Field.getDefFigureValue())); assertFalse(field.setCell(field.getWidthCount(), field.getHeightCount() + 1, Field.getDefFigureValue())); assertFalse(field.setCell(field.getWidthCount() + 1, field.getHeightCount(), Field.getDefFigureValue())); for (Field.StartCellStyle scs : Field.StartCellStyle.values()) { field = new Field(5, 16, ' ', scs); for (int i = 1; i <= field.getWidthCount(); i++) { for (int j = 1; j <= field.getHeightCount(); j++) { assertTrue(field.setCell(i, j, 'X')); assertFalse(field.setCell(i, j, 'O')); assertTrue(field.setCell(i, j, Field.getDefFigureValue())); assertTrue(field.setCell(i, j, 'O')); assertTrue(field.setCell(i, j, Field.getDefFigureValue())); } } } for (Field.StartCellStyle scs : Field.StartCellStyle.values()) { field = new Field(12, 4, ' ', scs); for (int i = field.getWidthCount(); i > 0; i for (int j = field.getHeightCount(); j > 0; j assertTrue(field.setCell(i, j, 'X')); assertFalse(field.setCell(i, j, 'O')); assertTrue(field.setCell(i, j, Field.getDefFigureValue())); assertTrue(field.setCell(i, j, 'O')); assertTrue(field.setCell(i, j, Field.getDefFigureValue())); } } } String checkString[] = {"[1][2]\n[3][4]\n[5][6]\n", "[2][1]\n[4][3]\n[6][5]\n", "[6][5]\n[4][3]\n[2][1]\n", "[5][6]\n[3][4]\n[1][2]\n"}; int stringNum = 0; for (Field.StartCellStyle scs : Field.StartCellStyle.values()) { field = new Field(3, 2, ' ', scs); Integer numToCell = 1; for (int i = 1; i <= field.getWidthCount(); i++) { for (int j = 1; j <= field.getHeightCount(); j++) { field.setCell(i, j, (numToCell++).toString().charAt(0)); } } assertEquals(checkString[stringNum++], field.toString()); } assertFalse(field.setCell(field.getWidthCount() + 1, field.getHeightCount() + 1, Field.getDefFigureValue())); assertFalse(field.setCell(field.getWidthCount(), field.getHeightCount() + 1, Field.getDefFigureValue())); assertFalse(field.setCell(field.getWidthCount() + 1, field.getHeightCount(), Field.getDefFigureValue())); assertFalse(field.setCell(0, 0, Field.getDefFigureValue())); assertFalse(field.setCell(1, 0, Field.getDefFigureValue())); assertFalse(field.setCell(0, 1, Field.getDefFigureValue())); } }
package example; import ethanjones.cubes.block.Block; public class MyBlock extends Block { public MyBlock() { super("MyMod:block/texture"); } }
package jade.content.onto; import java.util.Hashtable; import java.util.Date; import jade.content.Term; import jade.content.abs.AbsObject; import jade.content.schema.ObjectSchema; import jade.util.leap.List; import jade.util.leap.Iterator; import jade.util.leap.Serializable; import jade.util.Logger; import jade.core.CaseInsensitiveString; /** * An application-specific ontology describes the elements that agents * can use within content of messages. It defines a vocabulary and * relationships between the elements in such a vocabulary. * The relationships can be: * <ul> * <li>structural, e.g., the predicate <code>fatherOf</code> accepts two * parameters, a father and a set of children; * <li>semantic, e.g., a concept of class <code>Man</code> is also of class * <code>Person</code>. * </ul> * Application-specific ontologies are implemented through objects * of class <code>Ontology</code>.<br> * An ontology is characterized by: * <ul> * <li>one name; * <li>one (or more) base ontology that it extends; * <li>a set of <i>element schemas</i>. * </ul> * Element schemas are objects describing the structure of concepts, actions, * and predicates. that are allowed in messages. For example, * <code>People</code> ontology contains an element schema called * <code>Person</code>. This schema states that a <code>Person</code> is * characterized by a <code>name</code> and by an <code>address</code>: * <code> * ConceptSchema personSchema = new ConceptSchema(PERSON); * personSchema.addSlot(NAME, stringSchema); * personSchema.addSlot(ADDRESS, addressSchema, ObjectSchema.OPTIONAL); * </code> * where <code>PERSON<code>, <code>NAME</code> and <code>ADDRESS</code> are * string constants. When you register your schema with the ontology, such * constants become part of the vocabulary of the ontology.<br> * Schemas that describe concepts support inheritance. You can define the * concept <code>Man</code> as a refinement of the concept <code>Person</code>: * <code> * ConceptSchema manSchema = new ConceptSchema(MAN); * manSchema.addSuperSchema(personSchema); * </code> * Each element schema can be associated with a Java class to map elements of * the ontology that comply with a schema with Java objects of that class. The * following is a class that might be associated with the <code>Person</code> * schema: * <code> * public class Person extends Concept { * private String name = null; * private Address address = null; * * public void setName(String name) { * this.name = name; * } * * public void setAddress(Address address) { * this.address = address; * } * * public String getName() { * return name; * } * * public Address getAddress() { * return address; * } * } * </code> * When sending/receiving messages you can represent your content in terms of * objects belonging to classes that the ontology associates with schemas.<br> * As the previous example suggests, you cannot use objects of class * <code>Person</code> when asking for the value of some attribute, e.g., when * asking for the value of <code>address</code>. Basically, the problem is that * you cannot 'assign' a variable to an attribute of an object, i.e. * you cannot write something like: * <code>person.setName(new Variable("X"))</code>.<br> * In order to solve this problem, you can describe your content in terms of * <i>abstract descriptors</i>. An abstract descriptor is an * object that reifies an element of the ontology. * The following is the creation of an abstract * descriptor for a concept of type <code>Man</code>: * <code> * AbsConcept absMan = new AbsConcept(MAN); * absMan.setSlot(NAME, "John"); * absMan.setSlot(ADDRESS, absAddress); * </code> * where <code>absAddress</code> is the abstract descriptor for John's * address: * <code> * AbsConcept absAddress = new AbsConcept(ADDRESS); * absAddress.setSlot(CITY, "London"); * </code> * Objects of class <code>Ontology</code> allows you to: * <ul> * <li>register schemas with associated (i) a mandatory term of the * vocabulary e.g. <code>NAME</code> and (ii) an optional Java class, * e.g. <code>Person</code>; * <li>retrieve the registered information through various keys. * </ul> * The framework already provides the <code>BasicOntology</code> ontology * that provides all basic elements, i.e. primitive data types, aggregate * types, etc. * Application-specific ontologies should be implemented extending it. * @see jade.content.Concept * @see jade.content.abs.AbsConcept * @see jade.content.schema.ConceptSchema * @see jade.content.onto.BasicOntology * @author Federico Bergenti - Universita` di Parma * @author Giovanni Caire - TILAB */ public class Ontology implements Serializable { private static final String DEFAULT_INTROSPECTOR_CLASS = "jade.content.onto.ReflectiveIntrospector"; private Ontology[] base = new Ontology[0]; private String name = null; private Introspector introspector = null; private Hashtable elements = new Hashtable(); // Maps type-names to schemas private Hashtable classes = new Hashtable(); // Maps type-names to java classes private Hashtable schemas = new Hashtable(); // Maps java classes to schemas private Logger logger = Logger.getMyLogger(this.getClass().getName()); // This is required for compatibility with CLDC MIDP where XXX.class // is not supported private static Class absObjectClass = null; static { try { absObjectClass = Class.forName("jade.content.abs.AbsObject"); } catch (Exception e) { // Should never happen e.printStackTrace(); } } /** * Construct an Ontology object with a given <code>name</code> * that extends a given ontology. * The <code>ReflectiveIntrospector</code> is used by default to * convert between Java objects and abstract descriptors. * @param name The identifier of the ontology. * @param base The base ontology. */ public Ontology(String name, Ontology base) { this(name, base, null); try { introspector = (Introspector) Class.forName(DEFAULT_INTROSPECTOR_CLASS).newInstance(); } catch (Exception e) { throw new RuntimeException("Class "+DEFAULT_INTROSPECTOR_CLASS+"for default Introspector not found"); } } /** * Construct an Ontology object with a given <code>name</code> * that uses a given Introspector to * convert between Java objects and abstract descriptors. * @param name The identifier of the ontology. * @param introspector The introspector. */ public Ontology(String name, Introspector introspector) { this(name, new Ontology[0], introspector); } /** * Construct an Ontology object with a given <code>name</code> * that extends a given ontology and that uses a given Introspector to * convert between Java objects and abstract descriptors. * @param name The identifier of the ontology. * @param base The base ontology. * @param introspector The introspector. */ public Ontology(String name, Ontology base, Introspector introspector) { this(name, (base != null ? new Ontology[]{base} : new Ontology[0]), introspector); } /** * Construct an Ontology object with a given <code>name</code> * that extends a given set of ontologies and that uses a given Introspector to * convert between Java objects and abstract descriptors. * @param name The identifier of the ontology. * @param base The base ontology. * @param introspector The introspector. */ public Ontology(String name, Ontology[] base, Introspector introspector) { this.name = name; this.introspector = introspector; this.base = (base != null ? base : new Ontology[0]); } /** * Retrieves the name of this ontology. * @return the name of this ontology. */ public String getName() { return name; } /** * Adds a schema to this ontology * @param schema The schema to add * @throws OntologyException */ public void add(ObjectSchema schema) throws OntologyException { add(schema, null); } /** * Adds a schema to the ontology and associates it to the class * <code>javaClass</code> * @param schema the schema. * @param javaClass the concrete class. * @throws OntologyException */ public void add(ObjectSchema schema, Class javaClass) throws OntologyException { if (schema.getTypeName() == null) { throw new OntologyException("Invalid schema identifier"); } String s = schema.getTypeName().toLowerCase(); elements.put(s, schema); if (javaClass != null) { classes.put(s, javaClass); if (!absObjectClass.isAssignableFrom(javaClass)) { if (introspector != null) { introspector.checkClass(schema, javaClass, this); } schemas.put(javaClass, schema); } else { // If the java class is an abstract descriptor check the // coherence between the schema and the abstract descriptor if (!javaClass.isInstance(schema.newInstance())) { throw new OntologyException("Java class "+javaClass.getName()+" can't represent instances of schema "+schema); } } } } /** * Retrieves the schema of element <code>name</code> in this ontology. * The search is extended to the base ontologies if the schema is not * found. * @param name the name of the schema in the vocabulary. * @return the schema or <code>null</code> if the schema is not found. * @throws OntologyException */ public ObjectSchema getSchema(String name) throws OntologyException { if (name == null) { throw new OntologyException("Null schema identifier"); } ObjectSchema ret = (ObjectSchema) elements.get(name.toLowerCase()); if (ret == null) { logger.log(Logger.WARNING,"Ontology "+getName()+". Schema for "+name+" not found"); for (int i = 0; i < base.length; ++i) { if (base[i] == null) { logger.log(Logger.WARNING,"Base ontology # "+i+" for ontology "+getName()+" is null"); } ret = base[i].getSchema(name); if (ret != null) { return ret; } } } return ret; } /** * Converts an abstract descriptor to a Java object of the proper class. * @param abs the abstract descriptor. * @return the object * @throws UngroundedException if the abstract descriptor contains a * variable * @throws OntologyException if some mismatch with the schema is found * @see #fromObject(Object) */ public Object toObject(AbsObject abs) throws OntologyException, UngroundedException { if (abs == null) { return null; } try { return toObject(abs, abs.getTypeName().toLowerCase(), this); } catch (UnknownSchemaException use) { // If we get this exception here, the schema is globally unknown // (i.e. is unknown in the reference ontology and all its base // ontologies) --> throw a generic OntologyException throw new OntologyException("No schema found for type "+abs.getTypeName()); } catch (OntologyException oe) { // This ontology can have been thrown as the Abs descriptor is // ungrounded. In this case an UngroundedException must be thrown. // Note that we don't check ungrouding before to speed up performances if (!abs.isGrounded()) { throw new UngroundedException(); } else { throw oe; } } } /** * Converts a Java object into a proper abstract descriptor. * @param obj the object * @return the abstract descriptor. * @throws OntologyException if some mismatch with the schema is found * @see #toObject(AbsObject) */ public AbsObject fromObject(Object obj) throws OntologyException { if (obj == null) { return null; } try { return fromObject(obj, this); } catch (UnknownSchemaException use) { // If we get this exception here, the schema is globally unknown // (i.e. is unknown in the reference ontology and all its base // ontologies) --> throw a generic OntologyException throw new OntologyException("No schema found for class "+obj.getClass().getName()); } } /** * Retrieves the concrete class associated with element <code>name</code> * in this ontology. The search is extended to the base ontologies * @param name the name of the schema. * @return the Java class or null if no schema called <code>name</code> * is found or if no class is associated to that schema. * @throws OntologyException if name is null */ public Class getClassForElement(String name) throws OntologyException { if (name == null) { throw new OntologyException("Null schema identifier"); } Class ret = (Class) classes.get(name.toLowerCase()); if (ret == null) { for (int i = 0; i < base.length; ++i) { ret = base[i].getClassForElement(name); if (ret != null) { return ret; } } } return ret; } //#APIDOC_EXCLUDE_BEGIN /** * Converts an abstract descriptor to a Java object of the proper class. * @param abs the abstract descriptor. * @param lcType the type of the abstract descriptor to be translated * aconverted into lower case. This is passed as parameters to avoid * making the conversion to lower case for each base ontology. * @param globalOnto The ontology this ontology is part of (i.e. the * ontology that extends this ontology). * @return the object * @throws UnknownSchemaException If no schema for the abs descriptor * to be translated is defined in this ontology. * @throws UngroundedException if the abstract descriptor contains a * variable * @throws OntologyException if some mismatch with the schema is found * ontology. In this case UnknownSchema */ protected Object toObject(AbsObject abs, String lcType, Ontology globalOnto) throws UnknownSchemaException, UngroundedException, OntologyException { logger.log(Logger.CONFIG,"Ontology "+getName()+". Abs is: "+abs); // Retrieve the schema ObjectSchema schema = (ObjectSchema) elements.get(lcType); logger.log(Logger.CONFIG,"Ontology "+getName()+". Schema is: "+schema); if (schema != null) { // Retrieve the java class Class javaClass = (Class) classes.get(lcType); if (javaClass == null) { throw new OntologyException("No java class associated to type "+abs.getTypeName()); } logger.log(Logger.FINE,"Ontology "+getName()+". Class is: "+javaClass.getName()); // If the Java class is an Abstract descriptor --> just return abs if (absObjectClass.isAssignableFrom(javaClass)) { return abs; } if (introspector != null) { logger.log(Logger.FINE,"Ontology "+getName()+". Try to internalise "+abs+" through "+introspector); return introspector.internalise(abs, schema, javaClass, globalOnto); } } // If we get here --> This ontology is not able to translate abs // --> Try to convert it using the base ontologies for (int i = 0; i < base.length; ++i) { try { return base[i].toObject(abs, lcType, globalOnto); } catch (UnknownSchemaException use) { // Try the next one } } throw new UnknownSchemaException(); } /** * Converts a Java object into a proper abstract descriptor. * @param obj the object * @param globalOnto The ontology this ontology is part of (i.e. the * ontology that extends this ontology). * @return the abstract descriptor. * @throws UnknownSchemaException If no schema for the object to be * translated is defined in this ontology. * @throws OntologyException if some mismatch with the schema is found */ protected AbsObject fromObject(Object obj, Ontology globalOnto) throws UnknownSchemaException, OntologyException { // If obj is already an abstract descriptor --> just return it if (obj instanceof AbsObject) { return (AbsObject) obj; } // Retrieve the Java class Class javaClass = obj.getClass(); logger.log(Logger.FINE,"Ontology "+getName()+". Class is: "+javaClass); // Retrieve the schema ObjectSchema schema = (ObjectSchema) schemas.get(javaClass); logger.log(Logger.FINE,"Ontology "+getName()+". Schema is: "+schema); if (schema != null) { if (introspector != null) { logger.log(Logger.FINE,"Ontology "+getName()+". Try to externalise "+obj+" through "+introspector); return introspector.externalise(obj, schema, javaClass, globalOnto); } } // If we get here --> This ontology is not able to translate obj // --> Try to convert it using the base ontologies for (int i = 0; i < base.length; ++i) { try { return base[i].fromObject(obj, globalOnto); } catch (UnknownSchemaException use) { // Try the next one } } throw new UnknownSchemaException(); } //#APIDOC_EXCLUDE_END // Utility static methods /** * Check whether a given object is a valid term. * If it is an Aggregate (i.e. a <code>List</code>) it also check * the elements. * @throws OntologyException if the given object is not a valid term */ public static void checkIsTerm(Object obj) throws OntologyException { if (obj instanceof String || obj instanceof Boolean || obj instanceof Integer || obj instanceof Long || //#MIDP_EXCLUDE_BEGIN obj instanceof Float || obj instanceof Double || //#MIDP_EXCLUDE_END obj instanceof Date || obj instanceof Term) { return; } if (obj instanceof List) { Iterator it = ((List) obj).iterator(); while (it.hasNext()) { checkIsTerm(it.next()); } return; } // If we reach this point the object is not a term throw new OntologyException("Object "+obj+" of class "+obj.getClass().getName()+" is not a term"); } }
package jade.util; //__CLDC_UNSUPPORTED__BEGIN import java.io.PrintStream; import java.io.PrintWriter; //__CLDC_UNSUPPORTED__END /** This class acts as a base class for all the exceptions that wrap another (nested) exception. The typical usage for descendents of this class is to throw them within the <code>catch</code> block for their nested exception. @author Giovanni Rimassa - Universita` di Parma @version $Date$ $Revision$ */ public abstract class WrapperException extends Exception { private String message; private Throwable nested; protected WrapperException(String m, Throwable t) { message = m; nested = t; } protected WrapperException(String m) { message = m; } public String getMessage() { if((nested != null)) { return message + " [nested message is: " + nested.getMessage() + "]"; } return message; } //__CLDC_UNSUPPORTED__BEGIN public void printStackTrace() { printStackTrace(System.err); } public void printStackTrace(PrintStream s) { PrintWriter pw = new PrintWriter(s); printStackTrace(pw); } public void printStackTrace(PrintWriter s) { super.printStackTrace(s); if(nested != null) { s.println("Nested Exception is:"); nested.printStackTrace(s); } } //__CLDC_UNSUPPORTED__END /** Reads the exception wrapped by this object. @return the <code>Throwable</code> object that is the exception thrown by the concrete MTP subsystem. */ public Throwable getNested() { return nested; } }
package joshua.server; import java.net.*; import java.io.*; import joshua.decoder.ArgsParser; import joshua.decoder.Decoder; public class JoshuaServer { public static void main(String[] args) throws IOException { ArgsParser cliArgs = new ArgsParser(args); Decoder decoder = new Decoder(cliArgs.getConfigFile()); ServerSocket serverSocket = null; boolean listening = true; try { serverSocket = new ServerSocket(8182); } catch (IOException e) { System.err.println("Could not listen on port: 8182."); System.exit(-1); } System.err.println("** Server running and listening on port 8182."); while (listening) new JoshuaServerThread(serverSocket.accept(), decoder).start(); serverSocket.close(); } }
package fini.main; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.stream.Collectors; import fini.main.model.FiniParser; import fini.main.model.StatusSaver; import fini.main.model.Storage; import fini.main.model.Task; import fini.main.model.FiniParser.CommandType; import fini.main.util.Sorter; import fini.main.view.RootController; import javafx.collections.FXCollections; import javafx.collections.ObservableList; /** * A Half-damaged Brain * @author gaieepo */ public class Brain { private static Brain brain; private RootController rootController; private Storage taskOrganiser; private FiniParser finiParser; private Sorter sorter; private StatusSaver statusSaver; private ArrayList<Task> taskMasterList; private ObservableList<Task> taskObservableList = FXCollections.observableArrayList(); private Brain() { finiParser = FiniParser.getInstance(); taskOrganiser = Storage.getInstance(); statusSaver = StatusSaver.getInstance(); // Everything stored here in Brain unless an updateFile is executed // taskMasterList: all existing tasks // taskObservableList: all displayed tasks taskMasterList = taskOrganiser.readFile(); sortTaskMasterList(); taskObservableList.addAll(taskMasterList.stream().filter(task -> !task.isCompleted()).collect(Collectors.toList())); } public static Brain getInstance() { if (brain == null) { brain = new Brain(); } return brain; } // Initialize first display when Fini is started - executed in MainApp public void initDisplay() { rootController.updateMainDisplay(taskObservableList); rootController.updateProjectsOverviewPanel(taskObservableList); rootController.updateTasksOverviewPanel(taskObservableList); } public void executeCommand(String userInput) { String display = ""; finiParser.parse(userInput); System.out.println(">>>>>"); System.out.println(finiParser.getStoredUserInput()); System.out.println(finiParser.getCommandType()); System.out.println(finiParser.getCommandParameters()); System.out.println(finiParser.getCleanParameters()); System.out.println(finiParser.getPriority()); System.out.println(finiParser.getProjectName()); for (LocalDateTime ldt : finiParser.getDatetimes()) { System.out.println(ldt.toString()); } System.out.println(finiParser.getNotParsed()); System.out.println("<<<<<"); CommandType commandType = finiParser.getCommandType(); switch (commandType) { case ADD: display = addTask(); break; // case MODE: // MainApp.switchMode(); // break; default: break; } sortTaskMasterList(); taskObservableList.setAll(taskMasterList.stream().filter(task -> !task.isCompleted()).collect(Collectors.toList())); rootController.updateMainDisplay(taskObservableList); rootController.updateProjectsOverviewPanel(taskObservableList); rootController.updateTasksOverviewPanel(taskObservableList); rootController.updateDisplayToUser(display); } // Logic Methods private String addTask() { // StatusSaver if (finiParser.getCommandParameters().isEmpty()) { return "CommandParameters is empty"; } // TODO if recurring, then create multiple tasks at the same time Task newTask = new Task(finiParser.getNotParsed(), finiParser.getDatetimes(), finiParser.getPriority(), finiParser.getProjectName(), finiParser.getIsRecurring(), finiParser.getRecursUntil()); taskMasterList.add(newTask); taskOrganiser.updateFile(taskMasterList); return "Added: " + finiParser.getNotParsed(); } // /** // * EXTRAORDINARY FEATURE - Sync with nusmods html file // * @author gaieepo // */ // private void loadNUSMods(String commandParameters) { // File modsFile = new File(commandParameters); // if (modsFile.exists()) { // ModsLoader loader = new ModsLoader(modsFile); // } else { // System.out.println("No Mods File"); // private void clearTasks(String commandParameters) { // taskOrganiser.clearTasks(); // private void addTask(String commandParameters) { // boolean hasTaskParameters = checkIfHasParameters(commandParameters); // boolean isRecurringTask = checkIfRecurringTask(commandParameters); // boolean hasPriority = checkIfHasPriority(commandParameters); // boolean hasProject = checkIfHasProject(commandParameters); // boolean hasDate = checkIfDateIsAvailable(commandParameters); // boolean isEvent = checkIfTaskIsEvent(commandParameters); // boolean isDeadline = checkIfTaskIsDeadline(commandParameters); // String[] splitParameters = null; // String[] splitTaskDetails = null; // String taskDetails = ""; // // System.out.println("PRINTING TASK DETAILS: " + taskDetails); // String priority = null; // String project = null; // String startTime = null; // String endTime = null; // String date = null; // String title = null; // if (hasTaskParameters) { // splitParameters = commandParameters.split(" "); // splitTaskDetails = commandParameters.split("//"); // taskDetails = splitTaskDetails[1].substring(1); // int indexOfStartOfTaskDetails = commandParameters.indexOf(" //"); // title = commandParameters.substring(0, indexOfStartOfTaskDetails); // if (hasPriority) { // priority = extractPriority(commandParameters); // if (hasProject) { // project = extractProject(commandParameters); // if (isRecurringTask) { // int indexOfEvery = taskDetails.indexOf("every "); // System.out.println("The task details for the recurring task: " + taskDetails); // String removeEveryKeyWord = taskDetails.substring(indexOfEvery); // removeEveryKeyWord = removeEveryKeyWord.replace("every ", ""); // System.out // .println("The task details for the recurring task: " + removeEveryKeyWord); // String[] splitRemoveEveryKeyWord = removeEveryKeyWord.split(" "); // date = splitRemoveEveryKeyWord[0]; // System.out.println("The task details for the recurring task: " + date); // if (isEvent) { // int indexOfFrom = taskDetails.indexOf("from"); // int indexOfTo = taskDetails.indexOf("to"); // String removeFromKeyword = taskDetails.substring(indexOfFrom); // removeFromKeyword = removeFromKeyword.replace("from ", ""); // String[] splitRemoveFromKeyword = removeFromKeyword.split(" "); // startTime = splitRemoveFromKeyword[0]; // String removeToKeyword = taskDetails.substring(indexOfTo); // removeToKeyword = removeToKeyword.replace("to ", ""); // String[] splitRemoveToKeyword = removeToKeyword.split(" "); // endTime = splitRemoveToKeyword[0]; // } else if (isDeadline) { // int indexOfAt = taskDetails.indexOf("at "); // String removeAtKeyword = taskDetails.substring(indexOfAt); // removeAtKeyword = removeAtKeyword.replace("at ", ""); // String[] splitRemoveAtKeyword = removeAtKeyword.split(" "); // startTime = splitRemoveAtKeyword[0]; // endTime = null; // } else { // System.out.println(taskDetails); // String[] taskDetailsArray = taskDetails.split(" "); // if(hasDate) { // date = taskDetailsArray[0]; // } else { // date = null; // System.out.println(date); // if (isDeadline) { // int indexOfStartTime = taskDetails.indexOf("at "); // String removeAtKeyword = taskDetails.substring(indexOfStartTime); // removeAtKeyword = removeAtKeyword.replace("at ", ""); // String[] splitRremoveAtKeyword = removeAtKeyword.split(" "); // startTime = splitRremoveAtKeyword[0]; // endTime = null; // } else if (isEvent) { // int indexOfStartTime = taskDetails.indexOf("from "); // String removeFromKeyword = taskDetails.substring(indexOfStartTime); // removeFromKeyword = removeFromKeyword.replace("from ", ""); // String[] splitRemoveFromKeyword = removeFromKeyword.split(" "); // startTime = splitRemoveFromKeyword[0]; // System.out.println(startTime); // int indexOfEndTime = taskDetails.indexOf("to "); // String removeToKeyword = taskDetails.substring(indexOfEndTime); // removeToKeyword = removeToKeyword.replace("to ", ""); // String[] splitRemoveToKeyword = removeToKeyword.split(" "); // endTime = splitRemoveToKeyword[0]; // System.out.println(endTime); // } else { // startTime = null; // endTime = null; // } else { // title = commandParameters.trim(); // Task newTask = // new Task(isRecurringTask, title, date, startTime, endTime, priority, project); // taskOrganiser.addNewTask(newTask); // private void deleteTask(String commandParameters) { // Integer taskId = checkTaskId(commandParameters); // if (taskId > taskOrganiser.getSize()) { // System.out.println("Invalid TaskID input!"); // } else { // Task deletedTask = taskOrganiser.getTasks().get(taskId-1); // taskOrganiser.deleteTask(taskId); // System.out.println("Task " + taskId + ": " + deletedTask.getTitle() + " has been deleted!"); // private void updateTask(String commandParameters) { // Integer taskId = checkTaskId(commandParameters); // boolean hasTaskParameters = checkIfHasParameters(commandParameters); // if (0 < taskId && taskId < taskOrganiser.getSize() + 2 && hasTaskParameters) { // Task taskForUpdate = taskOrganiser.getTasks().get(taskId - 1); // System.out.println("updating task number " + taskId + ": "+ taskForUpdate.getTitle()); // String taskUpdateDetails = commandParameters.split("//")[1].trim(); // boolean needToChangeTitle = checkIfHasTitle(taskUpdateDetails); // boolean needToChangePriority = checkIfHasPriority(taskUpdateDetails); // boolean needToChangeProject = checkIfHasProject(taskUpdateDetails); // boolean needToChangeDate = checkIfHasDate(taskUpdateDetails); // boolean needToChangeTime = checkIfHasTime(taskUpdateDetails); // boolean isEvent = taskForUpdate.checkIfDeadline(); // boolean isDeadline = taskForUpdate.checkIfDeadline(); // boolean isRecurringTask = taskForUpdate.checkIfRecurring(); // // TODO cannot add more than one word for title. need to fix // if (needToChangeTitle) { // taskForUpdate.setTitle(extractInformation("title", taskUpdateDetails)); // if (needToChangePriority) { // taskForUpdate.setPriority(extractInformation("priority", taskUpdateDetails)); // if (needToChangeProject) { // taskForUpdate.setProject(extractInformation("project", taskUpdateDetails)); // if(needToChangeDate) { // taskForUpdate.setTaskDate(extractInformation("date", taskUpdateDetails)); // if (needToChangeTime) { // /* recurring function not implemented // * if (isRecurringTask) { // if(isDeadline) { // setRecurTaskDate(taskUpdateDetails); // } else if(isEvent) { // setRecurTaskStartAndEndTime(taskUpdateDetails); // } // } else { // */ // if(isDeadline) { // taskForUpdate.setStartTime(extractInformation("time", taskUpdateDetails)); // } else if (isEvent) { // String timeDetail = extractInformation("time", taskUpdateDetails); // taskForUpdate.setStartTime(extractInformation("from", timeDetail)); // taskForUpdate.setEndTime(extractInformation("to", timeDetail)); // taskOrganiser.getTasks().set(taskId - 1, taskForUpdate); // } else { // System.out.println("Invalid UPDATE input"); // Initialization Methods public void setRootController(RootController rootController) { this.rootController = rootController; } private void sortTaskMasterList() { assert taskMasterList != null; sorter = new Sorter(taskMasterList); sorter.sort(); taskMasterList = sorter.getSortedList(); } }
package org.wikipedia; import android.app.*; import android.content.*; import android.content.pm.*; import android.net.Uri; import android.os.*; import android.text.*; import android.text.format.*; import android.util.*; import android.view.*; import android.view.inputmethod.*; import android.widget.*; import com.squareup.otto.*; import org.json.*; import org.mediawiki.api.json.*; import org.wikipedia.bridge.*; import org.wikipedia.events.*; import org.wikipedia.zero.*; import java.io.*; import java.security.*; import java.text.*; import java.util.*; /** * Contains utility methods that Java doesn't have because we can't make code look too good, can we? */ public final class Utils { /** * Private constructor, so nobody can construct Utils. * * THEIR EVIL PLANS HAVE BEEN THWARTED!!!1 */ private Utils() { } /** * Compares two strings properly, even when one of them is null - without throwing up * * @param str1 The first string * @param str2 Guess? * @return true if they are both equal (even if both are null) */ public static boolean compareStrings(String str1, String str2) { return (str1 == null ? str2 == null : str1.equals(str2)); } /** * Creates an MD5 hash of the provided string & returns its base64 representation * @param s String to hash * @return Base64'd MD5 representation of the string passed in */ public static String md5(final String s) { try { // Create MD5 Hash MessageDigest digest = java.security.MessageDigest .getInstance("MD5"); digest.update(s.getBytes("utf-8")); byte[] messageDigest = digest.digest(); return Base64.encodeToString(messageDigest, Base64.URL_SAFE | Base64.NO_WRAP); } catch (NoSuchAlgorithmException e) { // This will never happen, yes. throw new RuntimeException(e); } catch (UnsupportedEncodingException e) { // This will never happen, yes. throw new RuntimeException(e); } } /** * Returns the local file name for a remote image. * * Warning: Should be kept stable between releases. * @param url URL of the thumbnail image. Expects them to be not protocol relative & have an extension. * @return */ public static String imageUrlToFileName(String url) { String[] protocolParts = url.split(": return "saved-image-" + md5(protocolParts[protocolParts.length - 1]); } /** * Add some utility methods to a communuication bridge, that can be called synchronously from JS */ public static void addUtilityMethodsToBridge(final Context context, final CommunicationBridge bridge) { bridge.addListener("imageUrlToFilePath", new CommunicationBridge.JSEventListener() { @Override public void onMessage(String messageType, JSONObject messagePayload) { String imageUrl = messagePayload.optString("imageUrl"); JSONObject ret = new JSONObject(); try { File imageFile = new File(context.getFilesDir(), imageUrlToFileName(imageUrl)); ret.put("originalURL", imageUrl); ret.put("newURL", imageFile.getAbsolutePath()); bridge.sendMessage("replaceImageSrc", ret); } catch (JSONException e) { // stupid, stupid, stupid throw new RuntimeException(e); } } }); } /** * Parses dates from the format MediaWiki uses. * * @param mwDate String representing Date returned from a MW API call * @return A {@link java.util.Date} object representing that particular date */ public static Date parseMWDate(String mwDate) { SimpleDateFormat isoFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); // Assuming MW always gives me UTC try { return isoFormat.parse(mwDate); } catch (ParseException e) { throw new RuntimeException(e); } } /** * Formats provided date relative to the current system time * @param date Date to format * @return String representing the relative time difference of the paramter from current time */ public static String formatDateRelative(Date date) { return DateUtils.getRelativeTimeSpanString(date.getTime(), System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS, 0).toString(); } /** * Ensures that the calling method is on the main thread. */ public static void ensureMainThread() { if (Looper.getMainLooper().getThread() != Thread.currentThread()) { throw new IllegalStateException("Method must be called from the Main Thread"); } } /** * Attempt to hide the Android Keyboard. * * FIXME: This should not need to exist. * I do not know why Android does not handle this automatically. * * @param activity The current activity */ public static void hideSoftKeyboard(Activity activity) { InputMethodManager keyboard = (InputMethodManager)activity.getSystemService(Context.INPUT_METHOD_SERVICE); // Not using getCurrentFocus as that sometimes is null, but the keyboard is still up. keyboard.hideSoftInputFromWindow(activity.getWindow().getDecorView().getWindowToken(), 0); } public static void setupShowPasswordCheck(final CheckBox check, final EditText edit) { check.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) { // EditText loses the cursor position when you change the InputType int curPos = edit.getSelectionStart(); if (isChecked) { edit.setInputType(InputType.TYPE_CLASS_TEXT); } else { edit.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD); } edit.setSelection(curPos); } }); } /* Inspect an API response, and fire an event to update the UI for Wikipedia Zero On/Off. * * @param app The application object * @param result An API result to inspect for Wikipedia Zero headers */ public static void processHeadersForZero(final WikipediaApp app, final ApiResult result) { new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { Map<String, List<String>> headers = result.getHeaders(); boolean responseZeroState = headers.containsKey("X-CS"); if (responseZeroState) { String xcs = headers.get("X-CS").get(0); if (!xcs.equals(WikipediaApp.getXcs())) { identifyZeroCarrier(app, xcs); } } else if (WikipediaApp.getWikipediaZeroDisposition()) { WikipediaApp.setXcs(""); WikipediaApp.setCarrierMessage(""); WikipediaApp.setWikipediaZeroDisposition(responseZeroState); app.getBus().post(new WikipediaZeroStateChangeEvent()); } } }); } private static final int MESSAGE_ZERO = 1; public static void identifyZeroCarrier(final WikipediaApp app, final String xcs) { Handler wikipediaZeroHandler = new Handler(new Handler.Callback(){ private WikipediaZeroTask curZeroTask; @Override public boolean handleMessage(Message msg) { WikipediaZeroTask zeroTask = new WikipediaZeroTask(app.getAPIForSite(app.getPrimarySite()), app) { @Override public void onFinish(String message) { Log.d("Wikipedia", "Wikipedia Zero message: " + message); if (message != null) { WikipediaApp.setXcs(xcs); WikipediaApp.setCarrierMessage(message); WikipediaApp.setWikipediaZeroDisposition(true); Bus bus = app.getBus(); bus.post(new WikipediaZeroStateChangeEvent()); curZeroTask = null; } } @Override public void onCatch(Throwable caught) { // oh snap Log.d("Wikipedia", "Wikipedia Zero Eligibility Check Exception Caught"); curZeroTask = null; } }; if (curZeroTask != null) { // if this connection was hung, clean up a bit curZeroTask.cancel(); } curZeroTask = zeroTask; curZeroTask.execute(); return true; } }); wikipediaZeroHandler.removeMessages(MESSAGE_ZERO); Message zeroMessage = Message.obtain(); zeroMessage.what = MESSAGE_ZERO; zeroMessage.obj = "zero_eligible_check"; wikipediaZeroHandler.sendMessage(zeroMessage); } /** * Takes a language code (as returned by Android) and returns a wiki code, as used by wikipedia. * * @param langCode Language code (as returned by Android) * @return Wiki code, as used by wikipedia. */ public static String langCodeToWikiLang(String langCode) { // Convert deprecated language codes to modern ones. if (langCode.equals("iw")) { return "he"; // Hebrew } else if (langCode.equals("in")) { return "id"; // Indonesian } else if (langCode.equals("ji")) { return "yi"; // Yiddish } return langCode; } /** * List of wiki language codes for which the content is primarily RTL. * * Ensure that this is always sorted alphabetically. */ private static final String[] RTL_LANGS = { "arc", "arz", "ar", "bcc", "bqi", "ckb", "dv", "fa", "glk", "ha", "he", "khw", "ks", "mzn", "pnb", "ps", "sd", "ug", "ur", "yi" }; /** * Setup directionality for both UI and content elements in a webview. * * @param contentLang The Content language to use to set directionality. Wiki Language code. * @param uiLang The UI language to use to set directionality. Java language code. * @param bridge The CommunicationBridge to use to communicate with the WebView */ public static void setupDirectionality(String contentLang, String uiLang, CommunicationBridge bridge) { JSONObject payload = new JSONObject(); try { if (isLangRTL(contentLang)) { payload.put("contentDirection", "rtl"); } else { payload.put("contentDirection", "ltr"); } if (isLangRTL(langCodeToWikiLang(uiLang))) { payload.put("uiDirection", "rtl"); } else { payload.put("uiDirection", "ltr"); } } catch (JSONException e) { throw new RuntimeException(e); } bridge.sendMessage("setDirectionality", payload); } /** * Returns true if the given wiki language is to be displayed RTL. * * @param lang Wiki code for the language to check for directionality * @return true if it is RTL, false if LTR */ public static boolean isLangRTL(String lang) { return Arrays.binarySearch(RTL_LANGS, lang, null) >= 0; } /** * Sets text direction (RTL / LTR) for given view based on given lang. * * Doesn't do anything on pre Android 4.2, since their RTL support is terrible. * * @param view View to set direction of * @param lang Wiki code for the language based on which to set direction */ public static void setTextDirection(View view, String lang) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { view.setTextDirection(Utils.isLangRTL(lang) ? View.TEXT_DIRECTION_RTL : View.TEXT_DIRECTION_LTR); } } /** * Returns db name for given site * * WARNING: HARDCODED TO WORK FOR WIKIPEDIA ONLY * * @param site Site object to get dbname for * @return dbname for given site object */ public static String getDBNameForSite(Site site) { return site.getLanguage() + "wiki"; } /** * Open the specified URI in an external browser (even if our app's intent filter * matches the given URI) * * @param context Context of the calling app * @param uri URI to open in an external browser */ public static void visitInExternalBrowser(final Context context, Uri uri){ Intent intent = new Intent(); intent.setAction(Intent.ACTION_VIEW); intent.setData(uri); List<ResolveInfo> resInfo = context.getPackageManager().queryIntentActivities(intent, 0); if (!resInfo.isEmpty()){ List<Intent> browserIntents = new ArrayList<Intent>(); for (ResolveInfo resolveInfo : resInfo) { String packageName = resolveInfo.activityInfo.packageName; // remove our app from the selection! if(packageName.equals(context.getPackageName())) { continue; } Intent newIntent = new Intent(Intent.ACTION_VIEW); newIntent.setData(uri); newIntent.setPackage(packageName); browserIntents.add(newIntent); } if (browserIntents.size() > 0) { // initialize the chooser intent with one of the browserIntents, and remove that // intent from the list, since the chooser already has it, and we don't need to // add it again in putExtra. (initialize with the last item in the list, to preserve order) Intent chooserIntent = Intent.createChooser(browserIntents.remove(browserIntents.size() - 1), null); chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, browserIntents.toArray(new Parcelable[]{})); context.startActivity(chooserIntent); return; } } context.startActivity(intent); } /** * Utility method to copy a stream into another stream. * * Uses a 16KB buffer. * * @param in Stream to copy from. * @param out Stream to copy to. * @throws IOException */ public static void copyStreams(InputStream in, OutputStream out) throws IOException { byte[] buffer = new byte[16 * 1024]; // 16kb buffer int len; while ((len = in.read(buffer)) != -1) { out.write(buffer, 0, len); } } /** * Format for formatting/parsing dates to/from the ISO 8601 standard */ private static final String ISO8601_FORMAT_STRING = "yyyy-MM-dd'T'HH:mm:ss'Z'"; /** * Parse a date formatted in ISO8601 format. * * @param dateString Date String to parse * @return Parsed Date object. * @throws ParseException */ public static Date parseISO8601(String dateString) throws ParseException { Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat(ISO8601_FORMAT_STRING); sdf.setTimeZone(TimeZone.getTimeZone("UTC")); date.setTime(sdf.parse(dateString).getTime()); return date; } /** * Format a date to an ISO8601 formatted string. * * @param date Date to format. * @return The given date formatted in ISO8601 format. */ public static String formatISO8601(Date date) { SimpleDateFormat sdf = new SimpleDateFormat(ISO8601_FORMAT_STRING); sdf.setTimeZone(TimeZone.getTimeZone("UTC")); return sdf.format(date); } }
import com.sun.star.sdbc.SQLException; import com.sun.star.uno.Exception; import com.sun.star.wizards.common.JavaTools; public class CommandName{ protected CommandMetaData oCommandMetaData; protected String CatalogName = ""; protected String SchemaName = ""; protected String TableName = ""; protected String DisplayName = ""; protected String ComposedName = ""; protected String AliasName = ""; protected boolean bCatalogAtStart; protected String sCatalogSep; protected String sIdentifierQuote; protected boolean baddQuotation = true; public CommandName(CommandMetaData _CommandMetaData, String _DisplayName){ oCommandMetaData = _CommandMetaData; setComposedCommandName(_DisplayName); } public CommandName(CommandMetaData _CommandMetaData, String _CatalogName, String _SchemaName, String _TableName, boolean _baddQuotation){ try { baddQuotation = _baddQuotation; oCommandMetaData = _CommandMetaData; if ((_CatalogName != null) && (oCommandMetaData.xDBMetaData.supportsCatalogsInTableDefinitions())){ if (!_CatalogName.equals("")){ CatalogName = _CatalogName; } } if ((_SchemaName != null) && (oCommandMetaData.xDBMetaData.supportsSchemasInTableDefinitions())){ if (!_SchemaName.equals("")){ SchemaName = _SchemaName; } } if (_TableName != null){ if (!_TableName.equals("")){ TableName = _TableName; } } setComposedCommandName(); } catch (SQLException e) { e.printStackTrace(System.out); }} private void setComposedCommandName(String _DisplayName) { try{ if (this.setMetaDataAttributes()){ this.DisplayName = _DisplayName; int iIndex; if (oCommandMetaData.xDBMetaData.supportsCatalogsInDataManipulation() == true) { // ...dann Catalog mit in TableName iIndex = _DisplayName.indexOf(sCatalogSep); if (iIndex >= 0) { if (bCatalogAtStart == true) { CatalogName = _DisplayName.substring(0, iIndex); _DisplayName = _DisplayName.substring(iIndex + 1, _DisplayName.length()); } else { CatalogName = _DisplayName.substring(iIndex + 1, _DisplayName.length()); _DisplayName = _DisplayName.substring(0, iIndex); } } } if (oCommandMetaData.xDBMetaData.supportsSchemasInDataManipulation() == true) { String[] NameList; NameList = new String[0]; NameList = JavaTools.ArrayoutofString(_DisplayName, "."); SchemaName = NameList[0]; TableName = NameList[1]; // TODO Was ist mit diesem Fall: CatalogSep = "." und CatalogName = "" } else TableName = _DisplayName; setComposedCommandName(); } } catch (Exception exception) { exception.printStackTrace(System.out); }} public void setComposedCommandName() { if (this.setMetaDataAttributes()){ if (CatalogName != null){ if (!CatalogName.equals("")){ if (bCatalogAtStart == true){ ComposedName = quoteName(CatalogName) + sCatalogSep; } } } if (SchemaName != null){ if (!SchemaName.equals("")) ComposedName += quoteName(SchemaName) + "."; } if (ComposedName == "") ComposedName = quoteName(TableName); else ComposedName += quoteName(TableName); if ((bCatalogAtStart == false) && (CatalogName != null)){ if (!CatalogName.equals("")) ComposedName += sCatalogSep + quoteName(CatalogName); } } } private boolean setMetaDataAttributes(){ try { bCatalogAtStart = oCommandMetaData.xDBMetaData.isCatalogAtStart(); sCatalogSep = oCommandMetaData.xDBMetaData.getCatalogSeparator(); sIdentifierQuote = oCommandMetaData.xDBMetaData.getIdentifierQuoteString(); return true; } catch (SQLException e) { e.printStackTrace(System.out); return false; }} public String quoteName(String _sName) { if (baddQuotation) return quoteName(_sName, this.oCommandMetaData.getIdentifierQuote()); else return _sName; } public static String quoteName(String sName, String _sIdentifierQuote) { if (sName == null) sName = ""; String ReturnQuote = ""; ReturnQuote = _sIdentifierQuote + sName + _sIdentifierQuote; return ReturnQuote; } public void setAliasName(String _AliasName){ AliasName = _AliasName; } public String getAliasName(){ return AliasName; } /** * @return Returns the catalogName. */ public String getCatalogName() { return CatalogName; } /** * @return Returns the composedName. */ public String getComposedName() { return ComposedName; } /** * @return Returns the displayName. */ public String getDisplayName() { return DisplayName; } /** * @return Returns the schemaName. */ public String getSchemaName() { return SchemaName; } /** * @return Returns the tableName. */ public String getTableName() { return TableName; } public CommandMetaData getCommandMetaData(){ return oCommandMetaData; } }
package grovepi; import java.io.IOException; import grovepi.common.Delay; /** * GrovePi+ board. * * @author Dan Jackson (originally based on code by Johannes Bergmann, but rewritten following C# implementation) */ public class GrovePi { private static class Command { public static final byte DIGITAL_READ = 1; public static final byte DIGITAL_WRITE = 2; public static final byte ANALOG_READ = 3; public static final byte ANALOG_WRITE = 4; public static final byte PIN_MODE = 5; public static final byte VERSION = 8; }; private final GrovePiI2CDevice device; public GrovePiI2CDevice getDirectAccess() { return device; } public GrovePi() { this(GrovePiI2CDevice.getInstanceRuntimeExecption()); } public GrovePi(GrovePiI2CDevice device) { this.device = device; } // [dgj] Added this -- makes more sense than the C# way of making sensors private GroveDeviceFactory deviceFactory = null; public GroveDeviceFactory getDeviceFactory() { if (deviceFactory == null) { deviceFactory = new GroveDeviceFactory(this); } return deviceFactory; } public String getFirmwareVersion() throws IOException { byte[] buffer = new byte[] { Command.VERSION, Constants.UNUSED, Constants.UNUSED, Constants.UNUSED }; getDirectAccess().read(buffer); return "" + buffer[1] + buffer[2] + "." + buffer[3] + ""; } public int digitalRead(int pin) { byte[] buffer = new byte[] { (byte)Command.DIGITAL_READ, (byte)pin, Constants.UNUSED, Constants.UNUSED}; getDirectAccess().write(buffer); Delay.milliseconds(100); // C# version doesn't do this int value = getDirectAccess().read(); System.out.print("<pin-" + pin + "<=" + value + ">"); return value; } public void digitalWrite(int pin, int value) { byte[] buffer = new byte[] { (byte)Command.DIGITAL_WRITE, (byte)pin, (byte)value, Constants.UNUSED}; System.out.print("<pin-" + pin + "=>" + value + ">"); getDirectAccess().write(buffer); } public int analogRead(int pin) { byte[] buffer = new byte[] { (byte)Command.ANALOG_READ, (byte)pin, Constants.UNUSED, Constants.UNUSED}; getDirectAccess().write(buffer); Delay.milliseconds(100); // C# version doesn't do this getDirectAccess().read(buffer); return Byte.toUnsignedInt(buffer[1])*256 + (int)buffer[2]; } public void analogWrite(int pin, int value) { byte[] buffer = new byte[] {(byte)Command.ANALOG_WRITE, (byte)pin, (byte)value, Constants.UNUSED}; getDirectAccess().write(buffer); } public void pinMode(int pin, PinMode mode) { byte[] buffer = new byte[] {(byte)Command.PIN_MODE, (byte)pin, (byte)mode.getValue(), Constants.UNUSED}; getDirectAccess().write(buffer); System.out.println("DEBUG: Mode for pin " + pin + " = " + mode + " (" + mode.getValue() + ")."); } }
package gui; import java.awt.Color; import java.awt.Component; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import javax.swing.ButtonGroup; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JTextField; import shared.Allele; import shared.Genotype; import shared.SessionParameters; import java.util.ArrayList; /** * * @author jasonfortunato * @author linneasahlberg * * A pane in the GUI that allows the user to put in information about the initial population: number of generations, * number of populations, population size, and enter allele frequencies OR genotype numbers. * */ public class InitPopPane extends EvoPane { JLabel popLabel; // Population size JLabel popSizeLabel; JTextField popSizeField; JLabel numPopsLabel; // number of populations JTextField numPops; JLabel numGensLabel; // number of generations JTextField numGens; ButtonGroup initPopVals; // radio buttons JRadioButton alleleFreqs; JRadioButton genotypeNums; JLabel initPopLabel; // Initial population JTextField initPop; JLabel initFreqALabel, initFreqBLabel, // Initial frequencies initFreqCLabel; JTextField initFreqA, initFreqB, initFreqC; JLabel alleleFreqsLabel, genoNumsLabel; // labels for subsections JLabel calcFreqAALabel, calcFreqABLabel, // calculated frequencies calcFreqBBLabel, calcFreqACLabel, calcFreqBCLabel, calcFreqCCLabel; JLabel freqTotal; JLabel genoAALabel, genoABLabel, // genotypes genoBBLabel, genoACLabel, genoBCLabel, genoCCLabel; JLabel genoTotal; JTextField genoAA, genoAB, genoBB, genoAC, genoBC, genoCC; JPanel afPane, gnPane; // allele freqency and genotype panes JButton apply; // apply button to see calculated values ArrayList<Component> alFreqList = new ArrayList<Component>(); ArrayList<Component> gtNumList = new ArrayList<Component>(); public InitPopPane() { super(); color1List.add(getParent()); popLabel = new JLabel("<html><b><span style='font-size:11px'>Initial Population:</span></b>"); popSizeLabel = new JLabel("<html><b>Population Size:"); popSizeField = new JTextField(TEXT_LEN_LONG); popSizeField.setName(INT); popSizeField.setInputVerifier(iv); // init pop size c.gridx = 0; c.gridy = 1; c.anchor = GridBagConstraints.WEST; add(popLabel, c); // num gens and pops numGensLabel = new JLabel("<html><b>Number of Generations:"); numGens = new JTextField(TEXT_LEN_LONG); numPopsLabel = new JLabel("<html><b>Number of Populations:"); numPops = new JTextField(TEXT_LEN_LONG); c.insets = new Insets(0, 20, 0, 0); c.gridwidth = 2; c.gridx = 0; c.gridy++; add(numGensLabel, c); c.gridwidth = 2; c.gridx++; add(numGens, c); c.gridx = 0; c.gridy++; add(numPopsLabel, c); c.gridx++; add(numPops, c); c.gridx = 0; c.gridy++; add(popSizeLabel, c); c.gridx++; add(popSizeField, c); // population constant radio button stuff initPopVals = new ButtonGroup(); alleleFreqs = new JRadioButton("<html><b>Enter Allele Frequncies", true); genotypeNums = new JRadioButton("<html><b>Enter Genotype Numbers"); initPopVals.add(alleleFreqs); initPopVals.add(genotypeNums); alleleFreqsLabel = new JLabel("<html><b>Allele frequencies</b> (0-1):"); initFreqALabel = new JLabel("A:"); initFreqBLabel = new JLabel("B:"); initFreqCLabel = new JLabel("C:"); threeAllelesList.add(initFreqCLabel); initFreqA = new JTextField(TEXT_LEN_SHORT); initFreqB = new JTextField(TEXT_LEN_SHORT); initFreqC = new JTextField(TEXT_LEN_SHORT); threeAllelesList.add(initFreqC); initFreqA.setName(RATE); initFreqB.setName(RATE); initFreqC.setName(RATE); calcFreqAALabel = new JLabel("AA: ___"); calcFreqABLabel = new JLabel("AB: ___"); calcFreqBBLabel = new JLabel("BB: ___"); calcFreqACLabel = new JLabel("AC: ___"); threeAllelesList.add(calcFreqACLabel); calcFreqBCLabel = new JLabel("BC: ___"); threeAllelesList.add(calcFreqBCLabel); calcFreqCCLabel = new JLabel("CC: ___"); threeAllelesList.add(calcFreqCCLabel); c.gridwidth = 2; c.gridx = 0; c.gridy++; afPane = new JPanel(); afPane.setBackground(color1); afPane.setLayout(new GridBagLayout()); GridBagConstraints t = new GridBagConstraints(); // t for temp constraints t.insets = new Insets(0, 0, 3, 15); t.gridwidth = 6; t.gridx = 0; t.gridy = 0; afPane.add(alleleFreqs, t); t.gridwidth = 1; t.gridx = 6; t.gridy = 0; afPane.add(initFreqALabel, t); t.gridx = 7; t.gridy = 0; afPane.add(initFreqA, t); t.gridx = 8; t.gridy = 0; afPane.add(initFreqBLabel, t); t.gridx = 9; t.gridy = 0; afPane.add(initFreqB, t); t.gridx = 10; t.gridy = 0; afPane.add(initFreqCLabel, t); t.gridx = 11; t.gridy = 0; afPane.add(initFreqC, t); c.gridx = 0; c.gridwidth = 7; add(afPane, c); genoNumsLabel = new JLabel("<html><b>Genotype Numbers:"); genoAALabel = new JLabel("AA"); genoABLabel = new JLabel("AB"); genoBBLabel = new JLabel("BB"); genoACLabel = new JLabel("AC"); threeAllelesList.add(genoACLabel); genoBCLabel = new JLabel("BC"); threeAllelesList.add(genoBCLabel); genoCCLabel = new JLabel("CC"); threeAllelesList.add(genoCCLabel); genoAA = new JTextField(TEXT_LEN_SHORT); genoAB = new JTextField(TEXT_LEN_SHORT); genoBB = new JTextField(TEXT_LEN_SHORT); genoAC = new JTextField(TEXT_LEN_SHORT); threeAllelesList.add(genoAC); genoBC = new JTextField(TEXT_LEN_SHORT); threeAllelesList.add(genoBC); genoCC = new JTextField(TEXT_LEN_SHORT); threeAllelesList.add(genoCC); gnPane = new JPanel(); gnPane.setBackground(color1); gnPane.setLayout(new GridBagLayout()); t = new GridBagConstraints(); t.insets = new Insets(0, 0, 0, 15); t.gridwidth = 1; t.gridx = 0; t.gridy = 1; gnPane.add(genotypeNums, t); t.gridwidth = 1; t.gridx++; t.gridy = 1; gnPane.add(genoAALabel, t); t.gridy = 2; gnPane.add(genoAA, t); t.gridx = 2; t.gridy = 1; gnPane.add(genoABLabel, t); t.gridx = 2; t.gridy = 2; gnPane.add(genoAB, t); t.gridx = 3; t.gridy = 1; gnPane.add(genoBBLabel, t); t.gridx = 3; t.gridy = 2; gnPane.add(genoBB, t); t.gridx = 4; t.gridy = 1; gnPane.add(genoACLabel, t); t.gridx = 4; t.gridy = 2; gnPane.add(genoAC, t); t.gridx = 5; t.gridy = 1; gnPane.add(genoBCLabel, t); t.gridx = 5; t.gridy = 2; gnPane.add(genoBC, t); t.gridx = 6; t.gridy = 1; gnPane.add(genoCCLabel, t); t.gridx = 6; t.gridy = 2; gnPane.add(genoCC, t); c.gridx = 0; c.gridy++; add(gnPane, c); addToLists(); modeAlleleFreqs(true); // Set actions for the PopConstTrue/False radio buttons alleleFreqs.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { modeAlleleFreqs(true); } }); genotypeNums.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { modeAlleleFreqs(false); } }); popSizeField.addFocusListener(new FocusListener() { public void focusGained(FocusEvent e) { popSizeField.selectAll(); } public void focusLost(FocusEvent e) { popSizeField.select(0, 0); updateGenoNums(); } }); initFreqA.addFocusListener(new FocusListener() { public void focusGained(FocusEvent e) { initFreqA.selectAll(); } public void focusLost(FocusEvent e) { initFreqA.select(0, 0); updateFreq(); updateGenoNums(); } }); initFreqB.addFocusListener(new FocusListener() { public void focusGained(FocusEvent e) { initFreqB.selectAll(); } public void focusLost(FocusEvent e) { initFreqB.select(0, 0); updateFreq(); updateGenoNums(); } }); genoAA.addFocusListener(new FocusListener() { public void focusGained(FocusEvent e) { genoAA.selectAll(); } public void focusLost(FocusEvent e) { genoAA.select(0, 0); updatePopSizeAndFreq(); } }); genoAB.addFocusListener(new FocusListener() { public void focusGained(FocusEvent e) { genoAB.selectAll(); } public void focusLost(FocusEvent e) { genoAB.select(0, 0); updatePopSizeAndFreq(); } }); genoBB.addFocusListener(new FocusListener() { public void focusGained(FocusEvent e) { genoBB.selectAll(); } public void focusLost(FocusEvent e) { genoBB.select(0, 0); updatePopSizeAndFreq(); } }); genoAC.addFocusListener(new FocusListener() { public void focusGained(FocusEvent e) { genoAC.selectAll(); } public void focusLost(FocusEvent e) { genoAC.select(0, 0); updatePopSizeAndFreq(); } }); genoBC.addFocusListener(new FocusListener() { public void focusGained(FocusEvent e) { genoBC.selectAll(); } public void focusLost(FocusEvent e) { genoBC.select(0, 0); updatePopSizeAndFreq(); } }); genoCC.addFocusListener(new FocusListener() { public void focusGained(FocusEvent e) { genoCC.selectAll(); } public void focusLost(FocusEvent e) { genoCC.select(0, 0); updatePopSizeAndFreq(); } }); } /** * adds components to the alFreqList and gtNumList */ private void addToLists() { alFreqList.add(alleleFreqsLabel); alFreqList.add(initFreqALabel); alFreqList.add(initFreqBLabel); alFreqList.add(initFreqA); alFreqList.add(initFreqB); gtNumList.add(genoNumsLabel); gtNumList.add(genoAALabel); gtNumList.add(genoABLabel); gtNumList.add(genoBBLabel); gtNumList.add(genoACLabel); gtNumList.add(genoBCLabel); gtNumList.add(genoCCLabel); gtNumList.add(genoAA); gtNumList.add(genoAB); gtNumList.add(genoBB); gtNumList.add(genoAC); gtNumList.add(genoBC); gtNumList.add(genoCC); } private void modeAlleleFreqs(boolean b) { for(Component comp : alFreqList) comp.setEnabled(b); for(Component comp : gtNumList) comp.setEnabled(!b); if(!threeAlleles) { initFreqB.setEnabled(false); initFreqBLabel.setEnabled(false); } } @Override public void modeThreeAlleles(boolean b){ super.modeThreeAlleles(b); initFreqB.setEnabled(b && alleleFreqs.isSelected()); initFreqBLabel.setEnabled(b && alleleFreqs.isSelected()); initFreqC.setEnabled(false); initFreqCLabel.setEnabled(false); updateAll(); } public void submit(shared.SessionParameters p) { double Afreq; double Bfreq; double Cfreq; p.setNumPops(Integer.parseInt(numPops.getText())); p.setNumGens(Integer.parseInt(numGens.getText())); if(alleleFreqs.isSelected()) { p.setPopSize(Integer.parseInt(popSizeField.getText())); Afreq = Double.parseDouble(initFreqA.getText()); if(threeAlleles) { Bfreq = Double.parseDouble(initFreqB.getText()); Cfreq = 1 - (Afreq + Bfreq); p.setAlleleFrequency(Allele.C, Cfreq); } else { // two allele mode Bfreq = 1 - Afreq; } p.setAlleleFrequency(Allele.A, Afreq); p.setAlleleFrequency(Allele.B, Bfreq); updateGenotypeNums(p); } else if(genotypeNums.isSelected()) { // Given the hard numbers, calculate the frequencies double AA = 0; double AB = 0; double BB = 0; double AC = 0; double BC = 0; double CC = 0; int total = 0; AA = Double.parseDouble(genoAA.getText()); AB = Double.parseDouble(genoAB.getText()); BB = Double.parseDouble(genoBB.getText()); if(threeAlleles) { AC = Double.parseDouble(genoAC.getText()); BC = Double.parseDouble(genoBC.getText()); CC = Double.parseDouble(genoCC.getText()); } total = (int) (AA + AB + BB + AC + BC + CC); p.setPopSize(total); popSizeField.setText(Double.toString(total)); // set init allele freqs // call updateGenotypeNums int totalA = (int) (2 * AA + AB + AC); int totalB = (int) (2 * BB + AB + BC); int totalC = (int) (2 * CC + AC + BC); double totalAlleles = totalA + totalB + totalC; double fa = (double) totalA / totalAlleles; double fb = (double) totalB / totalAlleles; double fc = (double) totalC / totalAlleles; initFreqA.setText(String.format("%.3f", fa)); initFreqB.setText(String.format("%.3f", fb)); initFreqC.setText(String.format("%.3f", fc)); } updateGenotypeNums(p); } // update the labels and boxes to reflect the A B and C allele freqs // update the sesh parms object too private void updateGenotypeNums(SessionParameters p) { double freqA = Double.parseDouble(initFreqA.getText()); double freqB = 0; double freqC = 0; double AAfreq = 0; double ABfreq = 0; double BBfreq = 0; double ACfreq = 0; double BCfreq = 0; double CCfreq = 0; if(threeAlleles) { freqB = Double.parseDouble(initFreqB.getText()); freqC = 1 - freqA - freqB; //calc 6 freqs AAfreq = freqA * freqA; ABfreq = 2 * freqA * freqB; BBfreq = freqB * freqB; ACfreq = 2 * freqA * freqC; BCfreq = 2 * freqB * freqC; CCfreq = freqC * freqC; p.setGenotypeFrequency(Genotype.AC, ACfreq); p.setGenotypeFrequency(Genotype.BC, BCfreq); p.setGenotypeFrequency(Genotype.CC, CCfreq); } else { // two allele mode freqB = 1 - freqA; AAfreq = freqA * freqA; ABfreq = 2 * freqA * freqB; BBfreq = freqB * freqB; } // Set the allele freq text fields initFreqB.setText(String.format("%.3f", freqB)); initFreqC.setText(String.format("%.3f", freqC)); calcFreqAALabel.setText("AA: " + String.format("%.3f", AAfreq)); calcFreqABLabel.setText("AB: " + String.format("%.3f", ABfreq)); calcFreqBBLabel.setText("BB: " + String.format("%.3f", BBfreq)); calcFreqACLabel.setText("AC: " + String.format("%.3f", ACfreq)); calcFreqBCLabel.setText("BC: " + String.format("%.3f", BCfreq)); calcFreqCCLabel.setText("CC: " + String.format("%.3f", CCfreq)); // Set the number text boxes if(!genotypeNums.isSelected()) { int totalPop = p.getPopSize(); int numAA = (int) (AAfreq * totalPop); int numAB = (int) (ABfreq * totalPop); int numBB = (int) (BBfreq * totalPop); int numAC = (int) (ACfreq * totalPop); int numBC = (int) (BCfreq * totalPop); int numCC = (int) (CCfreq * totalPop); genoAA.setText(Integer.toString(numAA)); genoAB.setText(Integer.toString(numAB)); genoBB.setText(Integer.toString(numBB)); genoAC.setText(Integer.toString(numAC)); genoBC.setText(Integer.toString(numBC)); genoCC.setText(Integer.toString(numCC)); } p.setGenotypeFrequency(Genotype.AA, AAfreq); p.setGenotypeFrequency(Genotype.AB, ABfreq); p.setGenotypeFrequency(Genotype.BB, BBfreq); } public void updateAll() { if(alleleFreqs.isSelected()) { updateFreq(); updateGenoNums(); } else { updatePopSizeAndFreq(); } } public void updateFreq() { if(!threeAlleles && initFreqA.getText().equals("")) { initFreqB.setText(""); return; } if(threeAlleles && (initFreqA.getText().equals("") || initFreqB.getText().equals(""))) { initFreqC.setText(""); return; } double Afreq = Double.parseDouble(initFreqA.getText()); double Bfreq; double Cfreq; if(!threeAlleles) { // two alleles Bfreq = 1 - Afreq; initFreqB.setText(String.format("%.3f", Bfreq)); } else { // three alleles Bfreq = Double.parseDouble(initFreqB.getText()); Cfreq = 1 - (Afreq + Bfreq); initFreqC.setText(String.format("%.3f", Cfreq)); } } public void updateGenoNums() { if(popSizeField.getText().equals("") || initFreqA.getText().equals("") || (threeAlleles && initFreqB.getText().equals(""))) { genoAA.setText(""); genoAB.setText(""); genoBB.setText(""); genoAC.setText(""); genoBC.setText(""); genoCC.setText(""); return; } int totalPop = Integer.parseInt(popSizeField.getText()); double freqA = Double.parseDouble(initFreqA.getText()); double freqB = Double.parseDouble(initFreqB.getText()); double freqC = 0; double AAfreq = 0; double ABfreq = 0; double BBfreq = 0; double ACfreq = 0; double BCfreq = 0; double CCfreq = 0; if(!threeAlleles) { // two alleles AAfreq = freqA * freqA; ABfreq = 2 * freqA * freqB; BBfreq = freqB * freqB; } else { // three alleles freqC = Double.parseDouble(initFreqC.getText()); AAfreq = freqA * freqA; ABfreq = 2 * freqA * freqB; BBfreq = freqB * freqB; ACfreq = 2 * freqA * freqC; BCfreq = 2 * freqB * freqC; CCfreq = freqC * freqC; } genoAA.setText(Integer.toString((int) (AAfreq * totalPop))); genoAB.setText(Integer.toString((int) (ABfreq * totalPop))); genoBB.setText(Integer.toString((int) (BBfreq * totalPop))); if(threeAlleles) { genoAC.setText(Integer.toString((int) (ACfreq * totalPop))); genoBC.setText(Integer.toString((int) (BCfreq * totalPop))); genoCC.setText(Integer.toString((int) (CCfreq * totalPop))); } } public void updatePopSizeAndFreq() { if(genoAA.getText().equals("") || genoAB.getText().equals("") || genoBB.getText().equals("") || (threeAlleles && ( genoAC.getText().equals("") || genoBC.getText().equals("") || genoCC.getText().equals("")))) { popSizeField.setText(""); initFreqA.setText(""); initFreqB.setText(""); initFreqC.setText(""); return; } double AA = Double.parseDouble(genoAA.getText());; double AB = Double.parseDouble(genoAB.getText());; double BB = Double.parseDouble(genoBB.getText());; double AC = 0; double BC = 0; double CC = 0; if(threeAlleles) { AC = Double.parseDouble(genoAC.getText()); BC = Double.parseDouble(genoBC.getText()); CC = Double.parseDouble(genoCC.getText()); } popSizeField.setText(Integer.toString((int) (AA + AB + BB + AC + BC + CC))); int totalA = (int) (2 * AA + AB + AC); int totalB = (int) (2 * BB + AB + BC); int totalC = (int) (2 * CC + AC + BC); double totalAlleles = totalA + totalB + totalC; initFreqA.setText(String.format("%.3f", (double) totalA / totalAlleles)); initFreqB.setText(String.format("%.3f", (double) totalB / totalAlleles)); initFreqC.setText(String.format("%.3f", (double) totalC / totalAlleles)); } } // class
package jade.core; import java.io.Reader; import java.io.StringReader; import java.io.StringWriter; import java.io.Serializable; import java.io.InterruptedIOException; import java.util.Date; import java.util.Iterator; import java.util.Map; import java.util.HashMap; import java.util.Vector; import jade.core.behaviours.Behaviour; import jade.lang.acl.*; import jade.domain.AgentManagementOntology; import jade.domain.FIPAException; /** The <code>Agent</code> class is the common superclass for user defined software agents. It provides methods to perform basic agent tasks, such as: <ul> <li> <b> Message passing using <code>ACLMessage</code> objects, both unicast and multicast with optional pattern matching. </b> <li> <b> Complete Agent Platform life cycle support, including starting, suspending and killing an agent. </b> <li> <b> Scheduling and execution of multiple concurrent activities. </b> <li> <b> Simplified interaction with <em>FIPA</em> system agents for automating common agent tasks (DF registration, etc.). </b> </ul> Application programmers must write their own agents as <code>Agent</code> subclasses, adding specific behaviours as needed and exploiting <code>Agent</code> class capabilities. @author Giovanni Rimassa - Universita` di Parma @version $Date$ $Revision$ */ public class Agent implements Runnable, Serializable, CommBroadcaster { // This inner class is used to force agent termination when a signal // from the outside is received private class AgentDeathError extends Error { AgentDeathError() { super("Agent " + Thread.currentThread().getName() + " has been terminated."); } } // This class manages bidirectional associations between Timer and // Behaviour objects, using hash tables. This class is fully // synchronized because is accessed both by agent internal thread // and high priority Timer Dispatcher thread. private static class AssociationTB { private Map BtoT = new HashMap(); private Map TtoB = new HashMap(); public synchronized void addPair(Behaviour b, Timer t) { BtoT.put(b, t); TtoB.put(t, b); } public synchronized void removeMapping(Behaviour b) { Timer t = (Timer)BtoT.remove(b); if(t != null) { TtoB.remove(t); } } public synchronized void removeMapping(Timer t) { Behaviour b = (Behaviour)TtoB.remove(t); if(b != null) { BtoT.remove(b); } } public synchronized Timer getPeer(Behaviour b) { return (Timer)BtoT.get(b); } public synchronized Behaviour getPeer(Timer t) { return (Behaviour)TtoB.get(t); } } private static TimerDispatcher theDispatcher; static void setDispatcher(TimerDispatcher td) { if(theDispatcher == null) { theDispatcher = td; theDispatcher.start(); } } static void stopDispatcher() { theDispatcher.stop(); } /** Schedules a restart for a behaviour, after a certain amount of time has passed. @param b The behaviour to restart later. @param millis The amount of time to wait before restarting <code>b</code>. @see jade.core.behaviours.Behaviour#block(long millis) */ public void restartLater(Behaviour b, long millis) { if(millis == 0) return; Timer t = new Timer(System.currentTimeMillis() + millis, this); pendingTimers.addPair(b, t); theDispatcher.add(t); } // Restarts the behaviour associated with t. This method runs within // the time-critical Timer Dispatcher thread. void doTimeOut(Timer t) { Behaviour b = pendingTimers.getPeer(t); if(b != null) { activateBehaviour(b); } } /** Notifies this agent that one of its behaviours has been restarted for some reason. This method clears any timer associated with behaviour object <code>b</code>, and it is unneeded by application level code. To explicitly schedule behaviours, use <code>block()</code> and <code>restart()</code> methods. @param b The behaviour object which was restarted. @see jade.core.behaviours.Behaviour#restart() */ public void notifyRestarted(Behaviour b) { Timer t = pendingTimers.getPeer(b); if(t != null) { pendingTimers.removeMapping(b); theDispatcher.remove(t); } } /** Out of band value for Agent Platform Life Cycle states. */ public static final int AP_MIN = 0; // Hand-made type checking /** Represents the <em>initiated</em> agent state. */ public static final int AP_INITIATED = 1; /** Represents the <em>active</em> agent state. */ public static final int AP_ACTIVE = 2; /** Represents the <em>suspended</em> agent state. */ public static final int AP_SUSPENDED = 3; /** Represents the <em>waiting</em> agent state. */ public static final int AP_WAITING = 4; /** Represents the <em>deleted</em> agent state. */ public static final int AP_DELETED = 5; /** Out of band value for Agent Platform Life Cycle states. */ public static final int AP_MAX = 6; // Hand-made type checking /** These constants represent the various Domain Life Cycle states */ /** Out of band value for Domain Life Cycle states. */ public static final int D_MIN = 9; // Hand-made type checking /** Represents the <em>active</em> agent state. */ public static final int D_ACTIVE = 10; /** Represents the <em>suspended</em> agent state. */ public static final int D_SUSPENDED = 20; /** Represents the <em>retired</em> agent state. */ public static final int D_RETIRED = 30; /** Represents the <em>unknown</em> agent state. */ public static final int D_UNKNOWN = 40; /** Out of band value for Domain Life Cycle states. */ public static final int D_MAX = 41; // Hand-made type checking /** Default value for message queue size. When the number of buffered messages exceeds this value, older messages are discarded according to a <b><em>FIFO</em></b> replacement policy. @see jade.core.Agent#setQueueSize(int newSize) @see jade.core.Agent#getQueueSize() */ public static final int MSG_QUEUE_SIZE = 100; private MessageQueue msgQueue = new MessageQueue(MSG_QUEUE_SIZE); private Vector listeners = new Vector(); private String myName = null; private String myAddress = null; private Object stateLock = new Object(); // Used to make state transitions atomic private Object waitLock = new Object(); // Used for agent waiting private Object suspendLock = new Object(); // Used for agent suspension private Thread myThread; private Scheduler myScheduler; private AssociationTB pendingTimers = new AssociationTB(); /** The <code>Behaviour</code> that is currently executing. @see jade.core.Behaviour */ protected Behaviour currentBehaviour; /** Last message received. @see jade.lang.acl.ACLMessage */ protected ACLMessage currentMessage; // This variable is 'volatile' because is used as a latch to signal // agent suspension and termination from outside world. private volatile int myAPState; // Temporary buffer for agent suspension private int myBufferedState = AP_MIN; private int myDomainState; private Vector blockedBehaviours = new Vector(); private ACLParser myParser = ACLParser.create(); /** Default constructor. */ public Agent() { myAPState = AP_INITIATED; myDomainState = D_UNKNOWN; myScheduler = new Scheduler(this); } /** Method to query the agent local name. @return A <code>String</code> containing the local agent name (e.g. <em>peter</em>). */ public String getLocalName() { return myName; } /** Method to query the agent complete name (<em><b>GUID</b></em>). @return A <code>String</code> containing the complete agent name (e.g. <em>peter@iiop://fipa.org:50/acc</em>). */ public String getName() { return myName + '@' + myAddress; } /** Method to query the agent home address. This is the address of the platform where the agent was created, and will never change during the whole lifetime of the agent. @return A <code>String</code> containing the agent home address (e.g. <em>iiop://fipa.org:50/acc</em>). */ public String getAddress() { return myAddress; } // This is used by the agent container to wait for agent termination void join() { try { myThread.join(); } catch(InterruptedException ie) { ie.printStackTrace(); } } public void setQueueSize(int newSize) throws IllegalArgumentException { msgQueue.setMaxSize(newSize); } /** Reads message queue size. A zero value means that the message queue is unbounded (its size is limited only by amount of available memory). @return The actual size of the message queue. @see jade.core.Agent#setQueueSize(int newSize) */ public int getQueueSize() { return msgQueue.getMaxSize(); } /** Read current agent state. This method can be used to query an agent for its state from the outside. @return the Agent Platform Life Cycle state this agent is currently in. */ public int getState() { return myAPState; } // State transition methods for Agent Platform Life-Cycle /** Make a state transition from <em>initiated</em> to <em>active</em> within Agent Platform Life Cycle. Agents are started automatically by JADE on agent creation and should not be used by application developers, unless creating some kind of agent factory. This method starts the embedded thread of the agent. @param name The local name of the agent. */ public void doStart(String name) { AgentContainerImpl thisContainer = Starter.getContainer(); try { thisContainer.createAgent(name, this, AgentContainer.START); } catch(java.rmi.RemoteException jrre) { jrre.printStackTrace(); } } void doStart(String name, String platformAddress, ThreadGroup myGroup) { // Set this agent's name and address and start its embedded thread if(myAPState == AP_INITIATED) { myAPState = AP_ACTIVE; myName = new String(name); myAddress = new String(platformAddress); myThread = new Thread(myGroup, this); myThread.setName(myName); myThread.setPriority(myGroup.getMaxPriority()); myThread.start(); } } /** Make a state transition from <em>active</em> to <em>initiated</em> within Agent Platform Life Cycle. This method is intended to support agent mobility and is called either by the Agent Platform or by the agent itself to start migration process. <em>This method is currently not implemented.</em> */ public void doMove() { // myAPState = AP_INITIATED; // FIXME: Should do something more } /** Make a state transition from <em>active</em> or <em>waiting</em> to <em>suspended</em> within Agent Platform Life Cycle; the original agent state is saved and will be restored by a <code>doActivate()</code> call. This method can be called from the Agent Platform or from the agent iself and stops all agent activities. Incoming messages for a suspended agent are buffered by the Agent Platform and are delivered as soon as the agent resumes. Calling <code>doSuspend()</code> on a suspended agent has no effect. @see jade.core.Agent#doActivate() */ public void doSuspend() { synchronized(stateLock) { if((myAPState == AP_ACTIVE)||(myAPState == AP_WAITING)) { myBufferedState = myAPState; myAPState = AP_SUSPENDED; } } if(myAPState == AP_SUSPENDED) { if(myThread.equals(Thread.currentThread())) { waitUntilActivate(); } } } /** Make a state transition from <em>suspended</em> to <em>active</em> or <em>waiting</em> (whichever state the agent was in when <code>doSuspend()</code> was called) within Agent Platform Life Cycle. This method is called from the Agent Platform and resumes agent execution. Calling <code>doActivate()</code> when the agent is not suspended has no effect. @see jade.core.Agent#doSuspend() */ public void doActivate() { synchronized(stateLock) { if(myAPState == AP_SUSPENDED) { myAPState = myBufferedState; } } if(myAPState != AP_SUSPENDED) { switch(myBufferedState) { case AP_ACTIVE: activateAllBehaviours(); synchronized(suspendLock) { myBufferedState = AP_MIN; suspendLock.notify(); } break; case AP_WAITING: doWake(); break; } } } /** Make a state transition from <em>active</em> to <em>waiting</em> within Agent Platform Life Cycle. This method can be called by the Agent Platform or by the agent itself and causes the agent to block, stopping all its activities until some event happens. A waiting agent wakes up as soon as a message arrives or when <code>doWake()</code> is called. Calling <code>doWait()</code> on a suspended or waiting agent has no effect. @see jade.core.Agent#doWake() */ public void doWait() { doWait(0); } /** Make a state transition from <em>active</em> to <em>waiting</em> within Agent Platform Life Cycle. This method adds a timeout to the other <code>doWait()</code> version. @param millis The timeout value, in milliseconds. @see jade.core.Agent#doWait() */ public void doWait(long millis) { synchronized(stateLock) { if(myAPState == AP_ACTIVE) myAPState = AP_WAITING; } if(myAPState == AP_WAITING) { if(myThread.equals(Thread.currentThread())) { waitUntilWake(millis); } } } /** Make a state transition from <em>waiting</em> to <em>active</em> within Agent Platform Life Cycle. This method is called from Agent Platform and resumes agent execution. Calling <code>doWake()</code> when an agent is not waiting has no effect. @see jade.core.Agent#doWait() */ public void doWake() { synchronized(stateLock) { if(myAPState == AP_WAITING) { myAPState = AP_ACTIVE; } } if(myAPState == AP_ACTIVE) { activateAllBehaviours(); synchronized(waitLock) { waitLock.notify(); // Wakes up the embedded thread } } } // This method handles both the case when the agents decides to exit // and the case in which someone else kills him from outside. /** Make a state transition from <em>active</em>, <em>suspended</em> or <em>waiting</em> to <em>deleted</em> state within Agent Platform Life Cycle, thereby destroying the agent. This method can be called either from the Agent Platform or from the agent itself. Calling <code>doDelete()</code> on an already deleted agent has no effect. */ public void doDelete() { if(myAPState != AP_DELETED) { myAPState = AP_DELETED; if(!myThread.equals(Thread.currentThread())) myThread.interrupt(); } } /** This method is the main body of every agent. It can handle automatically <b>AMS</b> registration and deregistration and provides startup and cleanup hooks for application programmers to put their specific code into. @see jade.core.Agent#setup() @see jade.core.Agent#takeDown() */ public final void run() { try{ registerWithAMS(null,Agent.AP_ACTIVE,null,null,null); setup(); mainLoop(); } catch(InterruptedException ie) { // Do Nothing, since this is a killAgent from outside } catch(InterruptedIOException iioe) { // Do nothing, since this is a killAgent from outside } catch(Exception e) { System.err.println("*** Uncaught Exception for agent " + myName + " ***"); e.printStackTrace(); } catch(AgentDeathError ade) { // Do Nothing, since this is a killAgent from outside } finally { takeDown(); destroy(); } } /** This protected method is an empty placeholder for application specific startup code. Agent developers can override it to provide necessary behaviour. When this method is called the agent has been already registered with the Agent Platform <b>AMS</b> and is able to send and receive messages. However, the agent execution model is still sequential and no behaviour scheduling is active yet. This method can be used for ordinary startup tasks such as <b>DF</b> registration, but is essential to add at least a <code>Behaviour</code> object to the agent, in order for it to be able to do anything. @see jade.core.Agent#addBehaviour(Behaviour b) @see jade.core.Behaviour */ protected void setup() {} /** This protected method is an empty placeholder for application specific cleanup code. Agent developers can override it to provide necessary behaviour. When this method is called the agent has not deregistered itself with the Agent Platform <b>AMS</b> and is still able to exchange messages with other agents. However, no behaviour scheduling is active anymore and the Agent Platform Life Cycle state is already set to <em>deleted</em>. This method can be used for ordinary cleanup tasks such as <b>DF</b> deregistration, but explicit removal of all agent behaviours is not needed. */ protected void takeDown() {} private void mainLoop() throws InterruptedException, InterruptedIOException { while(myAPState != AP_DELETED) { // Select the next behaviour to execute currentBehaviour = myScheduler.schedule(); // Just do it! currentBehaviour.action(); // Check for Agent state changes switch(myAPState) { case AP_WAITING: waitUntilWake(0); break; case AP_SUSPENDED: waitUntilActivate(); break; case AP_DELETED: return; case AP_ACTIVE: break; } // When it is needed no more, delete it from the behaviours queue if(currentBehaviour.done()) { myScheduler.remove(currentBehaviour); currentBehaviour = null; } else if(!currentBehaviour.isRunnable()) { // Remove blocked behaviours from scheduling queue and put it // in blocked behaviours queue myScheduler.remove(currentBehaviour); blockedBehaviours.addElement(currentBehaviour); currentBehaviour = null; } // Now give CPU control to other agents Thread.yield(); } } private void waitUntilWake(long millis) { synchronized(waitLock) { long timeToWait = millis; while(myAPState == AP_WAITING) { try { long startTime = System.currentTimeMillis(); waitLock.wait(timeToWait); // Blocks on waiting state monitor for a while long elapsedTime = System.currentTimeMillis() - startTime; timeToWait -= elapsedTime; // If this was a timed wait and the total time has passed, wake up. if((millis != 0) && (timeToWait <= 0)) myAPState = AP_ACTIVE; } catch(InterruptedException ie) { myAPState = AP_DELETED; throw new AgentDeathError(); } } } } private void waitUntilActivate() { synchronized(suspendLock) { while(myAPState == AP_SUSPENDED) { try { suspendLock.wait(); // Blocks on suspended state monitor } catch(InterruptedException ie) { myAPState = AP_DELETED; throw new AgentDeathError(); } } } } private void destroy() { try { deregisterWithAMS(); } catch(FIPAException fe) { fe.printStackTrace(); } notifyDestruction(); } /** This method adds a new behaviour to the agent. This behaviour will be executed concurrently with all the others, using a cooperative round robin scheduling. This method is typically called from an agent <code>setup()</code> to fire off some initial behaviour, but can also be used to spawn new behaviours dynamically. @param b The new behaviour to add to the agent. @see jade.core.Agent#setup() @see jade.core.Behaviour */ public void addBehaviour(Behaviour b) { myScheduler.add(b); } /** This method removes a given behaviour from the agent. This method is called automatically when a top level behaviour terminates, but can also be called from a behaviour to terminate itself or some other behaviour. @param b The behaviour to remove. @see jade.core.Behaviour */ public void removeBehaviour(Behaviour b) { myScheduler.remove(b); } /** Send an <b>ACL</b> message to another agent. This methods sends a message to the agent specified in <code>:receiver</code> message field (more than one agent can be specified as message receiver). @param msg An ACL message object containing the actual message to send. @see jade.lang.acl.ACLMessage */ public final void send(ACLMessage msg) { if(msg.getSource() == null) msg.setSource(myName); CommEvent event = new CommEvent(this, msg); broadcastEvent(event); } /** Send an <b>ACL</b> message to the agent contained in a given <code>AgentGroup</code>. This method allows simple message multicast to be done. A similar result can be obtained putting many agent names in <code>:receiver</code> message field; the difference is that in that case every receiver agent can read all other receivers' names, whereas this method hides multicasting to receivers. @param msg An ACL message object containing the actual message to send. @param g An agent group object holding all receivers names. @see jade.lang.acl.ACLMessage @see jade.core.AgentGroup */ public final void send(ACLMessage msg, AgentGroup g) { if(msg.getSource() == null) msg.setSource(myName); CommEvent event = new CommEvent(this, msg, g); broadcastEvent(event); } /** Receives an <b>ACL</b> message from the agent message queue. This method is non-blocking and returns the first message in the queue, if any. Therefore, polling and busy waiting is required to wait for the next message sent using this method. @return A new ACL message, or <code>null</code> if no message is present. @see jade.lang.acl.ACLMessage */ public final ACLMessage receive() { synchronized(waitLock) { if(msgQueue.isEmpty()) { return null; } else { currentMessage = msgQueue.removeFirst(); return currentMessage; } } } /** Receives an <b>ACL</b> message matching a given template. This method is non-blocking and returns the first matching message in the queue, if any. Therefore, polling and busy waiting is required to wait for a specific kind of message using this method. @param pattern A message template to match received messages against. @return A new ACL message matching the given template, or <code>null</code> if no such message is present. @see jade.lang.acl.ACLMessage @see jade.lang.acl.MessageTemplate */ public final ACLMessage receive(MessageTemplate pattern) { ACLMessage msg = null; synchronized(waitLock) { Iterator messages = msgQueue.iterator(); while(messages.hasNext()) { ACLMessage cursor = (ACLMessage)messages.next(); if(pattern.match(cursor)) { msg = cursor; msgQueue.remove(cursor); currentMessage = cursor; break; // Exit while loop } } } return msg; } /** Receives an <b>ACL</b> message from the agent message queue. This method is blocking and suspends the whole agent until a message is available in the queue. JADE provides a special behaviour named <code>ReceiverBehaviour</code> to wait for a message within a behaviour without suspending all the others and without wasting CPU time doing busy waiting. @return A new ACL message, blocking the agent until one is available. @see jade.lang.acl.ACLMessage @see jade.core.ReceiverBehaviour */ public final ACLMessage blockingReceive() { ACLMessage msg = null; while(msg == null) { msg = blockingReceive(0); } return msg; } /** Receives an <b>ACL</b> message from the agent message queue, waiting at most a specified amount of time. @param millis The maximum amount of time to wait for the message. @return A new ACL message, or <code>null</code> if the specified amount of time passes without any message reception. */ public final ACLMessage blockingReceive(long millis) { ACLMessage msg = receive(); if(msg == null) { doWait(millis); msg = receive(); } return msg; } /** Receives an <b>ACL</b> message matching a given message template. This method is blocking and suspends the whole agent until a message is available in the queue. JADE provides a special behaviour named <code>ReceiverBehaviour</code> to wait for a specific kind of message within a behaviour without suspending all the others and without wasting CPU time doing busy waiting. @param pattern A message template to match received messages against. @return A new ACL message matching the given template, blocking until such a message is available. @see jade.lang.acl.ACLMessage @see jade.lang.acl.MessageTemplate @see jade.core.ReceiverBehaviour */ public final ACLMessage blockingReceive(MessageTemplate pattern) { ACLMessage msg = null; while(msg == null) { msg = blockingReceive(pattern, 0); } return msg; } /** Receives an <b>ACL</b> message matching a given message template, waiting at most a specified time. @param pattern A message template to match received messages against. @param millis The amount of time to wait for the message, in milliseconds. @return A new ACL message matching the given template, or <code>null</code> if no suitable message was received within <code>millis</code> milliseconds. @see jade.core.Agent#blockingReceive() */ public final ACLMessage blockingReceive(MessageTemplate pattern, long millis) { ACLMessage msg = receive(pattern); long timeToWait = millis; while(msg == null) { long startTime = System.currentTimeMillis(); doWait(timeToWait); long elapsedTime = System.currentTimeMillis() - startTime; timeToWait -= elapsedTime; msg = receive(pattern); if((millis != 0) && (timeToWait <= 0)) break; } return msg; } /** Puts a received <b>ACL</b> message back into the message queue. This method can be used from an agent behaviour when it realizes it read a message of interest for some other behaviour. The message is put in front of the message queue, so it will be the first returned by a <code>receive()</code> call. @see jade.core.Agent#receive() */ public final void putBack(ACLMessage msg) { synchronized(waitLock) { msgQueue.addFirst(msg); } } /** @deprecated Builds an ACL message from a character stream. Now <code>ACLMessage</code> class has this capabilities itself, through <code>fromText()</code> method. @see jade.lang.acl.ACLMessage#fromText(Reader r) */ public ACLMessage parse(Reader text) { ACLMessage msg = null; try { msg = myParser.parse(text); } catch(ParseException pe) { pe.printStackTrace(); } catch(TokenMgrError tme) { tme.printStackTrace(); } return msg; } private ACLMessage FipaRequestMessage(String dest, String replyString) { ACLMessage request = new ACLMessage("request"); request.setSource(myName); request.removeAllDests(); request.addDest(dest); request.setLanguage("SL0"); request.setOntology("fipa-agent-management"); request.setProtocol("fipa-request"); request.setReplyWith(replyString); return request; } private String doFipaRequestClient(ACLMessage request, String replyString) throws FIPAException { send(request); ACLMessage reply = blockingReceive(MessageTemplate.MatchReplyTo(replyString)); if(reply.getType().equalsIgnoreCase("agree")) { reply = blockingReceive(MessageTemplate.MatchReplyTo(replyString)); if(!reply.getType().equalsIgnoreCase("inform")) { String content = reply.getContent(); StringReader text = new StringReader(content); throw FIPAException.fromText(text); } else { String content = reply.getContent(); return content; } } else { String content = reply.getContent(); StringReader text = new StringReader(content); throw FIPAException.fromText(text); } } /** Register this agent with Agent Platform <b>AMS</b>. While this task can be accomplished with regular message passing according to <b>FIPA</b> protocols, this method is meant to ease this common duty. However, since <b>AMS</b> registration and deregistration are automatic in JADE, this method should not be used by application programmers. Some parameters here are optional, and <code>null</code> can safely be passed for them. @param signature An optional signature string, used for security reasons. @param APState The Agent Platform state of the agent; must be a valid state value (typically, <code>Agent.AP_ACTIVE</code> constant is passed). @param delegateAgent An optional delegate agent name. @param forwardAddress An optional forward address. @param ownership An optional ownership string. @exception FIPAException A suitable exception can be thrown when a <code>refuse</code> or <code>failure</code> messages are received from the AMS to indicate some error condition. */ public void registerWithAMS(String signature, int APState, String delegateAgent, String forwardAddress, String ownership) throws FIPAException { String replyString = myName + "-ams-registration-" + (new Date()).getTime(); ACLMessage request = FipaRequestMessage("ams", replyString); // Build an AMS action object for the request AgentManagementOntology.AMSAction a = new AgentManagementOntology.AMSAction(); AgentManagementOntology.AMSAgentDescriptor amsd = new AgentManagementOntology.AMSAgentDescriptor(); amsd.setName(getName()); amsd.setAddress(getAddress()); amsd.setAPState(APState); amsd.setDelegateAgentName(delegateAgent); amsd.setForwardAddress(forwardAddress); amsd.setOwnership(ownership); a.setName(AgentManagementOntology.AMSAction.REGISTERAGENT); a.setArg(amsd); // Convert it to a String and write it in content field of the request StringWriter text = new StringWriter(); a.toText(text); request.setContent(text.toString()); // Send message and collect reply doFipaRequestClient(request, replyString); } /** Authenticate this agent with Agent Platform <b>AMS</b>. While this task can be accomplished with regular message passing according to <b>FIPA</b> protocols, this method is meant to ease this common duty. Some parameters here are optional, and <code>null</code> can safely be passed for them. @param signature An optional signature string, used for security reasons. @param APState The Agent Platform state of the agent; must be a valid state value (typically, <code>Agent.AP_ACTIVE</code> constant is passed). @param delegateAgent An optional delegate agent name. @param forwardAddress An optional forward address. @param ownership An optional ownership string. @exception FIPAException A suitable exception can be thrown when a <code>refuse</code> or <code>failure</code> messages are received from the AMS to indicate some error condition. <em>This method is currently not implemented.</em> */ public void authenticateWithAMS(String signature, int APState, String delegateAgent, String forwardAddress, String ownership) throws FIPAException { // FIXME: Not implemented } /** Deregister this agent with Agent Platform <b>AMS</b>. While this task can be accomplished with regular message passing according to <b>FIPA</b> protocols, this method is meant to ease this common duty. However, since <b>AMS</b> registration and deregistration are automatic in JADE, this method should not be used by application programmers. @exception FIPAException A suitable exception can be thrown when a <code>refuse</code> or <code>failure</code> messages are received from the AMS to indicate some error condition. */ public void deregisterWithAMS() throws FIPAException { String replyString = myName + "-ams-deregistration-" + (new Date()).getTime(); // Get a semi-complete request message ACLMessage request = FipaRequestMessage("ams", replyString); // Build an AMS action object for the request AgentManagementOntology.AMSAction a = new AgentManagementOntology.AMSAction(); AgentManagementOntology.AMSAgentDescriptor amsd = new AgentManagementOntology.AMSAgentDescriptor(); amsd.setName(getName()); a.setName(AgentManagementOntology.AMSAction.DEREGISTERAGENT); a.setArg(amsd); // Convert it to a String and write it in content field of the request StringWriter text = new StringWriter(); a.toText(text); request.setContent(text.toString()); // Send message and collect reply doFipaRequestClient(request, replyString); } /** Modifies the data about this agent kept by Agent Platform <b>AMS</b>. While this task can be accomplished with regular message passing according to <b>FIPA</b> protocols, this method is meant to ease this common duty. Some parameters here are optional, and <code>null</code> can safely be passed for them. When a non null parameter is passed, it replaces the value currently stored inside <b>AMS</b> agent. @param signature An optional signature string, used for security reasons. @param APState The Agent Platform state of the agent; must be a valid state value (typically, <code>Agent.AP_ACTIVE</code> constant is passed). @param delegateAgent An optional delegate agent name. @param forwardAddress An optional forward address. @param ownership An optional ownership string. @exception FIPAException A suitable exception can be thrown when a <code>refuse</code> or <code>failure</code> messages are received from the AMS to indicate some error condition. */ public void modifyAMSRegistration(String signature, int APState, String delegateAgent, String forwardAddress, String ownership) throws FIPAException { String replyString = myName + "-ams-modify-" + (new Date()).getTime(); ACLMessage request = FipaRequestMessage("ams", replyString); // Build an AMS action object for the request AgentManagementOntology.AMSAction a = new AgentManagementOntology.AMSAction(); AgentManagementOntology.AMSAgentDescriptor amsd = new AgentManagementOntology.AMSAgentDescriptor(); amsd.setName(getName()); amsd.setAddress(getAddress()); amsd.setAPState(APState); amsd.setDelegateAgentName(delegateAgent); amsd.setForwardAddress(forwardAddress); amsd.setOwnership(ownership); a.setName(AgentManagementOntology.AMSAction.MODIFYAGENT); a.setArg(amsd); // Convert it to a String and write it in content field of the request StringWriter text = new StringWriter(); a.toText(text); request.setContent(text.toString()); // Send message and collect reply doFipaRequestClient(request, replyString); } /** This method uses Agent Platform <b>ACC</b> agent to forward an ACL message. Calling this method is exactly the same as calling <code>send()</code>, only slower, since the message is first sent to the ACC using a <code>fipa-request</code> standard protocol, and then bounced to actual destination agent. @param msg The ACL message to send. @exception FIPAException A suitable exception can be thrown when a <code>refuse</code> or <code>failure</code> messages are received from the ACC to indicate some error condition. @see jade.core.Agent#send(ACLMessage msg) */ public void forwardWithACC(ACLMessage msg) throws FIPAException { String replyString = myName + "-acc-forward-" + (new Date()).getTime(); ACLMessage request = FipaRequestMessage("acc", replyString); // Build an ACC action object for the request AgentManagementOntology.ACCAction a = new AgentManagementOntology.ACCAction(); a.setName(AgentManagementOntology.ACCAction.FORWARD); a.setArg(msg); // Convert it to a String and write it in content field of the request StringWriter text = new StringWriter(); a.toText(text); request.setContent(text.toString()); // Send message and collect reply doFipaRequestClient(request, replyString); } /** Register this agent with a <b>DF</b> agent. While this task can be accomplished with regular message passing according to <b>FIPA</b> protocols, this method is meant to ease this common duty. @param dfName The GUID of the <b>DF</b> agent to register with. @param dfd A <code>DFAgentDescriptor</code> object containing all data necessary to the registration. @exception FIPAException A suitable exception can be thrown when a <code>refuse</code> or <code>failure</code> messages are received from the DF to indicate some error condition. @see jade.domain.AgentManagementOntology.DFAgentDescriptor */ public void registerWithDF(String dfName, AgentManagementOntology.DFAgentDescriptor dfd) throws FIPAException { String replyString = myName + "-df-register-" + (new Date()).getTime(); ACLMessage request = FipaRequestMessage(dfName, replyString); // Build a DF action object for the request AgentManagementOntology.DFAction a = new AgentManagementOntology.DFAction(); a.setName(AgentManagementOntology.DFAction.REGISTER); a.setActor(dfName); a.setArg(dfd); // Convert it to a String and write it in content field of the request StringWriter text = new StringWriter(); a.toText(text); request.setContent(text.toString()); // Send message and collect reply doFipaRequestClient(request, replyString); } /** Deregister this agent from a <b>DF</b> agent. While this task can be accomplished with regular message passing according to <b>FIPA</b> protocols, this method is meant to ease this common duty. @param dfName The GUID of the <b>DF</b> agent to deregister from. @param dfd A <code>DFAgentDescriptor</code> object containing all data necessary to the deregistration. @exception FIPAException A suitable exception can be thrown when a <code>refuse</code> or <code>failure</code> messages are received from the DF to indicate some error condition. @see jade.domain.AgentManagementOntology.DFAgentDescriptor */ public void deregisterWithDF(String dfName, AgentManagementOntology.DFAgentDescriptor dfd) throws FIPAException { String replyString = myName + "-df-deregister-" + (new Date()).getTime(); ACLMessage request = FipaRequestMessage(dfName, replyString); // Build a DF action object for the request AgentManagementOntology.DFAction a = new AgentManagementOntology.DFAction(); a.setName(AgentManagementOntology.DFAction.DEREGISTER); a.setActor(dfName); a.setArg(dfd); // Convert it to a String and write it in content field of the request StringWriter text = new StringWriter(); a.toText(text); request.setContent(text.toString()); // Send message and collect reply doFipaRequestClient(request, replyString); } /** Modifies data about this agent contained within a <b>DF</b> agent. While this task can be accomplished with regular message passing according to <b>FIPA</b> protocols, this method is meant to ease this common duty. @param dfName The GUID of the <b>DF</b> agent holding the data to be changed. @param dfd A <code>DFAgentDescriptor</code> object containing all new data values; every non null slot value replaces the corresponding value held inside the <b>DF</b> agent. @exception FIPAException A suitable exception can be thrown when a <code>refuse</code> or <code>failure</code> messages are received from the DF to indicate some error condition. @see jade.domain.AgentManagementOntology.DFAgentDescriptor */ public void modifyDFData(String dfName, AgentManagementOntology.DFAgentDescriptor dfd) throws FIPAException { String replyString = myName + "-df-modify-" + (new Date()).getTime(); ACLMessage request = FipaRequestMessage(dfName, replyString); // Build a DF action object for the request AgentManagementOntology.DFAction a = new AgentManagementOntology.DFAction(); a.setName(AgentManagementOntology.DFAction.MODIFY); a.setActor(dfName); a.setArg(dfd); // Convert it to a String and write it in content field of the request StringWriter text = new StringWriter(); a.toText(text); request.setContent(text.toString()); // Send message and collect reply doFipaRequestClient(request, replyString); } /** Searches for data contained within a <b>DF</b> agent. While this task can be accomplished with regular message passing according to <b>FIPA</b> protocols, this method is meant to ease this common duty. Nevertheless, a complete, powerful search interface is provided; search constraints can be given and recursive searches are possible. The only shortcoming is that this method blocks the whole agent until the search terminates. A special <code>SearchDFBehaviour</code> can be used to perform <b>DF</b> searches without blocking. @param dfName The GUID of the <b>DF</b> agent to start search from. @param dfd A <code>DFAgentDescriptor</code> object containing data to search for; this parameter is used as a template to match data against. @param constraints A <code>Vector</code> that must be filled with all <code>Constraint</code> objects to apply to the current search. This can be <code>null</code> if no search constraints are required. @return A <code>DFSearchResult</code> object containing all found <code>DFAgentDescriptor</code> objects matching the given descriptor, subject to given search constraints for search depth and result size. @exception FIPAException A suitable exception can be thrown when a <code>refuse</code> or <code>failure</code> messages are received from the DF to indicate some error condition. @see jade.domain.AgentManagementOntology.DFAgentDescriptor @see java.util.Vector @see jade.domain.AgentManagementOntology.Constraint @see jade.domain.AgentManagementOntology.DFSearchResult */ public AgentManagementOntology.DFSearchResult searchDF(String dfName, AgentManagementOntology.DFAgentDescriptor dfd, Vector constraints) throws FIPAException { String replyString = myName + "-df-search-" + (new Date()).getTime(); ACLMessage request = FipaRequestMessage(dfName, replyString); // Build a DF action object for the request AgentManagementOntology.DFSearchAction a = new AgentManagementOntology.DFSearchAction(); a.setName(AgentManagementOntology.DFAction.SEARCH); a.setActor(dfName); a.setArg(dfd); if(constraints == null) { AgentManagementOntology.Constraint c = new AgentManagementOntology.Constraint(); c.setName(AgentManagementOntology.Constraint.DFDEPTH); c.setFn(AgentManagementOntology.Constraint.EXACTLY); c.setArg(1); a.addConstraint(c); } else { // Put constraints into action Iterator i = constraints.iterator(); while(i.hasNext()) { AgentManagementOntology.Constraint c = (AgentManagementOntology.Constraint)i.next(); a.addConstraint(c); } } // Convert it to a String and write it in content field of the request StringWriter textOut = new StringWriter(); a.toText(textOut); request.setContent(textOut.toString()); // Send message and collect reply String content = doFipaRequestClient(request, replyString); // Extract agent descriptors from reply message AgentManagementOntology.DFSearchResult found = null; StringReader textIn = new StringReader(content); try { found = AgentManagementOntology.DFSearchResult.fromText(textIn); } catch(jade.domain.ParseException jdpe) { jdpe.printStackTrace(); } catch(jade.domain.TokenMgrError jdtme) { jdtme.printStackTrace(); } return found; } // Event handling methods // Broadcast communication event to registered listeners private void broadcastEvent(CommEvent event) { Iterator i = listeners.iterator(); while(i.hasNext()) { CommListener l = (CommListener)i.next(); l.CommHandle(event); } } // Register a new listener public final void addCommListener(CommListener l) { listeners.add(l); } // Remove a registered listener public final void removeCommListener(CommListener l) { listeners.remove(l); } // Notify listeners of the destruction of the current agent private void notifyDestruction() { Iterator i = listeners.iterator(); while(i.hasNext()) { CommListener l = (CommListener)i.next(); l.endSource(myName); } } private void activateBehaviour(Behaviour b) { Behaviour root = b.root(); blockedBehaviours.remove(root); b.restart(); myScheduler.add(root); } private void activateAllBehaviours() { // Put all blocked behaviours back in ready queue, // atomically with respect to the Scheduler object synchronized(myScheduler) { while(!blockedBehaviours.isEmpty()) { Behaviour b = (Behaviour)blockedBehaviours.lastElement(); blockedBehaviours.removeElementAt(blockedBehaviours.size() - 1); b.restart(); myScheduler.add(b); } } } /** Put a received message into the agent message queue. The mesage is put at the back end of the queue. This method is called by JADE runtime system when a message arrives, but can also be used by an agent, and is just the same as sending a message to oneself (though slightly faster). @param msg The ACL message to put in the queue. @see jade.core.Agent#send(ACLMessage msg) */ public final void postMessage (ACLMessage msg) { synchronized(waitLock) { if(msg != null) msgQueue.addLast(msg); doWake(); } } }
package jade.core; import java.io.Reader; import java.io.StringReader; import java.io.StringWriter; import java.io.Serializable; import java.io.InputStream; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.OutputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import java.io.IOException; import java.io.InterruptedIOException; import java.util.Date; import java.util.Iterator; import java.util.Map; import java.util.HashMap; import java.util.Vector; import jade.core.behaviours.Behaviour; import jade.lang.Codec; import jade.lang.acl.*; import jade.onto.Name; import jade.onto.Frame; import jade.onto.Ontology; import jade.onto.OntologyException; import jade.domain.AgentManagementOntology; import jade.domain.FIPAException; /** The <code>Agent</code> class is the common superclass for user defined software agents. It provides methods to perform basic agent tasks, such as: <ul> <li> <b> Message passing using <code>ACLMessage</code> objects, both unicast and multicast with optional pattern matching. </b> <li> <b> Complete Agent Platform life cycle support, including starting, suspending and killing an agent. </b> <li> <b> Scheduling and execution of multiple concurrent activities. </b> <li> <b> Simplified interaction with <em>FIPA</em> system agents for automating common agent tasks (DF registration, etc.). </b> </ul> Application programmers must write their own agents as <code>Agent</code> subclasses, adding specific behaviours as needed and exploiting <code>Agent</code> class capabilities. @author Giovanni Rimassa - Universita` di Parma @version $Date$ $Revision$ */ public class Agent implements Runnable, Serializable, CommBroadcaster { // This inner class is used to force agent termination when a signal // from the outside is received private class AgentDeathError extends Error { AgentDeathError() { super("Agent " + Thread.currentThread().getName() + " has been terminated."); } } private static class AgentInMotionError extends Error { AgentInMotionError() { super("Agent " + Thread.currentThread().getName() + " is about to move or be cloned."); } } // This class manages bidirectional associations between Timer and // Behaviour objects, using hash tables. This class is fully // synchronized because is accessed both by agent internal thread // and high priority Timer Dispatcher thread. private static class AssociationTB { private Map BtoT = new HashMap(); private Map TtoB = new HashMap(); public synchronized void addPair(Behaviour b, Timer t) { BtoT.put(b, t); TtoB.put(t, b); } public synchronized void removeMapping(Behaviour b) { Timer t = (Timer)BtoT.remove(b); if(t != null) { TtoB.remove(t); } } public synchronized void removeMapping(Timer t) { Behaviour b = (Behaviour)TtoB.remove(t); if(b != null) { BtoT.remove(b); } } public synchronized Timer getPeer(Behaviour b) { return (Timer)BtoT.get(b); } public synchronized Behaviour getPeer(Timer t) { return (Behaviour)TtoB.get(t); } } private static TimerDispatcher theDispatcher; static void setDispatcher(TimerDispatcher td) { if(theDispatcher == null) { theDispatcher = td; theDispatcher.start(); } } static void stopDispatcher() { theDispatcher.stop(); } /** Schedules a restart for a behaviour, after a certain amount of time has passed. @param b The behaviour to restart later. @param millis The amount of time to wait before restarting <code>b</code>. @see jade.core.behaviours.Behaviour#block(long millis) */ public void restartLater(Behaviour b, long millis) { if(millis == 0) return; Timer t = new Timer(System.currentTimeMillis() + millis, this); pendingTimers.addPair(b, t); theDispatcher.add(t); } // Restarts the behaviour associated with t. This method runs within // the time-critical Timer Dispatcher thread. void doTimeOut(Timer t) { Behaviour b = pendingTimers.getPeer(t); if(b != null) { activateBehaviour(b); } } /** Notifies this agent that one of its behaviours has been restarted for some reason. This method clears any timer associated with behaviour object <code>b</code>, and it is unneeded by application level code. To explicitly schedule behaviours, use <code>block()</code> and <code>restart()</code> methods. @param b The behaviour object which was restarted. @see jade.core.behaviours.Behaviour#restart() */ public void notifyRestarted(Behaviour b) { Timer t = pendingTimers.getPeer(b); if(t != null) { pendingTimers.removeMapping(b); theDispatcher.remove(t); } } /** Out of band value for Agent Platform Life Cycle states. */ public static final int AP_MIN = 0; // Hand-made type checking /** Represents the <em>initiated</em> agent state. */ public static final int AP_INITIATED = 1; /** Represents the <em>active</em> agent state. */ public static final int AP_ACTIVE = 2; /** Represents the <em>suspended</em> agent state. */ public static final int AP_SUSPENDED = 3; /** Represents the <em>waiting</em> agent state. */ public static final int AP_WAITING = 4; /** Represents the <em>deleted</em> agent state. */ public static final int AP_DELETED = 5; /** Represents the <code>transit</code> agent state. */ public static final int AP_TRANSIT = 6; // Non compliant states, used internally. Maybe report to FIPA... /** Represents the <code>copy</code> agent state. */ static final int AP_COPY = 7; /** Represents the <code>gone</code> agent state. This is the state the original instance of an agent goes into when a migration transaction successfully commits. */ static final int AP_GONE = 8; /** Out of band value for Agent Platform Life Cycle states. */ public static final int AP_MAX = 9; // Hand-made type checking /** These constants represent the various Domain Life Cycle states */ /** Out of band value for Domain Life Cycle states. */ public static final int D_MIN = 9; // Hand-made type checking /** Represents the <em>active</em> agent state. */ public static final int D_ACTIVE = 10; /** Represents the <em>suspended</em> agent state. */ public static final int D_SUSPENDED = 20; /** Represents the <em>retired</em> agent state. */ public static final int D_RETIRED = 30; /** Represents the <em>unknown</em> agent state. */ public static final int D_UNKNOWN = 40; /** Out of band value for Domain Life Cycle states. */ public static final int D_MAX = 41; // Hand-made type checking /** Default value for message queue size. When the number of buffered messages exceeds this value, older messages are discarded according to a <b><em>FIFO</em></b> replacement policy. @see jade.core.Agent#setQueueSize(int newSize) @see jade.core.Agent#getQueueSize() */ public static final int MSG_QUEUE_SIZE = 100; private MessageQueue msgQueue = new MessageQueue(MSG_QUEUE_SIZE); private transient Vector listeners = new Vector(); private String myName = null; private String myAddress = null; private transient Object stateLock = new Object(); // Used to make state transitions atomic private transient Object waitLock = new Object(); // Used for agent waiting private transient Object suspendLock = new Object(); // Used for agent suspension private transient Thread myThread; private Scheduler myScheduler; private transient AssociationTB pendingTimers = new AssociationTB(); // Free running counter that increments by one for each message // received. private int messageCounter = 0 ; private transient Map languages = new HashMap(); private transient Map ontologies = new HashMap(); /** The <code>Behaviour</code> that is currently executing. @see jade.core.behaviours.Behaviour */ protected Behaviour currentBehaviour; /** Last message received. @see jade.lang.acl.ACLMessage */ protected ACLMessage currentMessage; // This variable is 'volatile' because is used as a latch to signal // agent suspension and termination from outside world. private volatile int myAPState; // These two variables are used as temporary buffers for // mobility-related parameters private transient Location myDestination; private transient String myNewName; // Temporary buffer for agent suspension private int myBufferedState = AP_MIN; private int myDomainState; private Vector blockedBehaviours = new Vector(); /** Default constructor. */ public Agent() { myAPState = AP_INITIATED; myDomainState = D_UNKNOWN; myScheduler = new Scheduler(this); } /** Method to query the agent local name. @return A <code>String</code> containing the local agent name (e.g. <em>peter</em>). */ public String getLocalName() { return myName; } /** Method to query the agent complete name (<em><b>GUID</b></em>). @return A <code>String</code> containing the complete agent name (e.g. <em>peter@iiop://fipa.org:50/acc</em>). */ public String getName() { return myName + '@' + myAddress; } /** Method to query the agent home address. This is the address of the platform where the agent was created, and will never change during the whole lifetime of the agent. @return A <code>String</code> containing the agent home address (e.g. <em>iiop://fipa.org:50/acc</em>). */ public String getAddress() { return myAddress; } /** Adds a Content Language codec to the agent capabilities. When an agent wants to provide automatic support for a specific content language, it must use an implementation of the <code>Codec</code> interface for the specific content language, and add it to its languages table with this method. @param languageName The symbolic name to use for the language. @param translator A translator for the specific content language, able to translate back and forth between text strings and Frame objects. @see jade.core.Agent#deregisterLanguage(String languageName) @see jade.lang.Codec */ public void registerLanguage(String languageName, Codec translator) { languages.put(new Name(languageName), translator); } /** Looks a content language up into the supported languages table. @param languageName The name of the desired content language. @return The translator for the given language, or <code>null</code> if no translator was found. */ public Codec lookupLanguage(String languageName) { return (Codec)languages.get(new Name(languageName)); } /** Removes a Content Language from the agent capabilities. @param languageName The name of the language to remove. @see jade.core.Agent#registerLanguage(String languageName, Codec translator) */ public void deregisterLanguage(String languageName) { languages.remove(new Name(languageName)); } /** Adds an Ontology to the agent capabilities. When an agent wants to provide automatic support for a specific ontology, it must use an implementation of the <code>Ontology</code> interface for the specific ontology and add it to its ontologies table with this method. @param ontologyName The symbolic name to use for the ontology @param o An ontology object, that is able to convert back and forth between Frame objects and application specific Java objects representing concepts. @see jade.core.Agent#deregisterOntology(String ontologyName) @see jade.onto.Ontology */ public void registerOntology(String ontologyName, Ontology o) { ontologies.put(new Name(ontologyName), o); } /** Looks an ontology up into the supported ontologies table. @param ontologyName The name of the desired ontology. @return The given ontology, or <code>null</code> if no such named ontology was found. */ public Ontology lookupOntology(String ontologyName) { return (Ontology)ontologies.get(new Name(ontologyName)); } /** Removes an Ontology from the agent capabilities. @param ontologyName The name of the ontology to remove. @see jade.core.Agent#registerOntology(String ontologyName, Ontology o) */ public void deregisterOntology(String ontologyName) { ontologies.remove(new Name(ontologyName)); } /** Builds a Java object out of an ACL message. This method uses the <code>:language</code> slot to select a content language and the <code>:ontology</code> slot to select an ontology. Then the <code>:content</code> slot is interpreted according to the chosen language and ontology, to build an object of a user defined class. @param msg The ACL message from which a suitable Java object will be built. @return A new Java object representing the message content in the given content language and ontology. @exception jade.domain.FIPAException If some problem related to the content language or to the ontology is detected. @see jade.core.Agent#registerLanguage(String languageName, Codec translator) @see jade.core.Agent#registerOntology(String ontologyName, Ontology o) */ public Object buildFrom(ACLMessage msg) throws FIPAException { Codec c = lookupLanguage(msg.getLanguage()); if(c == null) throw new FIPAException("Unknown Content Language"); Ontology o = lookupOntology(msg.getOntology()); if(o == null) throw new FIPAException("Unknown Ontology"); try { Frame f = c.decode(msg.getContent(), o); return o.createObject(f); } catch(Codec.CodecException cce) { // cce.printStackTrace(); throw new FIPAException("Codec error: " + cce.getMessage()); } catch(OntologyException oe) { // oe.printStackTrace(); throw new FIPAException("Ontology error: " + oe.getMessage()); } } public void fillContent(ACLMessage msg, Object content, String roleName) throws FIPAException { Codec c = lookupLanguage(msg.getLanguage()); if(c == null) throw new FIPAException("Unknown Content Language"); Ontology o = lookupOntology(msg.getOntology()); if(o == null) throw new FIPAException("Unknown Ontology"); try { Frame f = o.createFrame(content, roleName); String s = c.encode(f, o); msg.setContent(s); } catch(OntologyException oe) { oe.printStackTrace(); throw new FIPAException("Ontology error: " + oe.getMessage()); } } // This is used by the agent container to wait for agent termination void join() { try { myThread.join(); } catch(InterruptedException ie) { ie.printStackTrace(); } } public void setQueueSize(int newSize) throws IllegalArgumentException { msgQueue.setMaxSize(newSize); } /** Reads message queue size. A zero value means that the message queue is unbounded (its size is limited only by amount of available memory). @return The actual size of the message queue. @see jade.core.Agent#setQueueSize(int newSize) */ public int getQueueSize() { return msgQueue.getMaxSize(); } /** Read current agent state. This method can be used to query an agent for its state from the outside. @return the Agent Platform Life Cycle state this agent is currently in. */ public int getState() { int state; synchronized(stateLock) { state = myAPState; } return state; } // State transition methods for Agent Platform Life-Cycle /** Make a state transition from <em>initiated</em> to <em>active</em> within Agent Platform Life Cycle. Agents are started automatically by JADE on agent creation and should not be used by application developers, unless creating some kind of agent factory. This method starts the embedded thread of the agent. @param name The local name of the agent. */ public void doStart(String name) { AgentContainerImpl thisContainer = Starter.getContainer(); try { thisContainer.createAgent(name, this, AgentContainer.START); } catch(java.rmi.RemoteException jrre) { jrre.printStackTrace(); } } /** Make a state transition from <em>active</em> to <em>transit</em> within Agent Platform Life Cycle. This method is intended to support agent mobility and is called either by the Agent Platform or by the agent itself to start a migration process. <em>This method is currently not implemented.</em> */ public void doMove(Location destination) { synchronized(stateLock) { if((myAPState == AP_ACTIVE)||(myAPState == AP_WAITING)) { myBufferedState = myAPState; myAPState = AP_TRANSIT; myDestination = destination; // Real action will be executed in the embedded thread if(!myThread.equals(Thread.currentThread())) myThread.interrupt(); } } } /** Make a state transition from <em>active</em> to <em>copy</em> within Agent Platform Life Cycle. This method is intended to support agent mobility and is called either by the Agent Platform or by the agent itself to start a clonation process. */ public void doClone(Location destination, String newName) { synchronized(stateLock) { if((myAPState == AP_ACTIVE)||(myAPState == AP_WAITING)) { myBufferedState = myAPState; myAPState = AP_COPY; myDestination = destination; myNewName = newName; // Real action will be executed in the embedded thread if(!myThread.equals(Thread.currentThread())) myThread.interrupt(); } } } /** Make a state transition from <em>transit</em> or <code>copy</code> to <em>active</em> within Agent Platform Life Cycle. This method is intended to support agent mobility and is called by the destination Agent Platform when a migration process completes and the mobile agent is about to be restarted on its new location. */ void doExecute() { synchronized(stateLock) { myAPState = myBufferedState; myBufferedState = AP_MIN; activateAllBehaviours(); } } /** Make a state transition from <em>transit</em> to <em>gone</em> state. This state is only used to label the original copy of a mobile agent which migrated somewhere. */ void doGone() { synchronized(stateLock) { myAPState = AP_GONE; } } /** Make a state transition from <em>active</em> or <em>waiting</em> to <em>suspended</em> within Agent Platform Life Cycle; the original agent state is saved and will be restored by a <code>doActivate()</code> call. This method can be called from the Agent Platform or from the agent iself and stops all agent activities. Incoming messages for a suspended agent are buffered by the Agent Platform and are delivered as soon as the agent resumes. Calling <code>doSuspend()</code> on a suspended agent has no effect. @see jade.core.Agent#doActivate() */ public void doSuspend() { synchronized(stateLock) { if((myAPState == AP_ACTIVE)||(myAPState == AP_WAITING)) { myBufferedState = myAPState; myAPState = AP_SUSPENDED; } } if(myAPState == AP_SUSPENDED) { if(myThread.equals(Thread.currentThread())) { waitUntilActivate(); } } } /** Make a state transition from <em>suspended</em> to <em>active</em> or <em>waiting</em> (whichever state the agent was in when <code>doSuspend()</code> was called) within Agent Platform Life Cycle. This method is called from the Agent Platform and resumes agent execution. Calling <code>doActivate()</code> when the agent is not suspended has no effect. @see jade.core.Agent#doSuspend() */ public void doActivate() { synchronized(stateLock) { if(myAPState == AP_SUSPENDED) { myAPState = myBufferedState; } } if(myAPState != AP_SUSPENDED) { switch(myBufferedState) { case AP_ACTIVE: activateAllBehaviours(); synchronized(suspendLock) { myBufferedState = AP_MIN; suspendLock.notifyAll(); } break; case AP_WAITING: doWake(); break; } } } /** Make a state transition from <em>active</em> to <em>waiting</em> within Agent Platform Life Cycle. This method can be called by the Agent Platform or by the agent itself and causes the agent to block, stopping all its activities until some event happens. A waiting agent wakes up as soon as a message arrives or when <code>doWake()</code> is called. Calling <code>doWait()</code> on a suspended or waiting agent has no effect. @see jade.core.Agent#doWake() */ public void doWait() { doWait(0); } /** Make a state transition from <em>active</em> to <em>waiting</em> within Agent Platform Life Cycle. This method adds a timeout to the other <code>doWait()</code> version. @param millis The timeout value, in milliseconds. @see jade.core.Agent#doWait() */ public void doWait(long millis) { synchronized(stateLock) { if(myAPState == AP_ACTIVE) myAPState = AP_WAITING; } if(myAPState == AP_WAITING) { if(myThread.equals(Thread.currentThread())) { waitUntilWake(millis); } } } /** Make a state transition from <em>waiting</em> to <em>active</em> within Agent Platform Life Cycle. This method is called from Agent Platform and resumes agent execution. Calling <code>doWake()</code> when an agent is not waiting has no effect. @see jade.core.Agent#doWait() */ public void doWake() { synchronized(stateLock) { if(myAPState == AP_WAITING) { myAPState = AP_ACTIVE; } } if(myAPState == AP_ACTIVE) { activateAllBehaviours(); synchronized(waitLock) { waitLock.notifyAll(); // Wakes up the embedded thread } } } // This method handles both the case when the agents decides to exit // and the case in which someone else kills him from outside. /** Make a state transition from <em>active</em>, <em>suspended</em> or <em>waiting</em> to <em>deleted</em> state within Agent Platform Life Cycle, thereby destroying the agent. This method can be called either from the Agent Platform or from the agent itself. Calling <code>doDelete()</code> on an already deleted agent has no effect. */ public void doDelete() { synchronized(stateLock) { if(myAPState != AP_DELETED) { myAPState = AP_DELETED; if(!myThread.equals(Thread.currentThread())) myThread.interrupt(); } } } /** Write this agent to an output stream; this method can be used to record a snapshot of the agent state on a file or to send it through a network connection. Of course, the whole agent must be serializable in order to be written successfully. @param s The stream this agent will be sent to. The stream is <em>not</em> closed on exit. @exception IOException Thrown if some I/O error occurs during writing. @see jade.core.Agent#read(InputStream s) */ public void write(OutputStream s) throws IOException { ObjectOutput out = new ObjectOutputStream(s); out.writeUTF(myName); out.writeObject(this); } /** Read a previously saved agent from an input stream and restarts it under its former name. This method can realize some sort of mobility through time, where an agent is saved, then destroyed and then restarted from the saved copy. @param s The stream the agent will be read from. The stream is <em>not</em> closed on exit. @exception IOException Thrown if some I/O error occurs during stream reading. @see jade.core.Agent#write(OutputStream s) */ public static void read(InputStream s) throws IOException { try { ObjectInput in = new ObjectInputStream(s); String name = in.readUTF(); Agent a = (Agent)in.readObject(); a.doStart(name); } catch(ClassNotFoundException cnfe) { cnfe.printStackTrace(); } } /** Read a previously saved agent from an input stream and restarts it under a different name. This method can realize agent cloning through streams, where an agent is saved, then an exact copy of it is restarted as a completely separated agent, with the same state but with different identity and address. @param s The stream the agent will be read from. The stream is <em>not</em> closed on exit. @param agentName The name of the new agent, copy of the saved original one. @exception IOException Thrown if some I/O error occurs during stream reading. @see jade.core.Agent#write(OutputStream s) */ public static void read(InputStream s, String agentName) throws IOException { try { ObjectInput in = new ObjectInputStream(s); String name = in.readUTF(); Agent a = (Agent)in.readObject(); a.doStart(agentName); } catch(ClassNotFoundException cnfe) { cnfe.printStackTrace(); } } /** This method reads a previously saved agent, replacing the current state of this agent with the one previously saved. The stream must contain the saved state of <b>the same agent</b> that it is trying to restore itself; that is, <em>both</em> the Java object <em>and</em> the agent name must be the same. @param s The input stream the agent state will be read from. @exception IOException Thrown if some I/O error occurs during stream reading. <em>Note: This method is currently not implemented</em> */ public void restore(InputStream s) throws IOException { // FIXME: Not implemented } /** This method is the main body of every agent. It can handle automatically <b>AMS</b> registration and deregistration and provides startup and cleanup hooks for application programmers to put their specific code into. @see jade.core.Agent#setup() @see jade.core.Agent#takeDown() */ public final void run() { try { switch(myAPState) { case AP_INITIATED: myAPState = AP_ACTIVE; // No 'break' statement - fall through case AP_ACTIVE: registerWithAMS(null,Agent.AP_ACTIVE,null,null,null); setup(); break; case AP_TRANSIT: doExecute(); afterMove(); break; case AP_COPY: doExecute(); registerWithAMS(null,Agent.AP_ACTIVE,null,null,null); afterClone(); break; } mainLoop(); } catch(InterruptedException ie) { // Do Nothing, since this is a killAgent from outside } catch(InterruptedIOException iioe) { // Do nothing, since this is a killAgent from outside } catch(Exception e) { System.err.println("*** Uncaught Exception for agent " + myName + " ***"); e.printStackTrace(); } catch(AgentDeathError ade) { // Do Nothing, since this is a killAgent from outside } finally { switch(myAPState) { case AP_DELETED: takeDown(); destroy(); break; case AP_GONE: break; default: System.out.println("ERROR: Agent " + myName + " died without being properly terminated !!!"); System.out.println("State was " + myAPState); takeDown(); destroy(); } } } /** This protected method is an empty placeholder for application specific startup code. Agent developers can override it to provide necessary behaviour. When this method is called the agent has been already registered with the Agent Platform <b>AMS</b> and is able to send and receive messages. However, the agent execution model is still sequential and no behaviour scheduling is active yet. This method can be used for ordinary startup tasks such as <b>DF</b> registration, but is essential to add at least a <code>Behaviour</code> object to the agent, in order for it to be able to do anything. @see jade.core.Agent#addBehaviour(Behaviour b) @see jade.core.behaviours.Behaviour */ protected void setup() {} /** This protected method is an empty placeholder for application specific cleanup code. Agent developers can override it to provide necessary behaviour. When this method is called the agent has not deregistered itself with the Agent Platform <b>AMS</b> and is still able to exchange messages with other agents. However, no behaviour scheduling is active anymore and the Agent Platform Life Cycle state is already set to <em>deleted</em>. This method can be used for ordinary cleanup tasks such as <b>DF</b> deregistration, but explicit removal of all agent behaviours is not needed. */ protected void takeDown() {} /** TO DO */ protected void beforeMove() {} /** TO DO */ protected void afterMove() {} /** TO DO */ protected void beforeClone() {} /** TO DO */ protected void afterClone() {} // This method is used by the Agent Container to fire up a new agent for the first time void powerUp(String name, String platformAddress, ThreadGroup myGroup) { // Set this agent's name and address and start its embedded thread if((myAPState == AP_INITIATED)||(myAPState == AP_TRANSIT)||(myAPState == AP_COPY)) { myName = new String(name); myAddress = new String(platformAddress); myThread = new Thread(myGroup, this); myThread.setName(myName); myThread.setPriority(myGroup.getMaxPriority()); myThread.start(); } } private void writeObject(ObjectOutputStream out) throws IOException { out.defaultWriteObject(); } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); // Restore transient fields (apart from myThread, which will be set by doStart()) listeners = new Vector(); stateLock = new Object(); suspendLock = new Object(); waitLock = new Object(); pendingTimers = new AssociationTB(); languages = new HashMap(); ontologies = new HashMap(); } private void mainLoop() throws InterruptedException, InterruptedIOException { while(myAPState != AP_DELETED) { try { // Check for Agent state changes switch(myAPState) { case AP_WAITING: waitUntilWake(0); break; case AP_SUSPENDED: waitUntilActivate(); break; case AP_TRANSIT: notifyMove(); if(myAPState == AP_GONE) { beforeMove(); return; } break; case AP_COPY: beforeClone(); notifyCopy(); doExecute(); break; case AP_ACTIVE: try { // Select the next behaviour to execute currentBehaviour = myScheduler.schedule(); } // Someone interrupted the agent. It could be a kill or a // move/clone request... catch(InterruptedException ie) { switch(myAPState) { case AP_DELETED: throw new AgentDeathError(); case AP_TRANSIT: case AP_COPY: throw new AgentInMotionError(); } } // Remember how many messages arrived int oldMsgCounter = messageCounter; // Just do it! currentBehaviour.action(); // If the current Behaviour is blocked and more messages // arrived, restart the behaviour to give it another chance if((oldMsgCounter != messageCounter) && (!currentBehaviour.isRunnable())) currentBehaviour.restart(); // When it is needed no more, delete it from the behaviours queue if(currentBehaviour.done()) { myScheduler.remove(currentBehaviour); currentBehaviour = null; } else if(!currentBehaviour.isRunnable()) { // Remove blocked behaviours from scheduling queue and put it // in blocked behaviours queue myScheduler.remove(currentBehaviour); blockedBehaviours.addElement(currentBehaviour); currentBehaviour = null; } break; } // Now give CPU control to other agents Thread.yield(); } catch(AgentInMotionError aime) { // Do nothing, since this is a doMove() or doClone() from the outside. } } } private void waitUntilWake(long millis) { synchronized(waitLock) { long timeToWait = millis; while(myAPState == AP_WAITING) { try { long startTime = System.currentTimeMillis(); waitLock.wait(timeToWait); // Blocks on waiting state monitor for a while long elapsedTime = System.currentTimeMillis() - startTime; // If this was a timed wait, update time to wait; if the // total time has passed, wake up. if(millis != 0) { timeToWait -= elapsedTime; if(timeToWait <= 0) myAPState = AP_ACTIVE; } } catch(InterruptedException ie) { switch(myAPState) { case AP_DELETED: throw new AgentDeathError(); case AP_TRANSIT: case AP_COPY: throw new AgentInMotionError(); } } } } } private void waitUntilActivate() { synchronized(suspendLock) { while(myAPState == AP_SUSPENDED) { try { suspendLock.wait(); // Blocks on suspended state monitor } catch(InterruptedException ie) { switch(myAPState) { case AP_DELETED: throw new AgentDeathError(); case AP_TRANSIT: case AP_COPY: // Undo the previous clone or move request myAPState = AP_SUSPENDED; } } } } } private void destroy() { try { int savedState = getState(); myAPState = AP_ACTIVE; deregisterWithAMS(); myAPState = savedState; } catch(FIPAException fe) { fe.printStackTrace(); } notifyDestruction(); } /** This method adds a new behaviour to the agent. This behaviour will be executed concurrently with all the others, using a cooperative round robin scheduling. This method is typically called from an agent <code>setup()</code> to fire off some initial behaviour, but can also be used to spawn new behaviours dynamically. @param b The new behaviour to add to the agent. @see jade.core.Agent#setup() @see jade.core.behaviours.Behaviour */ public void addBehaviour(Behaviour b) { myScheduler.add(b); } /** This method removes a given behaviour from the agent. This method is called automatically when a top level behaviour terminates, but can also be called from a behaviour to terminate itself or some other behaviour. @param b The behaviour to remove. @see jade.core.behaviours.Behaviour */ public void removeBehaviour(Behaviour b) { myScheduler.remove(b); } /** Send an <b>ACL</b> message to another agent. This methods sends a message to the agent specified in <code>:receiver</code> message field (more than one agent can be specified as message receiver). @param msg An ACL message object containing the actual message to send. @see jade.lang.acl.ACLMessage */ public final void send(ACLMessage msg) { if(msg.getSource().length() < 1) msg.setSource(myName); CommEvent event = new CommEvent(this, msg); broadcastEvent(event); } /** Send an <b>ACL</b> message to the agent contained in a given <code>AgentGroup</code>. This method allows simple message multicast to be done. A similar result can be obtained putting many agent names in <code>:receiver</code> message field; the difference is that in that case every receiver agent can read all other receivers' names, whereas this method hides multicasting to receivers. @param msg An ACL message object containing the actual message to send. @param g An agent group object holding all receivers names. @see jade.lang.acl.ACLMessage @see jade.core.AgentGroup */ public final void send(ACLMessage msg, AgentGroup g) { if(msg.getSource().length() < 1) msg.setSource(myName); CommEvent event = new CommEvent(this, msg, g); broadcastEvent(event); } /** Receives an <b>ACL</b> message from the agent message queue. This method is non-blocking and returns the first message in the queue, if any. Therefore, polling and busy waiting is required to wait for the next message sent using this method. @return A new ACL message, or <code>null</code> if no message is present. @see jade.lang.acl.ACLMessage */ public final ACLMessage receive() { synchronized(waitLock) { if(msgQueue.isEmpty()) { return null; } else { currentMessage = msgQueue.removeFirst(); return currentMessage; } } } /** Receives an <b>ACL</b> message matching a given template. This method is non-blocking and returns the first matching message in the queue, if any. Therefore, polling and busy waiting is required to wait for a specific kind of message using this method. @param pattern A message template to match received messages against. @return A new ACL message matching the given template, or <code>null</code> if no such message is present. @see jade.lang.acl.ACLMessage @see jade.lang.acl.MessageTemplate */ public final ACLMessage receive(MessageTemplate pattern) { ACLMessage msg = null; synchronized(waitLock) { Iterator messages = msgQueue.iterator(); while(messages.hasNext()) { ACLMessage cursor = (ACLMessage)messages.next(); if(pattern.match(cursor)) { msg = cursor; msgQueue.remove(cursor); currentMessage = cursor; break; // Exit while loop } } } return msg; } /** Receives an <b>ACL</b> message from the agent message queue. This method is blocking and suspends the whole agent until a message is available in the queue. JADE provides a special behaviour named <code>ReceiverBehaviour</code> to wait for a message within a behaviour without suspending all the others and without wasting CPU time doing busy waiting. @return A new ACL message, blocking the agent until one is available. @see jade.lang.acl.ACLMessage @see jade.core.behaviours.ReceiverBehaviour */ public final ACLMessage blockingReceive() { ACLMessage msg = null; while(msg == null) { msg = blockingReceive(0); } return msg; } /** Receives an <b>ACL</b> message from the agent message queue, waiting at most a specified amount of time. @param millis The maximum amount of time to wait for the message. @return A new ACL message, or <code>null</code> if the specified amount of time passes without any message reception. */ public final ACLMessage blockingReceive(long millis) { synchronized(waitLock) { ACLMessage msg = receive(); if(msg == null) { doWait(millis); msg = receive(); } return msg; } } /** Receives an <b>ACL</b> message matching a given message template. This method is blocking and suspends the whole agent until a message is available in the queue. JADE provides a special behaviour named <code>ReceiverBehaviour</code> to wait for a specific kind of message within a behaviour without suspending all the others and without wasting CPU time doing busy waiting. @param pattern A message template to match received messages against. @return A new ACL message matching the given template, blocking until such a message is available. @see jade.lang.acl.ACLMessage @see jade.lang.acl.MessageTemplate @see jade.core.behaviours.ReceiverBehaviour */ public final ACLMessage blockingReceive(MessageTemplate pattern) { ACLMessage msg = null; while(msg == null) { msg = blockingReceive(pattern, 0); } return msg; } /** Receives an <b>ACL</b> message matching a given message template, waiting at most a specified time. @param pattern A message template to match received messages against. @param millis The amount of time to wait for the message, in milliseconds. @return A new ACL message matching the given template, or <code>null</code> if no suitable message was received within <code>millis</code> milliseconds. @see jade.core.Agent#blockingReceive() */ public final ACLMessage blockingReceive(MessageTemplate pattern, long millis) { ACLMessage msg = null; synchronized(waitLock) { msg = receive(pattern); long timeToWait = millis; while(msg == null) { long startTime = System.currentTimeMillis(); doWait(timeToWait); long elapsedTime = System.currentTimeMillis() - startTime; msg = receive(pattern); if(millis != 0) { timeToWait -= elapsedTime; if(timeToWait <= 0) break; } } } return msg; } /** Puts a received <b>ACL</b> message back into the message queue. This method can be used from an agent behaviour when it realizes it read a message of interest for some other behaviour. The message is put in front of the message queue, so it will be the first returned by a <code>receive()</code> call. @see jade.core.Agent#receive() */ public final void putBack(ACLMessage msg) { synchronized(waitLock) { msgQueue.addFirst(msg); } } private ACLMessage FipaRequestMessage(String dest, String replyString) { ACLMessage request = new ACLMessage(ACLMessage.REQUEST); request.setSource(myName); request.removeAllDests(); request.addDest(dest); request.setLanguage("SL0"); request.setOntology("fipa-agent-management"); request.setProtocol("fipa-request"); request.setReplyWith(replyString); return request; } private String doFipaRequestClient(ACLMessage request, String replyString) throws FIPAException { send(request); ACLMessage reply = blockingReceive(MessageTemplate.MatchReplyTo(replyString)); if(reply.getPerformative() == ACLMessage.AGREE) { reply = blockingReceive(MessageTemplate.MatchReplyTo(replyString)); if(reply.getPerformative() != ACLMessage.INFORM) { String content = reply.getContent(); StringReader text = new StringReader(content); throw FIPAException.fromText(text); } else { String content = reply.getContent(); return content; } } else { String content = reply.getContent(); StringReader text = new StringReader(content); throw FIPAException.fromText(text); } } /** Register this agent with Agent Platform <b>AMS</b>. While this task can be accomplished with regular message passing according to <b>FIPA</b> protocols, this method is meant to ease this common duty. However, since <b>AMS</b> registration and deregistration are automatic in JADE, this method should not be used by application programmers. Some parameters here are optional, and <code>null</code> can safely be passed for them. @param signature An optional signature string, used for security reasons. @param APState The Agent Platform state of the agent; must be a valid state value (typically, <code>Agent.AP_ACTIVE</code> constant is passed). @param delegateAgent An optional delegate agent name. @param forwardAddress An optional forward address. @param ownership An optional ownership string. @exception FIPAException A suitable exception can be thrown when a <code>refuse</code> or <code>failure</code> messages are received from the AMS to indicate some error condition. */ public void registerWithAMS(String signature, int APState, String delegateAgent, String forwardAddress, String ownership) throws FIPAException { String replyString = myName + "-ams-registration-" + (new Date()).getTime(); ACLMessage request = FipaRequestMessage("ams", replyString); // Build an AMS action object for the request AgentManagementOntology.AMSAction a = new AgentManagementOntology.AMSAction(); AgentManagementOntology.AMSAgentDescriptor amsd = new AgentManagementOntology.AMSAgentDescriptor(); amsd.setName(getName()); amsd.setAddress(getAddress()); amsd.setAPState(APState); amsd.setDelegateAgentName(delegateAgent); amsd.setForwardAddress(forwardAddress); amsd.setOwnership(ownership); a.setName(AgentManagementOntology.AMSAction.REGISTERAGENT); a.setArg(amsd); // Convert it to a String and write it in content field of the request StringWriter text = new StringWriter(); a.toText(text); request.setContent(text.toString()); // Send message and collect reply doFipaRequestClient(request, replyString); } /** Authenticate this agent with Agent Platform <b>AMS</b>. While this task can be accomplished with regular message passing according to <b>FIPA</b> protocols, this method is meant to ease this common duty. Some parameters here are optional, and <code>null</code> can safely be passed for them. @param signature An optional signature string, used for security reasons. @param APState The Agent Platform state of the agent; must be a valid state value (typically, <code>Agent.AP_ACTIVE</code> constant is passed). @param delegateAgent An optional delegate agent name. @param forwardAddress An optional forward address. @param ownership An optional ownership string. @exception FIPAException A suitable exception can be thrown when a <code>refuse</code> or <code>failure</code> messages are received from the AMS to indicate some error condition. <em>This method is currently not implemented.</em> */ public void authenticateWithAMS(String signature, int APState, String delegateAgent, String forwardAddress, String ownership) throws FIPAException { // FIXME: Not implemented } /** Deregister this agent with Agent Platform <b>AMS</b>. While this task can be accomplished with regular message passing according to <b>FIPA</b> protocols, this method is meant to ease this common duty. However, since <b>AMS</b> registration and deregistration are automatic in JADE, this method should not be used by application programmers. @exception FIPAException A suitable exception can be thrown when a <code>refuse</code> or <code>failure</code> messages are received from the AMS to indicate some error condition. */ public void deregisterWithAMS() throws FIPAException { String replyString = myName + "-ams-deregistration-" + (new Date()).getTime(); // Get a semi-complete request message ACLMessage request = FipaRequestMessage("ams", replyString); // Build an AMS action object for the request AgentManagementOntology.AMSAction a = new AgentManagementOntology.AMSAction(); AgentManagementOntology.AMSAgentDescriptor amsd = new AgentManagementOntology.AMSAgentDescriptor(); amsd.setName(getName()); a.setName(AgentManagementOntology.AMSAction.DEREGISTERAGENT); a.setArg(amsd); // Convert it to a String and write it in content field of the request StringWriter text = new StringWriter(); a.toText(text); request.setContent(text.toString()); // Send message and collect reply doFipaRequestClient(request, replyString); } /** Modifies the data about this agent kept by Agent Platform <b>AMS</b>. While this task can be accomplished with regular message passing according to <b>FIPA</b> protocols, this method is meant to ease this common duty. Some parameters here are optional, and <code>null</code> can safely be passed for them. When a non null parameter is passed, it replaces the value currently stored inside <b>AMS</b> agent. @param signature An optional signature string, used for security reasons. @param APState The Agent Platform state of the agent; must be a valid state value (typically, <code>Agent.AP_ACTIVE</code> constant is passed). @param delegateAgent An optional delegate agent name. @param forwardAddress An optional forward address. @param ownership An optional ownership string. @exception FIPAException A suitable exception can be thrown when a <code>refuse</code> or <code>failure</code> messages are received from the AMS to indicate some error condition. */ public void modifyAMSRegistration(String signature, int APState, String delegateAgent, String forwardAddress, String ownership) throws FIPAException { String replyString = myName + "-ams-modify-" + (new Date()).getTime(); ACLMessage request = FipaRequestMessage("ams", replyString); // Build an AMS action object for the request AgentManagementOntology.AMSAction a = new AgentManagementOntology.AMSAction(); AgentManagementOntology.AMSAgentDescriptor amsd = new AgentManagementOntology.AMSAgentDescriptor(); amsd.setName(getName()); amsd.setAddress(getAddress()); amsd.setAPState(APState); amsd.setDelegateAgentName(delegateAgent); amsd.setForwardAddress(forwardAddress); amsd.setOwnership(ownership); a.setName(AgentManagementOntology.AMSAction.MODIFYAGENT); a.setArg(amsd); // Convert it to a String and write it in content field of the request StringWriter text = new StringWriter(); a.toText(text); request.setContent(text.toString()); // Send message and collect reply doFipaRequestClient(request, replyString); } /** This method uses Agent Platform <b>ACC</b> agent to forward an ACL message. Calling this method is exactly the same as calling <code>send()</code>, only slower, since the message is first sent to the ACC using a <code>fipa-request</code> standard protocol, and then bounced to actual destination agent. @param msg The ACL message to send. @exception FIPAException A suitable exception can be thrown when a <code>refuse</code> or <code>failure</code> messages are received from the ACC to indicate some error condition. @see jade.core.Agent#send(ACLMessage msg) */ public void forwardWithACC(ACLMessage msg) throws FIPAException { String replyString = myName + "-acc-forward-" + (new Date()).getTime(); ACLMessage request = FipaRequestMessage("acc", replyString); // Build an ACC action object for the request AgentManagementOntology.ACCAction a = new AgentManagementOntology.ACCAction(); a.setName(AgentManagementOntology.ACCAction.FORWARD); a.setArg(msg); // Convert it to a String and write it in content field of the request StringWriter text = new StringWriter(); a.toText(text); request.setContent(text.toString()); // Send message and collect reply doFipaRequestClient(request, replyString); } /** Register this agent with a <b>DF</b> agent. While this task can be accomplished with regular message passing according to <b>FIPA</b> protocols, this method is meant to ease this common duty. @param dfName The GUID of the <b>DF</b> agent to register with. @param dfd A <code>DFAgentDescriptor</code> object containing all data necessary to the registration. @exception FIPAException A suitable exception can be thrown when a <code>refuse</code> or <code>failure</code> messages are received from the DF to indicate some error condition. @see jade.domain.AgentManagementOntology.DFAgentDescriptor */ public void registerWithDF(String dfName, AgentManagementOntology.DFAgentDescriptor dfd) throws FIPAException { String replyString = myName + "-df-register-" + (new Date()).getTime(); ACLMessage request = FipaRequestMessage(dfName, replyString); // Build a DF action object for the request AgentManagementOntology.DFAction a = new AgentManagementOntology.DFAction(); a.setName(AgentManagementOntology.DFAction.REGISTER); a.setActor(dfName); a.setArg(dfd); // Convert it to a String and write it in content field of the request StringWriter text = new StringWriter(); a.toText(text); request.setContent(text.toString()); // Send message and collect reply doFipaRequestClient(request, replyString); } /** Deregister this agent from a <b>DF</b> agent. While this task can be accomplished with regular message passing according to <b>FIPA</b> protocols, this method is meant to ease this common duty. @param dfName The GUID of the <b>DF</b> agent to deregister from. @param dfd A <code>DFAgentDescriptor</code> object containing all data necessary to the deregistration. @exception FIPAException A suitable exception can be thrown when a <code>refuse</code> or <code>failure</code> messages are received from the DF to indicate some error condition. @see jade.domain.AgentManagementOntology.DFAgentDescriptor */ public void deregisterWithDF(String dfName, AgentManagementOntology.DFAgentDescriptor dfd) throws FIPAException { String replyString = myName + "-df-deregister-" + (new Date()).getTime(); ACLMessage request = FipaRequestMessage(dfName, replyString); // Build a DF action object for the request AgentManagementOntology.DFAction a = new AgentManagementOntology.DFAction(); a.setName(AgentManagementOntology.DFAction.DEREGISTER); a.setActor(dfName); a.setArg(dfd); // Convert it to a String and write it in content field of the request StringWriter text = new StringWriter(); a.toText(text); request.setContent(text.toString()); // Send message and collect reply doFipaRequestClient(request, replyString); } /** Modifies data about this agent contained within a <b>DF</b> agent. While this task can be accomplished with regular message passing according to <b>FIPA</b> protocols, this method is meant to ease this common duty. @param dfName The GUID of the <b>DF</b> agent holding the data to be changed. @param dfd A <code>DFAgentDescriptor</code> object containing all new data values; every non null slot value replaces the corresponding value held inside the <b>DF</b> agent. @exception FIPAException A suitable exception can be thrown when a <code>refuse</code> or <code>failure</code> messages are received from the DF to indicate some error condition. @see jade.domain.AgentManagementOntology.DFAgentDescriptor */ public void modifyDFData(String dfName, AgentManagementOntology.DFAgentDescriptor dfd) throws FIPAException { String replyString = myName + "-df-modify-" + (new Date()).getTime(); ACLMessage request = FipaRequestMessage(dfName, replyString); // Build a DF action object for the request AgentManagementOntology.DFAction a = new AgentManagementOntology.DFAction(); a.setName(AgentManagementOntology.DFAction.MODIFY); a.setActor(dfName); a.setArg(dfd); // Convert it to a String and write it in content field of the request StringWriter text = new StringWriter(); a.toText(text); request.setContent(text.toString()); // Send message and collect reply doFipaRequestClient(request, replyString); } /** Searches for data contained within a <b>DF</b> agent. While this task can be accomplished with regular message passing according to <b>FIPA</b> protocols, this method is meant to ease this common duty. Nevertheless, a complete, powerful search interface is provided; search constraints can be given and recursive searches are possible. The only shortcoming is that this method blocks the whole agent until the search terminates. A special <code>SearchDFBehaviour</code> can be used to perform <b>DF</b> searches without blocking. @param dfName The GUID of the <b>DF</b> agent to start search from. @param dfd A <code>DFAgentDescriptor</code> object containing data to search for; this parameter is used as a template to match data against. @param constraints A <code>Vector</code> that must be filled with all <code>Constraint</code> objects to apply to the current search. This can be <code>null</code> if no search constraints are required. @return A <code>DFSearchResult</code> object containing all found <code>DFAgentDescriptor</code> objects matching the given descriptor, subject to given search constraints for search depth and result size. @exception FIPAException A suitable exception can be thrown when a <code>refuse</code> or <code>failure</code> messages are received from the DF to indicate some error condition. @see jade.domain.AgentManagementOntology.DFAgentDescriptor @see java.util.Vector @see jade.domain.AgentManagementOntology.Constraint @see jade.domain.AgentManagementOntology.DFSearchResult */ public AgentManagementOntology.DFSearchResult searchDF(String dfName, AgentManagementOntology.DFAgentDescriptor dfd, Vector constraints) throws FIPAException { String replyString = myName + "-df-search-" + (new Date()).getTime(); ACLMessage request = FipaRequestMessage(dfName, replyString); // Build a DF action object for the request AgentManagementOntology.DFSearchAction a = new AgentManagementOntology.DFSearchAction(); a.setName(AgentManagementOntology.DFAction.SEARCH); a.setActor(dfName); a.setArg(dfd); if(constraints == null) { AgentManagementOntology.Constraint c = new AgentManagementOntology.Constraint(); c.setName(AgentManagementOntology.Constraint.DFDEPTH); c.setFn(AgentManagementOntology.Constraint.EXACTLY); c.setArg(1); a.addConstraint(c); } else { // Put constraints into action Iterator i = constraints.iterator(); while(i.hasNext()) { AgentManagementOntology.Constraint c = (AgentManagementOntology.Constraint)i.next(); a.addConstraint(c); } } // Convert it to a String and write it in content field of the request StringWriter textOut = new StringWriter(); a.toText(textOut); request.setContent(textOut.toString()); // Send message and collect reply String content = doFipaRequestClient(request, replyString); // Extract agent descriptors from reply message AgentManagementOntology.DFSearchResult found = null; StringReader textIn = new StringReader(content); try { found = AgentManagementOntology.DFSearchResult.fromText(textIn); } catch(jade.domain.ParseException jdpe) { jdpe.printStackTrace(); } catch(jade.domain.TokenMgrError jdtme) { jdtme.printStackTrace(); } return found; } // Event handling methods // Broadcast communication event to registered listeners private void broadcastEvent(CommEvent event) { Iterator i = listeners.iterator(); while(i.hasNext()) { CommListener l = (CommListener)i.next(); l.CommHandle(event); } } // Register a new listener public final void addCommListener(CommListener l) { listeners.add(l); } // Remove a registered listener public final void removeCommListener(CommListener l) { listeners.remove(l); } // Notify listeners of the destruction of the current agent private void notifyDestruction() { Iterator i = listeners.iterator(); while(i.hasNext()) { CommListener l = (CommListener)i.next(); l.endSource(myName); } } // Notify listeners of the need to move the current agent private void notifyMove() { Iterator i = listeners.iterator(); while(i.hasNext()) { CommListener l = (CommListener)i.next(); l.moveSource(myName, myDestination); } } // Notify listeners of the need to copy the current agent private void notifyCopy() { Iterator i = listeners.iterator(); while(i.hasNext()) { CommListener l = (CommListener)i.next(); l.copySource(myName, myDestination, myNewName); } } private void activateBehaviour(Behaviour b) { Behaviour root = b.root(); blockedBehaviours.remove(root); b.restart(); myScheduler.add(root); } private void activateAllBehaviours() { // Put all blocked behaviours back in ready queue, // atomically with respect to the Scheduler object synchronized(myScheduler) { while(!blockedBehaviours.isEmpty()) { Behaviour b = (Behaviour)blockedBehaviours.lastElement(); blockedBehaviours.removeElementAt(blockedBehaviours.size() - 1); b.restart(); myScheduler.add(b); } } } /** Put a received message into the agent message queue. The message is put at the back end of the queue. This method is called by JADE runtime system when a message arrives, but can also be used by an agent, and is just the same as sending a message to oneself (though slightly faster). @param msg The ACL message to put in the queue. @see jade.core.Agent#send(ACLMessage msg) */ public final void postMessage (ACLMessage msg) { synchronized(waitLock) { /* try { java.io.FileWriter f = new java.io.FileWriter("logs/" + getLocalName(), true); f.write("waitLock taken in postMessage() [thread " + Thread.currentThread().getName() + "]\n"); msg.toText(f); f.close(); } catch(java.io.IOException ioe) { System.out.println(ioe.getMessage()); } */ if(msg != null) msgQueue.addLast(msg); doWake(); messageCounter++; } /* try { java.io.FileWriter f = new java.io.FileWriter("logs/" + getLocalName(), true); f.write("waitLock dropped in postMessage() [thread " + Thread.currentThread().getName() + "]\n"); f.close(); } catch(java.io.IOException ioe) { System.out.println(ioe.getMessage()); } */ } Iterator messages() { return msgQueue.iterator(); } }
package jade.core; import java.io.IOException; import java.io.InterruptedIOException; import jade.util.leap.Serializable; import jade.util.leap.Iterator; import java.util.Hashtable; import java.util.Enumeration; import jade.core.behaviours.Behaviour; import jade.lang.acl.*; import jade.security.JADESecurityException; //#MIDP_EXCLUDE_BEGIN import java.io.InputStream; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.OutputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import jade.core.mobility.AgentMobilityHelper; import jade.core.mobility.Movable; import jade.util.leap.List; import jade.util.leap.ArrayList; import jade.util.leap.Map; import jade.util.leap.HashMap; //#MIDP_EXCLUDE_END /*#MIDP_INCLUDE_BEGIN import javax.microedition.midlet.*; #MIDP_INCLUDE_END*/ /** The <code>Agent</code> class is the common superclass for user defined software agents. It provides methods to perform basic agent tasks, such as: <ul> <li> <b> Message passing using <code>ACLMessage</code> objects, both unicast and multicast with optional pattern matching. </b></li> <li> <b> Complete Agent Platform life cycle support, including starting, suspending and killing an agent. </b></li> <li> <b> Scheduling and execution of multiple concurrent activities. </b></li> </ul> Application programmers must write their own agents as <code>Agent</code> subclasses, adding specific behaviours as needed and exploiting <code>Agent</code> class capabilities. @author Giovanni Rimassa - Universita' di Parma @author Giovanni Caire - TILAB @version $Date$ $Revision$ */ public class Agent implements Runnable, Serializable //#APIDOC_EXCLUDE_BEGIN , TimerListener //#APIDOC_EXCLUDE_END { private static final long serialVersionUID = 3487495895819000L; /** Inner class Interrupted. This class is used to handle change state requests that occur in particular situations such as when the agent thread is blocked in the doWait() method. */ public static class Interrupted extends Error { public Interrupted() { super(); } } // END of inner class Interrupted /** Inner class AssociationTB. This class manages bidirectional associations between Timer and Behaviour objects, using hash tables. This class is fully synchronized because it is accessed both by agent internal thread and high priority Timer Dispatcher thread. */ private class AssociationTB { private Hashtable BtoT = new Hashtable(); private Hashtable TtoB = new Hashtable(); public void clear() { Enumeration e = timers(); while (e.hasMoreElements()) { Timer t = (Timer) e.nextElement(); theDispatcher.remove(t); } BtoT.clear(); TtoB.clear(); //#J2ME_EXCLUDE_BEGIN // For persistence service persistentPendingTimers.clear(); //#J2ME_EXCLUDE_END } public synchronized void addPair(Behaviour b, Timer t) { TBPair pair = new TBPair(Agent.this, t, b); addPair(pair); } public synchronized void addPair(TBPair pair) { if(pair.getOwner() == null) { pair.setOwner(Agent.this); } pair.setTimer(theDispatcher.add(pair.getTimer())); TBPair old = (TBPair)BtoT.put(pair.getBehaviour(), pair); if(old != null) { theDispatcher.remove(old.getTimer()); //#J2ME_EXCLUDE_BEGIN persistentPendingTimers.remove(old); //#J2ME_EXCLUDE_END } old = (TBPair)TtoB.put(pair.getTimer(), pair); if(old != null) { theDispatcher.remove(old.getTimer()); //#J2ME_EXCLUDE_BEGIN persistentPendingTimers.remove(old); //#J2ME_EXCLUDE_END } //#J2ME_EXCLUDE_BEGIN // For persistence service persistentPendingTimers.add(pair); //#J2ME_EXCLUDE_END } public synchronized void removeMapping(Behaviour b) { TBPair pair = (TBPair)BtoT.remove(b); if(pair != null) { TtoB.remove(pair.getTimer()); //#J2ME_EXCLUDE_BEGIN // For persistence service persistentPendingTimers.remove(pair); //#J2ME_EXCLUDE_END theDispatcher.remove(pair.getTimer()); } } public synchronized void removeMapping(Timer t) { TBPair pair = (TBPair)TtoB.remove(t); if(pair != null) { BtoT.remove(pair.getBehaviour()); //#J2ME_EXCLUDE_BEGIN // For persistence service persistentPendingTimers.remove(pair); //#J2ME_EXCLUDE_END theDispatcher.remove(pair.getTimer()); } } public synchronized Timer getPeer(Behaviour b) { TBPair pair = (TBPair)BtoT.get(b); if(pair != null) { return pair.getTimer(); } else { return null; } } public synchronized Behaviour getPeer(Timer t) { TBPair pair = (TBPair)TtoB.get(t); if(pair != null) { return pair.getBehaviour(); } else { return null; } } public synchronized Enumeration timers() { return TtoB.keys(); } } // End of inner class AssociationTB /** Inner class TBPair */ private static class TBPair { public TBPair() { expirationTime = -1; } public TBPair(Agent a, Timer t, Behaviour b) { owner = a; myTimer = t; expirationTime = t.expirationTime(); myBehaviour = b; } public void setTimer(Timer t) { myTimer = t; } public Timer getTimer() { return myTimer; } public Behaviour getBehaviour() { return myBehaviour; } public void setBehaviour(Behaviour b) { myBehaviour = b; } public Agent getOwner() { return owner; } public void setOwner(Agent o) { owner = o; createTimerIfNeeded(); } public long getExpirationTime() { return expirationTime; } public void setExpirationTime(long when) { expirationTime = when; createTimerIfNeeded(); } // If both the owner and the expiration time have been set, // but the Timer object is still null, create one private void createTimerIfNeeded() { if(myTimer == null) { if((owner != null) && (expirationTime > 0)) { myTimer = new Timer(expirationTime, owner); } } } private Timer myTimer; private long expirationTime; private Behaviour myBehaviour; private Agent owner; } // End of inner class TBPair //#MIDP_EXCLUDE_BEGIN /** Inner class CondVar A simple class for a boolean condition variable */ private static class CondVar { private boolean value = false; public synchronized void waitOn() throws InterruptedException { while(!value) { wait(); } } public synchronized void set() { value = true; notifyAll(); } } // End of inner class CondVar //#MIDP_EXCLUDE_END //#APIDOC_EXCLUDE_BEGIN /** Schedules a restart for a behaviour, after a certain amount of time has passed. @param b The behaviour to restart later. @param millis The amount of time to wait before restarting <code>b</code>. @see jade.core.behaviours.Behaviour#block(long millis) */ public void restartLater(Behaviour b, long millis) { if (millis <= 0) return; Timer t = new Timer(System.currentTimeMillis() + millis, this); // The following block of code must be synchronized with the operations // carried out by the TimerDispatcher. In fact it could be the case that // 1) A behaviour blocks for a very short time --> A Timer is added // to the TimerDispatcher // 2) The Timer immediately expires and the TimerDispatcher try to // restart the behaviour before the pair (b, t) is added to the // pendingTimers of this agent. synchronized (theDispatcher) { pendingTimers.addPair(b, t); } } /** Restarts the behaviour associated with t. This method runs within the time-critical Timer Dispatcher thread and is not intended to be called by users. It is defined public only because is part of the <code>TimerListener</code> interface. */ public void doTimeOut(Timer t) { Behaviour b = pendingTimers.getPeer(t); if(b != null) { b.restart(); } //#MIDP_EXCLUDE_BEGIN else { System.out.println("Warning: No mapping found for expired timer "+t.expirationTime()); } //#MIDP_EXCLUDE_END } /** Notifies this agent that one of its behaviours has been restarted for some reason. This method clears any timer associated with behaviour object <code>b</code>, and it is unneeded by application level code. To explicitly schedule behaviours, use <code>block()</code> and <code>restart()</code> methods. @param b The behaviour object which was restarted. @see jade.core.behaviours.Behaviour#restart() */ public void notifyRestarted(Behaviour b) { Timer t = pendingTimers.getPeer(b); if(t != null) { pendingTimers.removeMapping(b); } // Did this restart() cause the root behaviour to become runnable ? // If so, put the root behaviour back into the ready queue. Behaviour root = b.root(); if(root.isRunnable()) { myScheduler.restart(root); } } /** Out of band value for Agent Platform Life Cycle states. */ public static final int AP_MIN = 0; // Hand-made type checking /** Represents the <em>initiated</em> agent state. */ public static final int AP_INITIATED = 1; /** Represents the <em>active</em> agent state. */ public static final int AP_ACTIVE = 2; /** Represents the <em>idle</em> agent state. */ public static final int AP_IDLE = 3; /** Represents the <em>suspended</em> agent state. */ public static final int AP_SUSPENDED = 4; /** Represents the <em>waiting</em> agent state. */ public static final int AP_WAITING = 5; /** Represents the <em>deleted</em> agent state. */ public static final int AP_DELETED = 6; /** Out of band value for Agent Platform Life Cycle states. */ public static final int AP_MAX = 13; // Hand-made type checking //#MIDP_EXCLUDE_BEGIN /** These constants represent the various Domain Life Cycle states */ /** Out of band value for Domain Life Cycle states. */ public static final int D_MIN = 9; // Hand-made type checking /** Represents the <em>active</em> agent state. */ public static final int D_ACTIVE = 10; /** Represents the <em>suspended</em> agent state. */ public static final int D_SUSPENDED = 20; /** Represents the <em>retired</em> agent state. */ public static final int D_RETIRED = 30; /** Represents the <em>unknown</em> agent state. */ public static final int D_UNKNOWN = 40; /** Out of band value for Domain Life Cycle states. */ public static final int D_MAX = 41; // Hand-made type checking //#MIDP_EXCLUDE_END //#APIDOC_EXCLUDE_END /** Get the Agent ID for the platform AMS. @return An <code>AID</code> object, that can be used to contact the AMS of this platform. */ public final AID getAMS() { return myToolkit.getAMS(); } /** Get the Agent ID for the platform default DF. @return An <code>AID</code> object, that can be used to contact the default DF of this platform. */ public final AID getDefaultDF() { return myToolkit.getDefaultDF(); } //#MIDP_EXCLUDE_BEGIN private int msgQueueMaxSize = 0; private transient MessageQueue msgQueue; private transient List o2aQueue; private int o2aQueueSize = 0; private transient Map o2aLocks; private transient AgentToolkit myToolkit = DummyToolkit.instance(); //#MIDP_EXCLUDE_END /*#MIDP_INCLUDE_BEGIN private transient AgentToolkit myToolkit; #MIDP_INCLUDE_END*/ private String myName = null; private AID myAID = null; private String myHap = null; private transient Object stateLock = new Object(); // Used to make state transitions atomic private transient Object suspendLock = new Object(); // Used for agent suspension private transient Thread myThread; private transient TimerDispatcher theDispatcher; private Scheduler myScheduler; private transient AssociationTB pendingTimers; // Free running counter that increments by one for each message // received. private int messageCounter = 0 ; private LifeCycle myLifeCycle; private LifeCycle myBufferedLifeCycle; private LifeCycle myActiveLifeCycle; private transient LifeCycle myDeletedLifeCycle; //#MIDP_EXCLUDE_BEGIN private transient LifeCycle mySuspendedLifeCycle; //#MIDP_EXCLUDE_END /** This flag is used to distinguish the normal AP_ACTIVE state from the particular case in which the agent state is set to AP_ACTIVE during agent termination to allow it to deregister with the AMS. In this case in fact a call to <code>doDelete()</code>, <code>doMove()</code>, <code>doClone()</code> and <code>doSuspend()</code> should have no effect. */ private boolean terminating = false; //#MIDP_EXCLUDE_BEGIN // For persistence service private void setTerminating(boolean b) { terminating = b; } // For persistence service private boolean getTerminating() { return terminating; } /** When set to false (default) all behaviour-related events (such as ADDED_BEHAVIOUR or CHANGED_BEHAVIOUR_STATE) are not generated in order to improve performances. These events in facts are very frequent. */ private boolean generateBehaviourEvents = false; //#MIDP_EXCLUDE_END /*#MIDP_INCLUDE_BEGIN public static MIDlet midlet; // Flag for agent interruption (necessary as Thread.interrupt() // is not available in MIDP) private boolean isInterrupted = false; #MIDP_INCLUDE_END*/ /** Default constructor. */ public Agent() { //#MIDP_EXCLUDE_BEGIN msgQueue = new MessageQueue(msgQueueMaxSize); //#MIDP_EXCLUDE_END /*#MIDP_INCLUDE_BEGIN msgQueue = new MessageQueue(); #MIDP_INCLUDE_END*/ o2aLocks = new HashMap(); pendingTimers = new AssociationTB(); myActiveLifeCycle = new ActiveLifeCycle(); myLifeCycle = myActiveLifeCycle; myScheduler = new Scheduler(this); theDispatcher = TimerDispatcher.getTimerDispatcher(); } //#MIDP_EXCLUDE_BEGIN /** Constructor to be used by special "agents" that will never powerUp. */ Agent(AID id) { setAID(id); } // For persistence service private Long persistentID; // For persistence service private Long getPersistentID() { return persistentID; } // For persistence service private void setPersistentID(Long l) { persistentID = l; } /** Declared transient because the container changes in case * of agent migration. **/ private transient jade.wrapper.AgentContainer myContainer = null; /** * Return a controller for the container this agent lives in. * <br> * <b>NOT available in MIDP</b> * <br> * @return jade.wrapper.AgentContainer a controller for the container this agent lives in. */ public final jade.wrapper.AgentContainer getContainerController() { if (myContainer == null) { // first time called try { jade.security.JADEPrincipal principal = null; jade.security.Credentials credentials = null; try { jade.security.CredentialsHelper ch = (jade.security.CredentialsHelper) getHelper("jade.core.security.Security"); principal = ch.getPrincipal(); credentials = ch.getCredentials(); } catch (ServiceException se) { // Security plug-in not present. Ignore it } myContainer = myToolkit.getContainerController(principal, credentials); } catch (Exception e) { throw new IllegalStateException("A ContainerController cannot be got for this agent. Probably the method has been called at an appropriate time before the complete initialization of the agent."); } } return myContainer; } //#MIDP_EXCLUDE_END private transient Object[] arguments = null; // array of arguments //#APIDOC_EXCLUDE_BEGIN /** * Called by AgentContainerImpl in order to pass arguments to a * just created Agent. * <p>Usually, programmers do not need to call this method in their code. * @see #getArguments() how to get the arguments passed to an agent **/ public final void setArguments(Object args[]) { // I have declared the method final otherwise getArguments would not work! arguments=args; } //#APIDOC_EXCLUDE_END /** * Get the array of arguments passed to this agent. * <p> Take care that the arguments are transient and they do not * migrate with the agent neither are cloned with the agent! * @return the array of arguments passed to this agent. * @see <a href=../../../tutorials/ArgsAndPropsPassing.htm>How to use arguments or properties to configure your agent.</a> **/ protected Object[] getArguments() { return arguments; } /** Method to query the agent local name. @return A <code>String</code> containing the local agent name (e.g. <em>peter</em>). */ public final String getLocalName() { return myName; } /** Method to query the agent complete name (<em><b>GUID</b></em>). @return A <code>String</code> containing the complete agent name (e.g. <em>peter@fipa.org:50</em>). */ public final String getName() { if (myHap != null) { return myName + '@' + myHap; } else { return myName; } } /** * Method to query the Home Agent Platform. This is the name of * the platform where the agent has been created, therefore it will * never change during the entire lifetime of the agent. * In JADE the name of an agent by default is composed by the * concatenation (using '@') of the agent local name and the Home * Agent Platform name * * @return A <code>String</code> containing the name of the home agent platform * (e.g. <em>myComputerName:1099/JADE</em>). */ public final String getHap() { return myHap; } /** Method to query the private Agent ID. Note that this Agent ID is <b>different</b> from the one that is registered with the platform AMS. @return An <code>Agent ID</code> object, containing the complete agent GUID, addresses and resolvers. */ public final AID getAID() { return myAID; } void setAID(AID id) { myName = id.getLocalName(); myHap = id.getHap(); myAID = id; } /** This method adds a new platform address to the AID of this Agent. It is called by the container when a new MTP is activated in the platform (in the local container - installMTP() - or in a remote container - updateRoutingTable()) to keep the Agent AID updated. */ synchronized void addPlatformAddress(String address) { // Mutual exclusion with Agent.powerUp() if (myAID != null) { // Cloning the AID is necessary as the agent may be using its AID. // If this is the case a ConcurrentModificationException would be thrown myAID = (AID)myAID.clone(); myAID.addAddresses(address); } } /** This method removes an old platform address from the AID of this Agent. It is called by the container when a new MTP is deactivated in the platform (in the local container - uninstallMTP() - or in a remote container - updateRoutingTable()) to keep the Agent AID updated. */ synchronized void removePlatformAddress(String address) { // Mutual exclusion with Agent.powerUp() if (myAID != null) { // Cloning the AID is necessary as the agent may be using its AID. // If this is the case a ConcurrentModificationException would be thrown myAID = (AID)myAID.clone(); myAID.removeAddresses(address); } } /** Method to retrieve the location this agent is currently at. @return A <code>Location</code> object, describing the location where this agent is currently running. */ public Location here() { return myToolkit.here(); } /** * This is used by the agent container to wait for agent termination. * We have alreader called doDelete on the thread which would have * issued an interrupt on it. However, it still may decide not to exit. * So we will wait no longer than 5 seconds for it to exit and we * do not care of this zombie agent. * FIXME: we must further isolate container and agents, for instance * by using custom class loader and dynamic proxies and JDK 1.3. * FIXME: the timeout value should be got by Profile */ void join() { //#MIDP_EXCLUDE_BEGIN try { if(myThread == null) { return; } myThread.join(5000); if (myThread.isAlive()) { System.out.println("*** Warning: Agent " + myName + " did not terminate when requested to do so."); if(!myThread.equals(Thread.currentThread())) { myThread.interrupt(); System.out.println("*** Second interrupt issued."); } } } catch(InterruptedException ie) { ie.printStackTrace(); } //#MIDP_EXCLUDE_END /*#MIDP_INCLUDE_BEGIN if (myThread != null && myThread.isAlive()) { try { myThread.join(); } catch (InterruptedException ie) { ie.printStackTrace(); } } #MIDP_INCLUDE_END*/ } //#CUSTOM_EXCLUDE_BEGIN public void setQueueSize(int newSize) throws IllegalArgumentException { msgQueue.setMaxSize(newSize); //#MIDP_EXCLUDE_BEGIN msgQueueMaxSize = newSize; //#MIDP_EXCLUDE_END } /** * This method retrieves the current lenght of the message queue * of this agent. * @return The number of messages that are currently stored into the * message queue. **/ public int getCurQueueSize() { return msgQueue.size(); } /** Reads message queue size. A zero value means that the message queue is unbounded (its size is limited only by amount of available memory). @return The actual size of the message queue (i.e. the max number of messages that can be stored into the queue) @see jade.core.Agent#setQueueSize(int newSize) @see jade.core.Agent#getCurQueueSize() */ public int getQueueSize() { return msgQueue.getMaxSize(); } //#CUSTOM_EXCLUDE_END // Agent state management public void changeStateTo(LifeCycle newLifeCycle) { boolean changed = false; newLifeCycle.setAgent(this); synchronized (stateLock) { if (!myLifeCycle.equals(newLifeCycle)) { // The new state is actually different from the current one if (myLifeCycle.transitionTo(newLifeCycle)) { myBufferedLifeCycle = myLifeCycle; myLifeCycle = newLifeCycle; changed = true; //#MIDP_EXCLUDE_BEGIN notifyChangedAgentState(myBufferedLifeCycle.getState(), myLifeCycle.getState()); //#MIDP_EXCLUDE_END } } } if (changed) { myLifeCycle.transitionFrom(myBufferedLifeCycle); if (!Thread.currentThread().equals(myThread)) { // If the state-change is forced from the outside, interrupt // the agent thread to allow the state change to take place interruptThread(); } } } public void restoreBufferedState() { System.out.println("Restoring buffered state "+myBufferedLifeCycle.getState()); changeStateTo(myBufferedLifeCycle); } /** The ActiveLifeCycle handles different internal states (INITIATED, ACTIVE, WAITING, IDLE). This method switches between them. */ private void setActiveState(int newState) { synchronized (stateLock) { if (myLifeCycle == myActiveLifeCycle) { int oldState = myLifeCycle.getState(); if (newState != oldState) { ((ActiveLifeCycle) myLifeCycle).setState(newState); //#MIDP_EXCLUDE_BEGIN notifyChangedAgentState(oldState, newState); //#MIDP_EXCLUDE_END } } else { // A change state request arrived in the meanwhile. // Let it take place. throw new Interrupted(); } } } //#APIDOC_EXCLUDE_BEGIN /** Read current agent state. This method can be used to query an agent for its state from the outside. @return the Agent Platform Life Cycle state this agent is currently in. */ public int getState() { return myLifeCycle.getState(); } //#APIDOC_EXCLUDE_END //#MIDP_EXCLUDE_BEGIN public AgentState getAgentState() { return AgentState.getInstance(getState()); } /** This is only called by the NotificationService to provide the Introspector agent with a snapshot of the behaviours currently loaded in the agent */ Scheduler getScheduler() { return myScheduler; } /** This is only called by AgentContainerImpl */ MessageQueue getMessageQueue() { return msgQueue; } // For persistence service private void setMessageQueue(MessageQueue mq) { msgQueue = mq; } // Mobility related code private transient AgentMobilityHelper mobHelper; private void initMobHelper() throws ServiceException { if (mobHelper == null) { mobHelper = (AgentMobilityHelper) getHelper(AgentMobilityHelper.NAME); mobHelper.registerMovable(new Movable() { public void beforeMove() { Agent.this.beforeMove(); } public void afterMove() { Agent.this.afterMove(); } public void beforeClone() { Agent.this.beforeClone(); } public void afterClone() { Agent.this.afterClone(); } } ); } } /** Make this agent move to a remote location. This method is intended to support agent mobility and is called either by the Agent Platform or by the agent itself to start a migration process. It should be noted that this method just changes the agent state to <code>AP_TRANSIT</code>. The actual migration takes place asynchronously. <br> <b>NOT available in MIDP</b> <br> @param destination The <code>Location</code> to migrate to. */ public void doMove(Location destination) { // Do nothing if the mobility service is not installed try { initMobHelper(); mobHelper.move(destination); } catch(ServiceException se) { // FIXME: Log a proper warning return; } } /** Make this agent be cloned on another location. This method is intended to support agent mobility and is called either by the Agent Platform or by the agent itself to start a clonation process. It should be noted that this method just changes the agent state to <code>AP_COPY</code>. The actual clonation takes place asynchronously. <br> <b>NOT available in MIDP</b> <br> @param destination The <code>Location</code> where the copy agent will start. @param newName The name that will be given to the copy agent. */ public void doClone(Location destination, String newName) { // Do nothing if the mobility service is not installed try { initMobHelper(); mobHelper.clone(destination, newName); } catch(ServiceException se) { // FIXME: Log a proper warning return; } } //#MIDP_EXCLUDE_END /** Make a state transition from <em>active</em> or <em>waiting</em> to <em>suspended</em> within Agent Platform Life Cycle; the original agent state is saved and will be restored by a <code>doActivate()</code> call. This method can be called from the Agent Platform or from the agent iself and stops all agent activities. Incoming messages for a suspended agent are buffered by the Agent Platform and are delivered as soon as the agent resumes. Calling <code>doSuspend()</code> on a suspended agent has no effect. <br> <b>NOT available in MIDP</b> <br> @see jade.core.Agent#doActivate() */ public void doSuspend() { //#MIDP_EXCLUDE_BEGIN if (mySuspendedLifeCycle == null) { mySuspendedLifeCycle = new SuspendedLifeCycle(); } changeStateTo(mySuspendedLifeCycle); //#MIDP_EXCLUDE_END } /** Make a state transition from <em>suspended</em> to <em>active</em> or <em>waiting</em> (whichever state the agent was in when <code>doSuspend()</code> was called) within Agent Platform Life Cycle. This method is called from the Agent Platform and resumes agent execution. Calling <code>doActivate()</code> when the agent is not suspended has no effect. <br> <b>NOT available in MIDP</b> <br> @see jade.core.Agent#doSuspend() */ public void doActivate() { //#MIDP_EXCLUDE_BEGIN //doExecute(); restoreBufferedState(); //#MIDP_EXCLUDE_END } /** Make a state transition from <em>active</em> to <em>waiting</em> within Agent Platform Life Cycle. This method has only effect when called by the agent thread and causes the agent to block, stopping all its activities until a message arrives or the <code>doWake()</code> method is called. @see jade.core.Agent#doWake() */ public void doWait() { doWait(0); } /** Make a state transition from <em>active</em> to <em>waiting</em> within Agent Platform Life Cycle. This method adds a timeout to the other <code>doWait()</code> version. @param millis The timeout value, in milliseconds. @see jade.core.Agent#doWait() */ public void doWait(long millis) { if (Thread.currentThread().equals(myThread)) { setActiveState(AP_WAITING); synchronized(msgQueue) { try { // Blocks on msgQueue monitor for a while waitOn(msgQueue, millis); } catch (InterruptedException ie) { if (myLifeCycle != myActiveLifeCycle && !terminating) { // Change state request from the outside throw new Interrupted(); } else { // Spurious wake up. Just print a warning System.out.println("Agent "+getName()+" interrupted while waiting"); } } setActiveState(AP_ACTIVE); } } } /** Make a state transition from <em>waiting</em> to <em>active</em> within Agent Platform Life Cycle. This method is called from Agent Platform and resumes agent execution. Calling <code>doWake()</code> when an agent is not waiting has no effect. @see jade.core.Agent#doWait() */ public void doWake() { synchronized(stateLock) { int previous = myLifeCycle.getState(); if((previous == AP_WAITING) || (previous == AP_IDLE)) { setActiveState(AP_ACTIVE); } } if(myLifeCycle.getState() == AP_ACTIVE) { activateAllBehaviours(); synchronized(msgQueue) { msgQueue.notifyAll(); // Wakes up the embedded thread } } } /** Make a state transition from <em>active</em>, <em>suspended</em> or <em>waiting</em> to <em>deleted</em> state within Agent Platform Life Cycle, thereby destroying the agent. This method can be called either from the Agent Platform or from the agent itself. Calling <code>doDelete()</code> on an already deleted agent has no effect. */ public void doDelete() { if (myDeletedLifeCycle == null) { myDeletedLifeCycle = new DeletedLifeCycle(); } changeStateTo(myDeletedLifeCycle); } // This is called only by the scheduler void idle() throws InterruptedException { setActiveState(AP_IDLE); // No need for synchronized block since this is only called by the // scheduler in the synchronized schedule() method waitOn(myScheduler, 0); setActiveState(AP_ACTIVE); } //#MIDP_EXCLUDE_BEGIN /** Write this agent to an output stream; this method can be used to record a snapshot of the agent state on a file or to send it through a network connection. Of course, the whole agent must be serializable in order to be written successfully. <br> <b>NOT available in MIDP</b> <br> @param s The stream this agent will be sent to. The stream is <em>not</em> closed on exit. @exception IOException Thrown if some I/O error occurs during writing. @see jade.core.Agent#read(InputStream s) */ public void write(OutputStream s) throws IOException { ObjectOutput out = new ObjectOutputStream(s); out.writeUTF(myName); out.writeObject(this); } /** Read a previously saved agent from an input stream and restarts it under its former name. This method can realize some sort of mobility through time, where an agent is saved, then destroyed and then restarted from the saved copy. <br> <b>NOT available in MIDP</b> <br> @param s The stream the agent will be read from. The stream is <em>not</em> closed on exit. @exception IOException Thrown if some I/O error occurs during stream reading. @see jade.core.Agent#write(OutputStream s) * public static void read(InputStream s) throws IOException { try { ObjectInput in = new ObjectInputStream(s); String name = in.readUTF(); Agent a = (Agent)in.readObject(); a.doStart(name); } catch(ClassNotFoundException cnfe) { cnfe.printStackTrace(); } }*/ /** Read a previously saved agent from an input stream and restarts it under a different name. This method can realize agent cloning through streams, where an agent is saved, then an exact copy of it is restarted as a completely separated agent, with the same state but with different identity and address. <br> <b>NOT available in MIDP</b> <br> @param s The stream the agent will be read from. The stream is <em>not</em> closed on exit. @param agentName The name of the new agent, copy of the saved original one. @exception IOException Thrown if some I/O error occurs during stream reading. @see jade.core.Agent#write(OutputStream s) * public static void read(InputStream s, String agentName) throws IOException { try { ObjectInput in = new ObjectInputStream(s); String oldName = in.readUTF(); Agent a = (Agent)in.readObject(); a.doStart(agentName); } catch(ClassNotFoundException cnfe) { cnfe.printStackTrace(); } }*/ /** This method reads a previously saved agent, replacing the current state of this agent with the one previously saved. The stream must contain the saved state of <b>the same agent</b> that it is trying to restore itself; that is, <em>both</em> the Java object <em>and</em> the agent name must be the same. <br> <b>NOT available in MIDP</b> <br> @param s The input stream the agent state will be read from. @exception IOException Thrown if some I/O error occurs during stream reading. <em>Note: This method is currently not implemented</em> */ public void restore(InputStream s) throws IOException { // FIXME: Not implemented } /** This method should not be used by application code. Use the same-named method of <code>jade.wrapper.Agent</code> instead. <br> <b>NOT available in MIDP</b> <br> @see jade.wrapper.Agent#putO2AObject(Object o, boolean blocking) */ public void putO2AObject(Object o, boolean blocking) throws InterruptedException { // Drop object on the floor if object-to-agent communication is // disabled. if(o2aQueue == null) return; // If the queue has a limited capacity and it is full, discard the // first element if((o2aQueueSize != 0) && (o2aQueue.size() == o2aQueueSize)) o2aQueue.remove(0); o2aQueue.add(o); // Reactivate the agent activateAllBehaviours(); // Synchronize the calling thread on a condition associated to the // object if(blocking) { CondVar cond = new CondVar(); // Store lock for later, when getO2AObject will be called o2aLocks.put(o, cond); // Sleep on the condition cond.waitOn(); } } /** This method picks an object (if present) from the internal object-to-agent communication queue. In order for this method to work, the agent must have declared its will to accept objects from other software components running within its JVM. This can be achieved by calling the <code>jade.core.Agent.setEnabledO2ACommunication()</code> method. If the retrieved object was originally inserted by an external component using a blocking call, that call will return during the execution of this method. <br> <b>NOT available in MIDP</b> <br> @return the first object in the queue, or <code>null</code> if the queue is empty. @see jade.wrapper.Agent#putO2AObject(Object o, boolean blocking) @see jade.core.Agent#setEnabledO2ACommunication(boolean enabled, int queueSize) */ public Object getO2AObject() { // Return 'null' if object-to-agent communication is disabled if(o2aQueue == null) return null; if(o2aQueue.isEmpty()) return null; // Retrieve the first object from the object-to-agent // communication queue Object result = o2aQueue.remove(0); // If some thread issued a blocking putO2AObject() call with this // object, wake it up CondVar cond = (CondVar)o2aLocks.remove(result); if(cond != null) { cond.set(); } return result; } /** This method declares this agent attitude towards object-to-agent communication, that is, whether the agent accepts to communicate with other non-JADE components living within the same JVM. <br> <b>NOT available in MIDP</b> <br> @param enabled Tells whether Java objects inserted with <code>putO2AObject()</code> will be accepted. @param queueSize If the object-to-agent communication is enabled, this parameter specifiies the maximum number of Java objects that will be queued. If the passed value is 0, no maximum limit is set up for the queue. @see jade.wrapper.Agent#putO2AObject(Object o, boolean blocking) @see jade.core.Agent#getO2AObject() */ public void setEnabledO2ACommunication(boolean enabled, int queueSize) { if(enabled) { if(o2aQueue == null) o2aQueue = new ArrayList(queueSize); // Ignore a negative value if(queueSize >= 0) o2aQueueSize = queueSize; } else { // Wake up all threads blocked in putO2AObject() calls Iterator it = o2aLocks.values().iterator(); while(it.hasNext()) { CondVar cv = (CondVar)it.next(); cv.set(); } o2aQueue = null; } } //#MIDP_EXCLUDE_END //#APIDOC_EXCLUDE_BEGIN /** This method is the main body of every agent. It provides startup and cleanup hooks for application programmers to put their specific code into. @see jade.core.Agent#setup() @see jade.core.Agent#takeDown() */ public final void run() { try { myLifeCycle.init(); while (myLifeCycle.alive()) { try { myLifeCycle.execute(); // Let other agents go on Thread.yield(); } catch (JADESecurityException jse) { // FIXME: maybe we should send a message to the agent System.out.println("JADESecurityException: "+jse.getMessage()); } catch (InterruptedException ie) { // Change LC state request from the outside. Just do nothing // and let the new LC state do its job } catch (InterruptedIOException ie) { // Change LC state request from the outside. Just do nothing // and let the new LC state do its job } catch (Interrupted i) { // Change LC state request from the outside. Just do nothing // and let the new LC state do its job } } } catch(Throwable t) { System.err.println("*** Uncaught Exception for agent " + myName + " ***"); t.printStackTrace(); } terminating = true; myLifeCycle.end(); } //#APIDOC_EXCLUDE_END /** Inner class ActiveLifeCycle */ private class ActiveLifeCycle extends LifeCycle { private ActiveLifeCycle() { super(AP_INITIATED); } public void setState(int s) { myState = s; } public void init() { setActiveState(AP_ACTIVE); //#MIDP_EXCLUDE_BEGIN notifyStarted(); //#MIDP_EXCLUDE_END setup(); } public void execute() throws JADESecurityException, InterruptedException, InterruptedIOException { // Select the next behaviour to execute Behaviour currentBehaviour = myScheduler.schedule(); // Remember how many messages arrived int oldMsgCounter = messageCounter; // Just do it! currentBehaviour.actionWrapper(); // If the current Behaviour has blocked and more messages arrived // in the meanwhile, restart the behaviour to give it another chance if((oldMsgCounter != messageCounter) && (!currentBehaviour.isRunnable())) { currentBehaviour.restart(); } // When it is needed no more, delete it from the behaviours queue if(currentBehaviour.done()) { currentBehaviour.onEnd(); myScheduler.remove(currentBehaviour); currentBehaviour = null; } else { synchronized(myScheduler) { // Need synchronized block (Crais Sayers, HP): What if // 1) it checks to see if its runnable, sees its not, // so it begins to enter the body of the if clause // 2) meanwhile, in another thread, a message arrives, so // the behaviour is restarted and moved to the ready list. // 3) now back in the first thread, the agent executes the // body of the if clause and, by calling block(), moves // the behaviour back to the blocked list. if(!currentBehaviour.isRunnable()) { // Remove blocked behaviour from ready behaviours queue // and put it in blocked behaviours queue myScheduler.block(currentBehaviour); currentBehaviour = null; } } } } public void end() { clean(false); } public boolean transitionTo(LifeCycle to) { // We can go to whatever state unless we are terminating if (!terminating) { // The agent is going to leave this state. When // the agent will enter this state again it must be // in AP_ACTIVE myState = AP_ACTIVE; return true; } else { return false; } } public void transitionFrom(LifeCycle from) { activateAllBehaviours(); } } // END of inner class ActiveLifeCycle /** Inner class DeletedLifeCycle */ private class DeletedLifeCycle extends LifeCycle { private DeletedLifeCycle() { super(AP_DELETED); } public void end() { clean(true); } public boolean alive() { return false; } } // END of inner class DeletedLifeCycle //#MIDP_EXCLUDE_BEGIN /** Inner class SuspendedLifeCycle */ private class SuspendedLifeCycle extends LifeCycle { private SuspendedLifeCycle() { super(AP_SUSPENDED); } public void execute() throws JADESecurityException, InterruptedException, InterruptedIOException { waitUntilActivate(); } public void end() { clean(false); } public boolean transitionTo(LifeCycle to) { // We can only die or resume return (to.getState() == AP_ACTIVE || to.getState() == AP_DELETED); } } // END of inner class SuspendedLifeCycle //#MIDP_EXCLUDE_END //#APIDOC_EXCLUDE_BEGIN public void clean(boolean ok) { if (!ok) { System.out.println("ERROR: Agent " + myName + " died without being properly terminated !!!"); System.out.println("State was " + myLifeCycle.getState()); } myBufferedLifeCycle = myLifeCycle; myLifeCycle = myActiveLifeCycle; takeDown(); pendingTimers.clear(); myToolkit.handleEnd(myAID); myLifeCycle = myBufferedLifeCycle; } //#APIDOC_EXCLUDE_END /** This protected method is an empty placeholder for application specific startup code. Agent developers can override it to provide necessary behaviour. When this method is called the agent has been already registered with the Agent Platform <b>AMS</b> and is able to send and receive messages. However, the agent execution model is still sequential and no behaviour scheduling is active yet. This method can be used for ordinary startup tasks such as <b>DF</b> registration, but is essential to add at least a <code>Behaviour</code> object to the agent, in order for it to be able to do anything. @see jade.core.Agent#addBehaviour(Behaviour b) @see jade.core.behaviours.Behaviour */ protected void setup() {} /** This protected method is an empty placeholder for application specific cleanup code. Agent developers can override it to provide necessary behaviour. When this method is called the agent has not deregistered itself with the Agent Platform <b>AMS</b> and is still able to exchange messages with other agents. However, no behaviour scheduling is active anymore and the Agent Platform Life Cycle state is already set to <em>deleted</em>. This method can be used for ordinary cleanup tasks such as <b>DF</b> deregistration, but explicit removal of all agent behaviours is not needed. */ protected void takeDown() {} //#MIDP_EXCLUDE_BEGIN protected void beforeMove() {} /** Actions to perform after moving. This empty placeholder method can be overridden by user defined agents to execute some actions just after arriving to the destination agent container for a migration. <br> <b>NOT available in MIDP</b> <br> */ protected void afterMove() {} /** * This empty placeholder method shall be overridden by user defined agents * to execute some actions before copying an agent to another agent container. * <br> * <b>NOT available in MIDP</b> * <br> * @see beforeMove() * @see afterClone() */ protected void beforeClone() {} /** Actions to perform after cloning. This empty placeholder method can be overridden by user defined agents to execute some actions just after creating an agent copy to the destination agent container. <br> <b>NOT available in MIDP</b> <br> */ protected void afterClone() {} //#MIDP_EXCLUDE_END // This method is used by the Agent Container to fire up a new agent for the first time void powerUp(AID id, Thread t) { // Set this agent's name and address and start its embedded thread myName = id.getLocalName(); myHap = id.getHap(); synchronized (this) { // Mutual exclusion with Agent.addPlatformAddress() myAID = id; myToolkit.setPlatformAddresses(myAID); } myThread = t; myThread.start(); } //#MIDP_EXCLUDE_BEGIN private void writeObject(ObjectOutputStream out) throws IOException { // Updates the queue maximum size field, before serialising msgQueueMaxSize = msgQueue.getMaxSize(); out.defaultWriteObject(); } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); // Restore transient fields (apart from myThread, which will be set when the agent will be powered up) msgQueue = new MessageQueue(msgQueueMaxSize); stateLock = new Object(); suspendLock = new Object(); pendingTimers = new AssociationTB(); theDispatcher = TimerDispatcher.getTimerDispatcher(); // restore O2AQueue if (o2aQueueSize > 0) o2aQueue = new ArrayList(o2aQueueSize); o2aLocks = new HashMap(); myToolkit = DummyToolkit.instance(); //#PJAVA_EXCLUDE_BEGIN //For persistence service persistentPendingTimers = new java.util.HashSet(); //#PJAVA_EXCLUDE_END } //#MIDP_EXCLUDE_END /** Thi method is executed when blockingReceive() is called from a separate Thread. It does not affect the agent state. */ private void waitUntilWake(long millis) { synchronized(msgQueue) { try { // Blocks on msgQueue monitor for a while waitOn(msgQueue, millis); } catch (InterruptedException ie) { throw new Interrupted(); } } } //#MIDP_EXCLUDE_BEGIN private void waitUntilActivate() throws InterruptedException { synchronized(suspendLock) { waitOn(suspendLock, 0); } } //#MIDP_EXCLUDE_END /** This method adds a new behaviour to the agent. This behaviour will be executed concurrently with all the others, using a cooperative round robin scheduling. This method is typically called from an agent <code>setup()</code> to fire off some initial behaviour, but can also be used to spawn new behaviours dynamically. @param b The new behaviour to add to the agent. @see jade.core.Agent#setup() @see jade.core.behaviours.Behaviour */ public void addBehaviour(Behaviour b) { b.setAgent(this); myScheduler.add(b); } /** This method removes a given behaviour from the agent. This method is called automatically when a top level behaviour terminates, but can also be called from a behaviour to terminate itself or some other behaviour. @param b The behaviour to remove. @see jade.core.behaviours.Behaviour */ public void removeBehaviour(Behaviour b) { b.setAgent(null); myScheduler.remove(b); } /** Send an <b>ACL</b> message to another agent. This methods sends a message to the agent specified in <code>:receiver</code> message field (more than one agent can be specified as message receiver). @param msg An ACL message object containing the actual message to send. @see jade.lang.acl.ACLMessage */ public final void send(ACLMessage msg) { // Set the sender of the message if not yet set // FIXME. Probably we should always set the sender of the message! try { msg.getSender().getName().charAt(0); } catch (Exception e) { msg.setSender(myAID); } myToolkit.handleSend(msg, myAID); } /** Receives an <b>ACL</b> message from the agent message queue. This method is non-blocking and returns the first message in the queue, if any. Therefore, polling and busy waiting is required to wait for the next message sent using this method. @return A new ACL message, or <code>null</code> if no message is present. @see jade.lang.acl.ACLMessage */ public final ACLMessage receive() { return receive(null); } /** Receives an <b>ACL</b> message matching a given template. This method is non-blocking and returns the first matching message in the queue, if any. Therefore, polling and busy waiting is required to wait for a specific kind of message using this method. @param pattern A message template to match received messages against. @return A new ACL message matching the given template, or <code>null</code> if no such message is present. @see jade.lang.acl.ACLMessage @see jade.lang.acl.MessageTemplate */ public final ACLMessage receive(MessageTemplate pattern) { ACLMessage msg = null; synchronized (msgQueue) { for (Iterator messages = msgQueue.iterator(); messages.hasNext(); ) { ACLMessage cursor = (ACLMessage)messages.next(); if (pattern == null || pattern.match(cursor)) { msgQueue.remove(cursor); //#MIDP_EXCLUDE_BEGIN myToolkit.handleReceived(myAID, cursor); //#MIDP_EXCLUDE_END msg = cursor; break; // Exit while loop } } } return msg; } /** Receives an <b>ACL</b> message from the agent message queue. This method is blocking and suspends the whole agent until a message is available in the queue. @return A new ACL message, blocking the agent until one is available. @see jade.core.Agent#receive() @see jade.lang.acl.ACLMessage */ public final ACLMessage blockingReceive() { return blockingReceive(null, 0); } /** Receives an <b>ACL</b> message from the agent message queue, waiting at most a specified amount of time. @param millis The maximum amount of time to wait for the message. @return A new ACL message, or <code>null</code> if the specified amount of time passes without any message reception. */ public final ACLMessage blockingReceive(long millis) { return blockingReceive(null, millis); } /** Receives an <b>ACL</b> message matching a given message template. This method is blocking and suspends the whole agent until a message is available in the queue. @param pattern A message template to match received messages against. @return A new ACL message matching the given template, blocking until such a message is available. @see jade.core.Agent#receive(MessageTemplate) @see jade.lang.acl.ACLMessage @see jade.lang.acl.MessageTemplate */ public final ACLMessage blockingReceive(MessageTemplate pattern) { return blockingReceive(pattern, 0); } /** Receives an <b>ACL</b> message matching a given message template, waiting at most a specified time. @param pattern A message template to match received messages against. @param millis The amount of time to wait for the message, in milliseconds. @return A new ACL message matching the given template, or <code>null</code> if no suitable message was received within <code>millis</code> milliseconds. @see jade.core.Agent#blockingReceive() */ public final ACLMessage blockingReceive(MessageTemplate pattern, long millis) { ACLMessage msg = null; synchronized(msgQueue) { msg = receive(pattern); long timeToWait = millis; while(msg == null) { long startTime = System.currentTimeMillis(); if (Thread.currentThread().equals(myThread)) { doWait(timeToWait); } else { // blockingReceive() called from an external thread --> Do not change the agent state waitUntilWake(timeToWait); } long elapsedTime = System.currentTimeMillis() - startTime; msg = receive(pattern); if(millis != 0) { timeToWait -= elapsedTime; if(timeToWait <= 0) break; } } } return msg; } /** Puts a received <b>ACL</b> message back into the message queue. This method can be used from an agent behaviour when it realizes it read a message of interest for some other behaviour. The message is put in front of the message queue, so it will be the first returned by a <code>receive()</code> call. @see jade.core.Agent#receive() */ public final void putBack(ACLMessage msg) { synchronized(msgQueue) { msgQueue.addFirst(msg); } } final void setToolkit(AgentToolkit at) { myToolkit = at; } final void resetToolkit() { //#MIDP_EXCLUDE_BEGIN myToolkit = DummyToolkit.instance(); //#MIDP_EXCLUDE_END /*#MIDP_INCLUDE_BEGIN myToolkit = null; #MIDP_INCLUDE_END*/ } //#MIDP_EXCLUDE_BEGIN //#APIDOC_EXCLUDE_BEGIN /** This method blocks until the agent has finished its start-up phase (i.e. until just before its setup() method is called. When this method returns, the target agent is registered with the AMS and the JADE platform is aware of it. */ public synchronized void waitUntilStarted() { while(myLifeCycle.getState() == AP_INITIATED) { try { wait(); } catch(InterruptedException ie) { // Do nothing... } } } //#APIDOC_EXCLUDE_END // Notify creator that the start-up phase has completed private synchronized void notifyStarted() { notifyAll(); } // Notify toolkit of the added behaviour // Package scooped as it is called by the Scheduler void notifyAddBehaviour(Behaviour b) { if (generateBehaviourEvents) { myToolkit.handleBehaviourAdded(myAID, b); } } // Notify the toolkit of the removed behaviour // Package scooped as it is called by the Scheduler void notifyRemoveBehaviour(Behaviour b) { if (generateBehaviourEvents) { myToolkit.handleBehaviourRemoved(myAID, b); } } //#APIDOC_EXCLUDE_BEGIN // Notify the toolkit of the change in behaviour state // Public as it is called by the Scheduler and by the Behaviour class public void notifyChangeBehaviourState(Behaviour b, String from, String to) { if (generateBehaviourEvents) { myToolkit.handleChangeBehaviourState(myAID, b, from, to); } } public void setGenerateBehaviourEvents(boolean b) { generateBehaviourEvents = b; } //#APIDOC_EXCLUDE_END // For persistence service private boolean getGenerateBehaviourEvents() { return generateBehaviourEvents; } // Notify toolkit that the current agent has changed its state private void notifyChangedAgentState(int oldState, int newState) { myToolkit.handleChangedAgentState(myAID, oldState, newState); } //#MIDP_EXCLUDE_END private void activateAllBehaviours() { myScheduler.restartAll(); } /** Put a received message into the agent message queue. The message is put at the back end of the queue. This method is called by JADE runtime system when a message arrives, but can also be used by an agent, and is just the same as sending a message to oneself (though slightly faster). @param msg The ACL message to put in the queue. @see jade.core.Agent#send(ACLMessage msg) */ public final void postMessage(final ACLMessage msg) { synchronized (msgQueue) { if (msg != null) { //#MIDP_EXCLUDE_BEGIN myToolkit.handlePosted(myAID, msg); //#MIDP_EXCLUDE_END msgQueue.addLast(msg); doWake(); messageCounter++; } } } //#CUSTOM_EXCLUDE_BEGIN private jade.content.ContentManager theContentManager = null; /** * Retrieves the agent's content manager * @return The content manager. */ public jade.content.ContentManager getContentManager() { if (theContentManager == null) { theContentManager = new jade.content.ContentManager(); } return theContentManager; } // All the agent's service helper private transient Hashtable helpersTable; /** * Retrieves the agent's service helper * @return The service helper. */ public ServiceHelper getHelper( String serviceName ) throws ServiceException { ServiceHelper se = null; if (helpersTable == null) { helpersTable = new Hashtable(); } se = (ServiceHelper) helpersTable.get(serviceName); // is the helper already into the agent's helpersTable ? if (se == null) { // there isn't, request its creation se = myToolkit.getHelper(this, serviceName); if (se != null) { se.init(this); helpersTable.put(serviceName, se); } else { throw new ServiceException("Null helper"); } } return se; } //#CUSTOM_EXCLUDE_END /** Retrieve a configuration property set in the <code>Profile</code> of the local container (first) or as a System property. @param key the key that maps to the property that has to be retrieved. @param aDefault a default value to be returned if there is no mapping for <code>key</code> */ public String getProperty(String key, String aDefault) { String val = myToolkit.getProperty(key, aDefault); if (val == null || val.equals(aDefault)) { // Try among the System properties String sval = System.getProperty(key); if (sval != null) { val = sval; } } return val; } /** This method is used to interrupt the agent's thread. In J2SE/PJAVA it just calls myThread.interrupt(). In MIDP, where interrupt() is not supported the thread interruption is simulated as described below. The agent thread can be in one of the following three states: 1) Running a behaviour. 2) Sleeping on msgQueue due to a doWait() 3) Sleeping on myScheduler due to a schedule() with no active behaviours Note that in MIDP the suspended state is not supported The idea is: set the 'isInterrupted' flag, then wake up the thread wherever it may be */ private void interruptThread() { //#MIDP_EXCLUDE_BEGIN myThread.interrupt(); //#MIDP_EXCLUDE_END /*#MIDP_INCLUDE_BEGIN synchronized (this) { isInterrupted = true; // case 1: Nothing to do. // case 2: Signal on msgQueue. synchronized (msgQueue) {msgQueue.notifyAll();} // case 3: Signal on the Scheduler synchronized (myScheduler) {myScheduler.notifyAll();} } #MIDP_INCLUDE_END*/ } /** Since in MIDP Thread.interrupt() does not exist and a simulated interruption is used to "interrupt" the agent's thread, we must check whether the simulated interruption happened just before and after going to sleep. */ void waitOn(Object lock, long millis) throws InterruptedException { /*#MIDP_INCLUDE_BEGIN synchronized (this) { if (isInterrupted) { isInterrupted = false; throw new InterruptedException(); } } #MIDP_INCLUDE_END*/ lock.wait(millis); /*#MIDP_INCLUDE_BEGIN synchronized (this) { if (isInterrupted) { isInterrupted = false; throw new InterruptedException(); } } #MIDP_INCLUDE_END*/ } //#J2ME_EXCLUDE_BEGIN // For persistence service -- Hibernate needs java.util collections private java.util.Set getBehaviours() { Behaviour[] behaviours = myScheduler.getBehaviours(); java.util.Set result = new java.util.HashSet(); result.addAll(java.util.Arrays.asList(behaviours)); return result; } // For persistence service -- Hibernate needs java.util collections private void setBehaviours(java.util.Set behaviours) { Behaviour[] arr = new Behaviour[behaviours.size()]; arr = (Behaviour[])behaviours.toArray(arr); // Reconnect all the behaviour -> agent pointers for(int i = 0; i < arr.length; i++) { arr[i].setAgent(this); } myScheduler.setBehaviours(arr); } // For persistence service -- Hibernate needs java.util collections private transient java.util.Set persistentPendingTimers = new java.util.HashSet(); // For persistence service -- Hibernate needs java.util collections private java.util.Set getPendingTimers() { return persistentPendingTimers; } // For persistence service -- Hibernate needs java.util collections private void setPendingTimers(java.util.Set timers) { if(!persistentPendingTimers.equals(timers)) { // Clear the timers table, and install the new timers. pendingTimers.clear(); java.util.Iterator it = timers.iterator(); while(it.hasNext()) { TBPair pair = (TBPair)it.next(); pendingTimers.addPair(pair); } } persistentPendingTimers = timers; } //#J2ME_EXCLUDE_END }
package jade.core; import java.io.Reader; import java.io.StringReader; import java.io.StringWriter; import java.io.Serializable; import java.io.InputStream; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.OutputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import java.io.IOException; import java.io.InterruptedIOException; import java.util.Date; import java.util.Iterator; import java.util.Map; import java.util.HashMap; import java.util.Vector; import jade.core.behaviours.Behaviour; import jade.lang.Codec; import jade.lang.acl.*; import jade.onto.Name; import jade.onto.Frame; import jade.onto.Ontology; import jade.onto.OntologyException; import jade.domain.AgentManagementOntology; import jade.domain.FIPAException; /** The <code>Agent</code> class is the common superclass for user defined software agents. It provides methods to perform basic agent tasks, such as: <ul> <li> <b> Message passing using <code>ACLMessage</code> objects, both unicast and multicast with optional pattern matching. </b> <li> <b> Complete Agent Platform life cycle support, including starting, suspending and killing an agent. </b> <li> <b> Scheduling and execution of multiple concurrent activities. </b> <li> <b> Simplified interaction with <em>FIPA</em> system agents for automating common agent tasks (DF registration, etc.). </b> </ul> Application programmers must write their own agents as <code>Agent</code> subclasses, adding specific behaviours as needed and exploiting <code>Agent</code> class capabilities. @author Giovanni Rimassa - Universita` di Parma @version $Date$ $Revision$ */ public class Agent implements Runnable, Serializable, CommBroadcaster { // This inner class is used to force agent termination when a signal // from the outside is received private class AgentDeathError extends Error { AgentDeathError() { super("Agent " + Thread.currentThread().getName() + " has been terminated."); } } private static class AgentInMotionError extends Error { AgentInMotionError() { super("Agent " + Thread.currentThread().getName() + " is about to move or be cloned."); } } // This class manages bidirectional associations between Timer and // Behaviour objects, using hash tables. This class is fully // synchronized because is accessed both by agent internal thread // and high priority Timer Dispatcher thread. private static class AssociationTB { private Map BtoT = new HashMap(); private Map TtoB = new HashMap(); public synchronized void addPair(Behaviour b, Timer t) { BtoT.put(b, t); TtoB.put(t, b); } public synchronized void removeMapping(Behaviour b) { Timer t = (Timer)BtoT.remove(b); if(t != null) { TtoB.remove(t); } } public synchronized void removeMapping(Timer t) { Behaviour b = (Behaviour)TtoB.remove(t); if(b != null) { BtoT.remove(b); } } public synchronized Timer getPeer(Behaviour b) { return (Timer)BtoT.get(b); } public synchronized Behaviour getPeer(Timer t) { return (Behaviour)TtoB.get(t); } } private static TimerDispatcher theDispatcher; static void setDispatcher(TimerDispatcher td) { if(theDispatcher == null) { theDispatcher = td; theDispatcher.start(); } } static void stopDispatcher() { theDispatcher.stop(); } /** Schedules a restart for a behaviour, after a certain amount of time has passed. @param b The behaviour to restart later. @param millis The amount of time to wait before restarting <code>b</code>. @see jade.core.behaviours.Behaviour#block(long millis) */ public void restartLater(Behaviour b, long millis) { if(millis == 0) return; Timer t = new Timer(System.currentTimeMillis() + millis, this); pendingTimers.addPair(b, t); theDispatcher.add(t); } // Restarts the behaviour associated with t. This method runs within // the time-critical Timer Dispatcher thread. void doTimeOut(Timer t) { Behaviour b = pendingTimers.getPeer(t); if(b != null) { activateBehaviour(b); } } /** Notifies this agent that one of its behaviours has been restarted for some reason. This method clears any timer associated with behaviour object <code>b</code>, and it is unneeded by application level code. To explicitly schedule behaviours, use <code>block()</code> and <code>restart()</code> methods. @param b The behaviour object which was restarted. @see jade.core.behaviours.Behaviour#restart() */ public void notifyRestarted(Behaviour b) { Timer t = pendingTimers.getPeer(b); if(t != null) { pendingTimers.removeMapping(b); theDispatcher.remove(t); } } /** Out of band value for Agent Platform Life Cycle states. */ public static final int AP_MIN = 0; // Hand-made type checking /** Represents the <em>initiated</em> agent state. */ public static final int AP_INITIATED = 1; /** Represents the <em>active</em> agent state. */ public static final int AP_ACTIVE = 2; /** Represents the <em>suspended</em> agent state. */ public static final int AP_SUSPENDED = 3; /** Represents the <em>waiting</em> agent state. */ public static final int AP_WAITING = 4; /** Represents the <em>deleted</em> agent state. */ public static final int AP_DELETED = 5; /** Represents the <code>transit</code> agent state. */ public static final int AP_TRANSIT = 6; // Non compliant states, used internally. Maybe report to FIPA... /** Represents the <code>copy</code> agent state. */ static final int AP_COPY = 7; /** Represents the <code>gone</code> agent state. This is the state the original instance of an agent goes into when a migration transaction successfully commits. */ static final int AP_GONE = 8; /** Out of band value for Agent Platform Life Cycle states. */ public static final int AP_MAX = 9; // Hand-made type checking /** These constants represent the various Domain Life Cycle states */ /** Out of band value for Domain Life Cycle states. */ public static final int D_MIN = 9; // Hand-made type checking /** Represents the <em>active</em> agent state. */ public static final int D_ACTIVE = 10; /** Represents the <em>suspended</em> agent state. */ public static final int D_SUSPENDED = 20; /** Represents the <em>retired</em> agent state. */ public static final int D_RETIRED = 30; /** Represents the <em>unknown</em> agent state. */ public static final int D_UNKNOWN = 40; /** Out of band value for Domain Life Cycle states. */ public static final int D_MAX = 41; // Hand-made type checking /** Default value for message queue size. When the number of buffered messages exceeds this value, older messages are discarded according to a <b><em>FIFO</em></b> replacement policy. @see jade.core.Agent#setQueueSize(int newSize) @see jade.core.Agent#getQueueSize() */ public static final int MSG_QUEUE_SIZE = 100; private MessageQueue msgQueue = new MessageQueue(MSG_QUEUE_SIZE); private transient Vector listeners = new Vector(); private String myName = null; private String myAddress = null; private transient Object stateLock = new Object(); // Used to make state transitions atomic private transient Object waitLock = new Object(); // Used for agent waiting private transient Object suspendLock = new Object(); // Used for agent suspension private transient Thread myThread; private Scheduler myScheduler; private transient AssociationTB pendingTimers = new AssociationTB(); // Free running counter that increments by one for each message // received. private int messageCounter = 0 ; private transient Map languages = new HashMap(); private transient Map ontologies = new HashMap(); /** The <code>Behaviour</code> that is currently executing. @see jade.core.behaviours.Behaviour */ protected Behaviour currentBehaviour; /** Last message received. @see jade.lang.acl.ACLMessage */ protected ACLMessage currentMessage; // This variable is 'volatile' because is used as a latch to signal // agent suspension and termination from outside world. private volatile int myAPState; // These two variables are used as temporary buffers for // mobility-related parameters private transient Location myDestination; private transient String myNewName; // Temporary buffer for agent suspension private int myBufferedState = AP_MIN; private int myDomainState; private Vector blockedBehaviours = new Vector(); /** Default constructor. */ public Agent() { myAPState = AP_INITIATED; myDomainState = D_UNKNOWN; myScheduler = new Scheduler(this); } /** Method to query the agent local name. @return A <code>String</code> containing the local agent name (e.g. <em>peter</em>). */ public String getLocalName() { return myName; } /** Method to query the agent complete name (<em><b>GUID</b></em>). @return A <code>String</code> containing the complete agent name (e.g. <em>peter@iiop://fipa.org:50/acc</em>). */ public String getName() { return myName + '@' + myAddress; } /** Method to query the agent home address. This is the address of the platform where the agent was created, and will never change during the whole lifetime of the agent. @return A <code>String</code> containing the agent home address (e.g. <em>iiop://fipa.org:50/acc</em>). */ public String getAddress() { return myAddress; } /** Adds a Content Language codec to the agent capabilities. When an agent wants to provide automatic support for a specific content language, it must use an implementation of the <code>Codec</code> interface for the specific content language, and add it to its languages table with this method. @param languageName The symbolic name to use for the language. @param translator A translator for the specific content language, able to translate back and forth between text strings and Frame objects. @see jade.core.Agent#deregisterLanguage(String languageName) @see jade.lang.Codec */ public void registerLanguage(String languageName, Codec translator) { languages.put(new Name(languageName), translator); } /** Looks a content language up into the supported languages table. @param languageName The name of the desired content language. @return The translator for the given language, or <code>null</code> if no translator was found. */ public Codec lookupLanguage(String languageName) { return (Codec)languages.get(new Name(languageName)); } /** Removes a Content Language from the agent capabilities. @param languageName The name of the language to remove. @see jade.core.Agent#registerLanguage(String languageName, Codec translator) */ public void deregisterLanguage(String languageName) { languages.remove(new Name(languageName)); } /** Adds an Ontology to the agent capabilities. When an agent wants to provide automatic support for a specific ontology, it must use an implementation of the <code>Ontology</code> interface for the specific ontology and add it to its ontologies table with this method. @param ontologyName The symbolic name to use for the ontology @param o An ontology object, that is able to convert back and forth between Frame objects and application specific Java objects representing concepts. @see jade.core.Agent#deregisterOntology(String ontologyName) @see jade.onto.Ontology */ public void registerOntology(String ontologyName, Ontology o) { ontologies.put(new Name(ontologyName), o); } /** Looks an ontology up into the supported ontologies table. @param ontologyName The name of the desired ontology. @return The given ontology, or <code>null</code> if no such named ontology was found. */ public Ontology lookupOntology(String ontologyName) { return (Ontology)ontologies.get(new Name(ontologyName)); } /** Removes an Ontology from the agent capabilities. @param ontologyName The name of the ontology to remove. @see jade.core.Agent#registerOntology(String ontologyName, Ontology o) */ public void deregisterOntology(String ontologyName) { ontologies.remove(new Name(ontologyName)); } /** Builds a Java object out of an ACL message. This method uses the <code>:language</code> slot to select a content language and the <code>:ontology</code> slot to select an ontology. Then the <code>:content</code> slot is interpreted according to the chosen language and ontology, to build an object of a user defined class. @param msg The ACL message from which a suitable Java object will be built. @return A new Java object representing the message content in the given content language and ontology. @exception jade.domain.FIPAException If some problem related to the content language or to the ontology is detected. @see jade.core.Agent#registerLanguage(String languageName, Codec translator) @see jade.core.Agent#registerOntology(String ontologyName, Ontology o) @see jade.core.Agent#fillContent(ACLMessage msg, Object content, String roleName) */ public Object extractContent(ACLMessage msg) throws FIPAException { Codec c = lookupLanguage(msg.getLanguage()); if(c == null) throw new FIPAException("Unknown Content Language"); Ontology o = lookupOntology(msg.getOntology()); if(o == null) throw new FIPAException("Unknown Ontology"); try { Frame f = c.decode(msg.getContent(), o); return o.createObject(f); } catch(Codec.CodecException cce) { // cce.printStackTrace(); throw new FIPAException("Codec error: " + cce.getMessage()); } catch(OntologyException oe) { // oe.printStackTrace(); throw new FIPAException("Ontology error: " + oe.getMessage()); } } /** Fills the <code>:content</code> slot of an ACL message with the string representation of a user defined ontological object. The given Java object is first converted into a <code>Frame</code> object according to the ontology present in the <code>:ontology</code> message slot, then the <code>Frame</code> is translated into a <code>String</code> using the codec for the content language indicated by the <code>:language</code> message slot. @param msg The ACL message whose content will be filled. @param content A Java object that will be converted into a string and written inti the <code>:content</code> slot. This object must be an instance of a class registered into the ontology named in the <code>:ontology</code> message slot. @param roleName The name of the role played by the class of the object <code>content</code> into the ontology indicated by the <code>:ontology </code> message slot. @exception jade.domain.FIPAException This exception is thrown if the <code>:language</code> or <code>:ontology</code> message slots contain an unknown name, or if some problem occurs during the various translation steps. @see jade.core.Agent#extractContent(ACLMessage msg) @see jade.core.Agent#registerLanguage(String languageName, Codec translator) @see jade.core.Agent#registerOntology(String ontologyName, Ontology o) */ public void fillContent(ACLMessage msg, Object content, String roleName) throws FIPAException { Codec c = lookupLanguage(msg.getLanguage()); if(c == null) throw new FIPAException("Unknown Content Language"); Ontology o = lookupOntology(msg.getOntology()); if(o == null) throw new FIPAException("Unknown Ontology"); try { Frame f = o.createFrame(content, roleName); String s = c.encode(f, o); msg.setContent(s); } catch(OntologyException oe) { oe.printStackTrace(); throw new FIPAException("Ontology error: " + oe.getMessage()); } } // This is used by the agent container to wait for agent termination void join() { try { myThread.join(); } catch(InterruptedException ie) { ie.printStackTrace(); } } public void setQueueSize(int newSize) throws IllegalArgumentException { msgQueue.setMaxSize(newSize); } /** Reads message queue size. A zero value means that the message queue is unbounded (its size is limited only by amount of available memory). @return The actual size of the message queue. @see jade.core.Agent#setQueueSize(int newSize) */ public int getQueueSize() { return msgQueue.getMaxSize(); } /** Read current agent state. This method can be used to query an agent for its state from the outside. @return the Agent Platform Life Cycle state this agent is currently in. */ public int getState() { int state; synchronized(stateLock) { state = myAPState; } return state; } // State transition methods for Agent Platform Life-Cycle /** Make a state transition from <em>initiated</em> to <em>active</em> within Agent Platform Life Cycle. Agents are started automatically by JADE on agent creation and should not be used by application developers, unless creating some kind of agent factory. This method starts the embedded thread of the agent. @param name The local name of the agent. */ public void doStart(String name) { AgentContainerImpl thisContainer = Starter.getContainer(); try { thisContainer.initAgent(name, this, AgentContainer.START); } catch(java.rmi.RemoteException jrre) { jrre.printStackTrace(); } } /** Make a state transition from <em>active</em> to <em>transit</em> within Agent Platform Life Cycle. This method is intended to support agent mobility and is called either by the Agent Platform or by the agent itself to start a migration process. @param destination The <code>Location</code> to migrate to. */ public void doMove(Location destination) { synchronized(stateLock) { if((myAPState == AP_ACTIVE)||(myAPState == AP_WAITING)) { myBufferedState = myAPState; myAPState = AP_TRANSIT; myDestination = destination; // Real action will be executed in the embedded thread if(!myThread.equals(Thread.currentThread())) myThread.interrupt(); } } } /** Make a state transition from <em>active</em> to <em>copy</em> within Agent Platform Life Cycle. This method is intended to support agent mobility and is called either by the Agent Platform or by the agent itself to start a clonation process. @param destination The <code>Location</code> where the copy agent will start. @param newName The name that will be given to the copy agent. */ public void doClone(Location destination, String newName) { synchronized(stateLock) { if((myAPState == AP_ACTIVE)||(myAPState == AP_WAITING)) { myBufferedState = myAPState; myAPState = AP_COPY; myDestination = destination; myNewName = newName; // Real action will be executed in the embedded thread if(!myThread.equals(Thread.currentThread())) myThread.interrupt(); } } } /** Make a state transition from <em>transit</em> or <code>copy</code> to <em>active</em> within Agent Platform Life Cycle. This method is intended to support agent mobility and is called by the destination Agent Platform when a migration process completes and the mobile agent is about to be restarted on its new location. */ void doExecute() { synchronized(stateLock) { myAPState = myBufferedState; myBufferedState = AP_MIN; activateAllBehaviours(); } } /** Make a state transition from <em>transit</em> to <em>gone</em> state. This state is only used to label the original copy of a mobile agent which migrated somewhere. */ void doGone() { synchronized(stateLock) { myAPState = AP_GONE; } } /** Make a state transition from <em>active</em> or <em>waiting</em> to <em>suspended</em> within Agent Platform Life Cycle; the original agent state is saved and will be restored by a <code>doActivate()</code> call. This method can be called from the Agent Platform or from the agent iself and stops all agent activities. Incoming messages for a suspended agent are buffered by the Agent Platform and are delivered as soon as the agent resumes. Calling <code>doSuspend()</code> on a suspended agent has no effect. @see jade.core.Agent#doActivate() */ public void doSuspend() { synchronized(stateLock) { if((myAPState == AP_ACTIVE)||(myAPState == AP_WAITING)) { myBufferedState = myAPState; myAPState = AP_SUSPENDED; } } if(myAPState == AP_SUSPENDED) { if(myThread.equals(Thread.currentThread())) { waitUntilActivate(); } } } /** Make a state transition from <em>suspended</em> to <em>active</em> or <em>waiting</em> (whichever state the agent was in when <code>doSuspend()</code> was called) within Agent Platform Life Cycle. This method is called from the Agent Platform and resumes agent execution. Calling <code>doActivate()</code> when the agent is not suspended has no effect. @see jade.core.Agent#doSuspend() */ public void doActivate() { synchronized(stateLock) { if(myAPState == AP_SUSPENDED) { myAPState = myBufferedState; } } if(myAPState != AP_SUSPENDED) { switch(myBufferedState) { case AP_ACTIVE: activateAllBehaviours(); synchronized(suspendLock) { myBufferedState = AP_MIN; suspendLock.notifyAll(); } break; case AP_WAITING: doWake(); break; } } } /** Make a state transition from <em>active</em> to <em>waiting</em> within Agent Platform Life Cycle. This method can be called by the Agent Platform or by the agent itself and causes the agent to block, stopping all its activities until some event happens. A waiting agent wakes up as soon as a message arrives or when <code>doWake()</code> is called. Calling <code>doWait()</code> on a suspended or waiting agent has no effect. @see jade.core.Agent#doWake() */ public void doWait() { doWait(0); } /** Make a state transition from <em>active</em> to <em>waiting</em> within Agent Platform Life Cycle. This method adds a timeout to the other <code>doWait()</code> version. @param millis The timeout value, in milliseconds. @see jade.core.Agent#doWait() */ public void doWait(long millis) { synchronized(stateLock) { if(myAPState == AP_ACTIVE) myAPState = AP_WAITING; } if(myAPState == AP_WAITING) { if(myThread.equals(Thread.currentThread())) { waitUntilWake(millis); } } } /** Make a state transition from <em>waiting</em> to <em>active</em> within Agent Platform Life Cycle. This method is called from Agent Platform and resumes agent execution. Calling <code>doWake()</code> when an agent is not waiting has no effect. @see jade.core.Agent#doWait() */ public void doWake() { synchronized(stateLock) { if(myAPState == AP_WAITING) { myAPState = AP_ACTIVE; } } if(myAPState == AP_ACTIVE) { activateAllBehaviours(); synchronized(waitLock) { waitLock.notifyAll(); // Wakes up the embedded thread } } } // This method handles both the case when the agents decides to exit // and the case in which someone else kills him from outside. /** Make a state transition from <em>active</em>, <em>suspended</em> or <em>waiting</em> to <em>deleted</em> state within Agent Platform Life Cycle, thereby destroying the agent. This method can be called either from the Agent Platform or from the agent itself. Calling <code>doDelete()</code> on an already deleted agent has no effect. */ public void doDelete() { synchronized(stateLock) { if(myAPState != AP_DELETED) { myAPState = AP_DELETED; if(!myThread.equals(Thread.currentThread())) myThread.interrupt(); } } } /** Write this agent to an output stream; this method can be used to record a snapshot of the agent state on a file or to send it through a network connection. Of course, the whole agent must be serializable in order to be written successfully. @param s The stream this agent will be sent to. The stream is <em>not</em> closed on exit. @exception IOException Thrown if some I/O error occurs during writing. @see jade.core.Agent#read(InputStream s) */ public void write(OutputStream s) throws IOException { ObjectOutput out = new ObjectOutputStream(s); out.writeUTF(myName); out.writeObject(this); } /** Read a previously saved agent from an input stream and restarts it under its former name. This method can realize some sort of mobility through time, where an agent is saved, then destroyed and then restarted from the saved copy. @param s The stream the agent will be read from. The stream is <em>not</em> closed on exit. @exception IOException Thrown if some I/O error occurs during stream reading. @see jade.core.Agent#write(OutputStream s) */ public static void read(InputStream s) throws IOException { try { ObjectInput in = new ObjectInputStream(s); String name = in.readUTF(); Agent a = (Agent)in.readObject(); a.doStart(name); } catch(ClassNotFoundException cnfe) { cnfe.printStackTrace(); } } /** Read a previously saved agent from an input stream and restarts it under a different name. This method can realize agent cloning through streams, where an agent is saved, then an exact copy of it is restarted as a completely separated agent, with the same state but with different identity and address. @param s The stream the agent will be read from. The stream is <em>not</em> closed on exit. @param agentName The name of the new agent, copy of the saved original one. @exception IOException Thrown if some I/O error occurs during stream reading. @see jade.core.Agent#write(OutputStream s) */ public static void read(InputStream s, String agentName) throws IOException { try { ObjectInput in = new ObjectInputStream(s); String name = in.readUTF(); Agent a = (Agent)in.readObject(); a.doStart(agentName); } catch(ClassNotFoundException cnfe) { cnfe.printStackTrace(); } } /** This method reads a previously saved agent, replacing the current state of this agent with the one previously saved. The stream must contain the saved state of <b>the same agent</b> that it is trying to restore itself; that is, <em>both</em> the Java object <em>and</em> the agent name must be the same. @param s The input stream the agent state will be read from. @exception IOException Thrown if some I/O error occurs during stream reading. <em>Note: This method is currently not implemented</em> */ public void restore(InputStream s) throws IOException { // FIXME: Not implemented } /** This method is the main body of every agent. It can handle automatically <b>AMS</b> registration and deregistration and provides startup and cleanup hooks for application programmers to put their specific code into. @see jade.core.Agent#setup() @see jade.core.Agent#takeDown() */ public final void run() { try { switch(myAPState) { case AP_INITIATED: myAPState = AP_ACTIVE; // No 'break' statement - fall through case AP_ACTIVE: registerWithAMS(null,Agent.AP_ACTIVE,null,null,null); setup(); break; case AP_TRANSIT: doExecute(); afterMove(); break; case AP_COPY: doExecute(); registerWithAMS(null,Agent.AP_ACTIVE,null,null,null); afterClone(); break; } mainLoop(); } catch(InterruptedException ie) { // Do Nothing, since this is a killAgent from outside } catch(InterruptedIOException iioe) { // Do nothing, since this is a killAgent from outside } catch(Exception e) { System.err.println("*** Uncaught Exception for agent " + myName + " ***"); e.printStackTrace(); } catch(AgentDeathError ade) { // Do Nothing, since this is a killAgent from outside } finally { switch(myAPState) { case AP_DELETED: int savedState = getState(); myAPState = AP_ACTIVE; takeDown(); destroy(); myAPState = savedState; break; case AP_GONE: break; default: System.out.println("ERROR: Agent " + myName + " died without being properly terminated !!!"); System.out.println("State was " + myAPState); savedState = getState(); myAPState = AP_ACTIVE; takeDown(); destroy(); myAPState = savedState; } } } /** This protected method is an empty placeholder for application specific startup code. Agent developers can override it to provide necessary behaviour. When this method is called the agent has been already registered with the Agent Platform <b>AMS</b> and is able to send and receive messages. However, the agent execution model is still sequential and no behaviour scheduling is active yet. This method can be used for ordinary startup tasks such as <b>DF</b> registration, but is essential to add at least a <code>Behaviour</code> object to the agent, in order for it to be able to do anything. @see jade.core.Agent#addBehaviour(Behaviour b) @see jade.core.behaviours.Behaviour */ protected void setup() {} /** This protected method is an empty placeholder for application specific cleanup code. Agent developers can override it to provide necessary behaviour. When this method is called the agent has not deregistered itself with the Agent Platform <b>AMS</b> and is still able to exchange messages with other agents. However, no behaviour scheduling is active anymore and the Agent Platform Life Cycle state is already set to <em>deleted</em>. This method can be used for ordinary cleanup tasks such as <b>DF</b> deregistration, but explicit removal of all agent behaviours is not needed. */ protected void takeDown() {} /** Actions to perform before moving. This empty placeholder method can be overridden by user defined agents to execute some actions just before leaving an agent container for a migration. */ protected void beforeMove() {} /** Actions to perform after moving. This empty placeholder method can be overridden by user defined agents to execute some actions just after arriving to the destination agent container for a migration. */ protected void afterMove() {} /** Actions to perform before cloning. This empty placeholder method can be overridden by user defined agents to execute some actions just before copying an agent to another agent container. */ protected void beforeClone() {} /** Actions to perform after cloning. This empty placeholder method can be overridden by user defined agents to execute some actions just after creating an agent copy to the destination agent container. */ protected void afterClone() {} // This method is used by the Agent Container to fire up a new agent for the first time void powerUp(String name, String platformAddress, ThreadGroup myGroup) { // Set this agent's name and address and start its embedded thread if((myAPState == AP_INITIATED)||(myAPState == AP_TRANSIT)||(myAPState == AP_COPY)) { myName = new String(name); myAddress = new String(platformAddress); myThread = new Thread(myGroup, this); myThread.setName(myName); myThread.setPriority(myGroup.getMaxPriority()); myThread.start(); } } private void writeObject(ObjectOutputStream out) throws IOException { out.defaultWriteObject(); } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); // Restore transient fields (apart from myThread, which will be set by doStart()) listeners = new Vector(); stateLock = new Object(); suspendLock = new Object(); waitLock = new Object(); pendingTimers = new AssociationTB(); languages = new HashMap(); ontologies = new HashMap(); } private void mainLoop() throws InterruptedException, InterruptedIOException { while(myAPState != AP_DELETED) { try { // Check for Agent state changes switch(myAPState) { case AP_WAITING: waitUntilWake(0); break; case AP_SUSPENDED: waitUntilActivate(); break; case AP_TRANSIT: notifyMove(); if(myAPState == AP_GONE) { beforeMove(); return; } break; case AP_COPY: beforeClone(); notifyCopy(); doExecute(); break; case AP_ACTIVE: try { // Select the next behaviour to execute currentBehaviour = myScheduler.schedule(); } // Someone interrupted the agent. It could be a kill or a // move/clone request... catch(InterruptedException ie) { switch(myAPState) { case AP_DELETED: throw new AgentDeathError(); case AP_TRANSIT: case AP_COPY: throw new AgentInMotionError(); } } // Remember how many messages arrived int oldMsgCounter = messageCounter; // Just do it! currentBehaviour.action(); // If the current Behaviour is blocked and more messages // arrived, restart the behaviour to give it another chance if((oldMsgCounter != messageCounter) && (!currentBehaviour.isRunnable())) currentBehaviour.restart(); // When it is needed no more, delete it from the behaviours queue if(currentBehaviour.done()) { myScheduler.remove(currentBehaviour); currentBehaviour = null; } else if(!currentBehaviour.isRunnable()) { // Remove blocked behaviours from scheduling queue and put it // in blocked behaviours queue myScheduler.remove(currentBehaviour); blockedBehaviours.addElement(currentBehaviour); currentBehaviour = null; } break; } // Now give CPU control to other agents Thread.yield(); } catch(AgentInMotionError aime) { // Do nothing, since this is a doMove() or doClone() from the outside. } } } private void waitUntilWake(long millis) { synchronized(waitLock) { long timeToWait = millis; while(myAPState == AP_WAITING) { try { long startTime = System.currentTimeMillis(); waitLock.wait(timeToWait); // Blocks on waiting state monitor for a while long elapsedTime = System.currentTimeMillis() - startTime; // If this was a timed wait, update time to wait; if the // total time has passed, wake up. if(millis != 0) { timeToWait -= elapsedTime; if(timeToWait <= 0) myAPState = AP_ACTIVE; } } catch(InterruptedException ie) { switch(myAPState) { case AP_DELETED: throw new AgentDeathError(); case AP_TRANSIT: case AP_COPY: throw new AgentInMotionError(); } } } } } private void waitUntilActivate() { synchronized(suspendLock) { while(myAPState == AP_SUSPENDED) { try { suspendLock.wait(); // Blocks on suspended state monitor } catch(InterruptedException ie) { switch(myAPState) { case AP_DELETED: throw new AgentDeathError(); case AP_TRANSIT: case AP_COPY: // Undo the previous clone or move request myAPState = AP_SUSPENDED; } } } } } private void destroy() { try { deregisterWithAMS(); } catch(FIPAException fe) { fe.printStackTrace(); } notifyDestruction(); } /** This method adds a new behaviour to the agent. This behaviour will be executed concurrently with all the others, using a cooperative round robin scheduling. This method is typically called from an agent <code>setup()</code> to fire off some initial behaviour, but can also be used to spawn new behaviours dynamically. @param b The new behaviour to add to the agent. @see jade.core.Agent#setup() @see jade.core.behaviours.Behaviour */ public void addBehaviour(Behaviour b) { myScheduler.add(b); } /** This method removes a given behaviour from the agent. This method is called automatically when a top level behaviour terminates, but can also be called from a behaviour to terminate itself or some other behaviour. @param b The behaviour to remove. @see jade.core.behaviours.Behaviour */ public void removeBehaviour(Behaviour b) { myScheduler.remove(b); } /** Send an <b>ACL</b> message to another agent. This methods sends a message to the agent specified in <code>:receiver</code> message field (more than one agent can be specified as message receiver). @param msg An ACL message object containing the actual message to send. @see jade.lang.acl.ACLMessage */ public final void send(ACLMessage msg) { if(msg.getSource().length() < 1) msg.setSource(myName); CommEvent event = new CommEvent(this, msg); broadcastEvent(event); } /** Send an <b>ACL</b> message to the agent contained in a given <code>AgentGroup</code>. This method allows simple message multicast to be done. A similar result can be obtained putting many agent names in <code>:receiver</code> message field; the difference is that in that case every receiver agent can read all other receivers' names, whereas this method hides multicasting to receivers. @param msg An ACL message object containing the actual message to send. @param g An agent group object holding all receivers names. @see jade.lang.acl.ACLMessage @see jade.core.AgentGroup */ public final void send(ACLMessage msg, AgentGroup g) { if(msg.getSource().length() < 1) msg.setSource(myName); CommEvent event = new CommEvent(this, msg, g); broadcastEvent(event); } /** Receives an <b>ACL</b> message from the agent message queue. This method is non-blocking and returns the first message in the queue, if any. Therefore, polling and busy waiting is required to wait for the next message sent using this method. @return A new ACL message, or <code>null</code> if no message is present. @see jade.lang.acl.ACLMessage */ public final ACLMessage receive() { synchronized(waitLock) { if(msgQueue.isEmpty()) { return null; } else { currentMessage = msgQueue.removeFirst(); return currentMessage; } } } /** Receives an <b>ACL</b> message matching a given template. This method is non-blocking and returns the first matching message in the queue, if any. Therefore, polling and busy waiting is required to wait for a specific kind of message using this method. @param pattern A message template to match received messages against. @return A new ACL message matching the given template, or <code>null</code> if no such message is present. @see jade.lang.acl.ACLMessage @see jade.lang.acl.MessageTemplate */ public final ACLMessage receive(MessageTemplate pattern) { ACLMessage msg = null; synchronized(waitLock) { Iterator messages = msgQueue.iterator(); while(messages.hasNext()) { ACLMessage cursor = (ACLMessage)messages.next(); if(pattern.match(cursor)) { msg = cursor; msgQueue.remove(cursor); currentMessage = cursor; break; // Exit while loop } } } return msg; } /** Receives an <b>ACL</b> message from the agent message queue. This method is blocking and suspends the whole agent until a message is available in the queue. JADE provides a special behaviour named <code>ReceiverBehaviour</code> to wait for a message within a behaviour without suspending all the others and without wasting CPU time doing busy waiting. @return A new ACL message, blocking the agent until one is available. @see jade.lang.acl.ACLMessage @see jade.core.behaviours.ReceiverBehaviour */ public final ACLMessage blockingReceive() { ACLMessage msg = null; while(msg == null) { msg = blockingReceive(0); } return msg; } /** Receives an <b>ACL</b> message from the agent message queue, waiting at most a specified amount of time. @param millis The maximum amount of time to wait for the message. @return A new ACL message, or <code>null</code> if the specified amount of time passes without any message reception. */ public final ACLMessage blockingReceive(long millis) { synchronized(waitLock) { ACLMessage msg = receive(); if(msg == null) { doWait(millis); msg = receive(); } return msg; } } /** Receives an <b>ACL</b> message matching a given message template. This method is blocking and suspends the whole agent until a message is available in the queue. JADE provides a special behaviour named <code>ReceiverBehaviour</code> to wait for a specific kind of message within a behaviour without suspending all the others and without wasting CPU time doing busy waiting. @param pattern A message template to match received messages against. @return A new ACL message matching the given template, blocking until such a message is available. @see jade.lang.acl.ACLMessage @see jade.lang.acl.MessageTemplate @see jade.core.behaviours.ReceiverBehaviour */ public final ACLMessage blockingReceive(MessageTemplate pattern) { ACLMessage msg = null; while(msg == null) { msg = blockingReceive(pattern, 0); } return msg; } /** Receives an <b>ACL</b> message matching a given message template, waiting at most a specified time. @param pattern A message template to match received messages against. @param millis The amount of time to wait for the message, in milliseconds. @return A new ACL message matching the given template, or <code>null</code> if no suitable message was received within <code>millis</code> milliseconds. @see jade.core.Agent#blockingReceive() */ public final ACLMessage blockingReceive(MessageTemplate pattern, long millis) { ACLMessage msg = null; synchronized(waitLock) { msg = receive(pattern); long timeToWait = millis; while(msg == null) { long startTime = System.currentTimeMillis(); doWait(timeToWait); long elapsedTime = System.currentTimeMillis() - startTime; msg = receive(pattern); if(millis != 0) { timeToWait -= elapsedTime; if(timeToWait <= 0) break; } } } return msg; } /** Puts a received <b>ACL</b> message back into the message queue. This method can be used from an agent behaviour when it realizes it read a message of interest for some other behaviour. The message is put in front of the message queue, so it will be the first returned by a <code>receive()</code> call. @see jade.core.Agent#receive() */ public final void putBack(ACLMessage msg) { synchronized(waitLock) { msgQueue.addFirst(msg); } } private ACLMessage FipaRequestMessage(String dest, String replyString) { ACLMessage request = new ACLMessage(ACLMessage.REQUEST); request.setSource(myName); request.removeAllDests(); request.addDest(dest); request.setLanguage("SL0"); request.setOntology("fipa-agent-management"); request.setProtocol("fipa-request"); request.setReplyWith(replyString); return request; } private String doFipaRequestClient(ACLMessage request, String replyString) throws FIPAException { send(request); ACLMessage reply = blockingReceive(MessageTemplate.MatchReplyTo(replyString)); if(reply.getPerformative() == ACLMessage.AGREE) { reply = blockingReceive(MessageTemplate.MatchReplyTo(replyString)); if(reply.getPerformative() != ACLMessage.INFORM) { String content = reply.getContent(); StringReader text = new StringReader(content); throw FIPAException.fromText(text); } else { String content = reply.getContent(); return content; } } else { String content = reply.getContent(); StringReader text = new StringReader(content); throw FIPAException.fromText(text); } } /** Register this agent with Agent Platform <b>AMS</b>. While this task can be accomplished with regular message passing according to <b>FIPA</b> protocols, this method is meant to ease this common duty. However, since <b>AMS</b> registration and deregistration are automatic in JADE, this method should not be used by application programmers. Some parameters here are optional, and <code>null</code> can safely be passed for them. @param signature An optional signature string, used for security reasons. @param APState The Agent Platform state of the agent; must be a valid state value (typically, <code>Agent.AP_ACTIVE</code> constant is passed). @param delegateAgent An optional delegate agent name. @param forwardAddress An optional forward address. @param ownership An optional ownership string. @exception FIPAException A suitable exception can be thrown when a <code>refuse</code> or <code>failure</code> messages are received from the AMS to indicate some error condition. */ public void registerWithAMS(String signature, int APState, String delegateAgent, String forwardAddress, String ownership) throws FIPAException { String replyString = myName + "-ams-registration-" + (new Date()).getTime(); ACLMessage request = FipaRequestMessage("ams", replyString); // Build an AMS action object for the request AgentManagementOntology.AMSAction a = new AgentManagementOntology.AMSAction(); AgentManagementOntology.AMSAgentDescriptor amsd = new AgentManagementOntology.AMSAgentDescriptor(); amsd.setName(getName()); amsd.setAddress(getAddress()); amsd.setAPState(APState); amsd.setDelegateAgentName(delegateAgent); amsd.setForwardAddress(forwardAddress); amsd.setOwnership(ownership); a.setName(AgentManagementOntology.AMSAction.REGISTERAGENT); a.setArg(amsd); // Convert it to a String and write it in content field of the request StringWriter text = new StringWriter(); a.toText(text); request.setContent(text.toString()); // Send message and collect reply doFipaRequestClient(request, replyString); } /** Authenticate this agent with Agent Platform <b>AMS</b>. While this task can be accomplished with regular message passing according to <b>FIPA</b> protocols, this method is meant to ease this common duty. Some parameters here are optional, and <code>null</code> can safely be passed for them. @param signature An optional signature string, used for security reasons. @param APState The Agent Platform state of the agent; must be a valid state value (typically, <code>Agent.AP_ACTIVE</code> constant is passed). @param delegateAgent An optional delegate agent name. @param forwardAddress An optional forward address. @param ownership An optional ownership string. @exception FIPAException A suitable exception can be thrown when a <code>refuse</code> or <code>failure</code> messages are received from the AMS to indicate some error condition. <em>This method is currently not implemented.</em> */ public void authenticateWithAMS(String signature, int APState, String delegateAgent, String forwardAddress, String ownership) throws FIPAException { // FIXME: Not implemented } /** Deregister this agent with Agent Platform <b>AMS</b>. While this task can be accomplished with regular message passing according to <b>FIPA</b> protocols, this method is meant to ease this common duty. However, since <b>AMS</b> registration and deregistration are automatic in JADE, this method should not be used by application programmers. @exception FIPAException A suitable exception can be thrown when a <code>refuse</code> or <code>failure</code> messages are received from the AMS to indicate some error condition. */ public void deregisterWithAMS() throws FIPAException { String replyString = myName + "-ams-deregistration-" + (new Date()).getTime(); // Get a semi-complete request message ACLMessage request = FipaRequestMessage("ams", replyString); // Build an AMS action object for the request AgentManagementOntology.AMSAction a = new AgentManagementOntology.AMSAction(); AgentManagementOntology.AMSAgentDescriptor amsd = new AgentManagementOntology.AMSAgentDescriptor(); amsd.setName(getName()); a.setName(AgentManagementOntology.AMSAction.DEREGISTERAGENT); a.setArg(amsd); // Convert it to a String and write it in content field of the request StringWriter text = new StringWriter(); a.toText(text); request.setContent(text.toString()); // Send message and collect reply doFipaRequestClient(request, replyString); } /** Modifies the data about this agent kept by Agent Platform <b>AMS</b>. While this task can be accomplished with regular message passing according to <b>FIPA</b> protocols, this method is meant to ease this common duty. Some parameters here are optional, and <code>null</code> can safely be passed for them. When a non null parameter is passed, it replaces the value currently stored inside <b>AMS</b> agent. @param signature An optional signature string, used for security reasons. @param APState The Agent Platform state of the agent; must be a valid state value (typically, <code>Agent.AP_ACTIVE</code> constant is passed). @param delegateAgent An optional delegate agent name. @param forwardAddress An optional forward address. @param ownership An optional ownership string. @exception FIPAException A suitable exception can be thrown when a <code>refuse</code> or <code>failure</code> messages are received from the AMS to indicate some error condition. */ public void modifyAMSRegistration(String signature, int APState, String delegateAgent, String forwardAddress, String ownership) throws FIPAException { String replyString = myName + "-ams-modify-" + (new Date()).getTime(); ACLMessage request = FipaRequestMessage("ams", replyString); // Build an AMS action object for the request AgentManagementOntology.AMSAction a = new AgentManagementOntology.AMSAction(); AgentManagementOntology.AMSAgentDescriptor amsd = new AgentManagementOntology.AMSAgentDescriptor(); amsd.setName(getName()); amsd.setAddress(getAddress()); amsd.setAPState(APState); amsd.setDelegateAgentName(delegateAgent); amsd.setForwardAddress(forwardAddress); amsd.setOwnership(ownership); a.setName(AgentManagementOntology.AMSAction.MODIFYAGENT); a.setArg(amsd); // Convert it to a String and write it in content field of the request StringWriter text = new StringWriter(); a.toText(text); request.setContent(text.toString()); // Send message and collect reply doFipaRequestClient(request, replyString); } /** This method uses Agent Platform <b>ACC</b> agent to forward an ACL message. Calling this method is exactly the same as calling <code>send()</code>, only slower, since the message is first sent to the ACC using a <code>fipa-request</code> standard protocol, and then bounced to actual destination agent. @param msg The ACL message to send. @exception FIPAException A suitable exception can be thrown when a <code>refuse</code> or <code>failure</code> messages are received from the ACC to indicate some error condition. @see jade.core.Agent#send(ACLMessage msg) */ public void forwardWithACC(ACLMessage msg) throws FIPAException { String replyString = myName + "-acc-forward-" + (new Date()).getTime(); ACLMessage request = FipaRequestMessage("acc", replyString); // Build an ACC action object for the request AgentManagementOntology.ACCAction a = new AgentManagementOntology.ACCAction(); a.setName(AgentManagementOntology.ACCAction.FORWARD); a.setArg(msg); // Convert it to a String and write it in content field of the request StringWriter text = new StringWriter(); a.toText(text); request.setContent(text.toString()); // Send message and collect reply doFipaRequestClient(request, replyString); } /** Register this agent with a <b>DF</b> agent. While this task can be accomplished with regular message passing according to <b>FIPA</b> protocols, this method is meant to ease this common duty. @param dfName The GUID of the <b>DF</b> agent to register with. @param dfd A <code>DFAgentDescriptor</code> object containing all data necessary to the registration. @exception FIPAException A suitable exception can be thrown when a <code>refuse</code> or <code>failure</code> messages are received from the DF to indicate some error condition. @see jade.domain.AgentManagementOntology.DFAgentDescriptor */ public void registerWithDF(String dfName, AgentManagementOntology.DFAgentDescriptor dfd) throws FIPAException { String replyString = myName + "-df-register-" + (new Date()).getTime(); ACLMessage request = FipaRequestMessage(dfName, replyString); // Build a DF action object for the request AgentManagementOntology.DFAction a = new AgentManagementOntology.DFAction(); a.setName(AgentManagementOntology.DFAction.REGISTER); a.setActor(dfName); a.setArg(dfd); // Convert it to a String and write it in content field of the request StringWriter text = new StringWriter(); a.toText(text); request.setContent(text.toString()); // Send message and collect reply doFipaRequestClient(request, replyString); } /** Deregister this agent from a <b>DF</b> agent. While this task can be accomplished with regular message passing according to <b>FIPA</b> protocols, this method is meant to ease this common duty. @param dfName The GUID of the <b>DF</b> agent to deregister from. @param dfd A <code>DFAgentDescriptor</code> object containing all data necessary to the deregistration. @exception FIPAException A suitable exception can be thrown when a <code>refuse</code> or <code>failure</code> messages are received from the DF to indicate some error condition. @see jade.domain.AgentManagementOntology.DFAgentDescriptor */ public void deregisterWithDF(String dfName, AgentManagementOntology.DFAgentDescriptor dfd) throws FIPAException { String replyString = myName + "-df-deregister-" + (new Date()).getTime(); ACLMessage request = FipaRequestMessage(dfName, replyString); // Build a DF action object for the request AgentManagementOntology.DFAction a = new AgentManagementOntology.DFAction(); a.setName(AgentManagementOntology.DFAction.DEREGISTER); a.setActor(dfName); a.setArg(dfd); // Convert it to a String and write it in content field of the request StringWriter text = new StringWriter(); a.toText(text); request.setContent(text.toString()); // Send message and collect reply doFipaRequestClient(request, replyString); } /** Modifies data about this agent contained within a <b>DF</b> agent. While this task can be accomplished with regular message passing according to <b>FIPA</b> protocols, this method is meant to ease this common duty. @param dfName The GUID of the <b>DF</b> agent holding the data to be changed. @param dfd A <code>DFAgentDescriptor</code> object containing all new data values; every non null slot value replaces the corresponding value held inside the <b>DF</b> agent. @exception FIPAException A suitable exception can be thrown when a <code>refuse</code> or <code>failure</code> messages are received from the DF to indicate some error condition. @see jade.domain.AgentManagementOntology.DFAgentDescriptor */ public void modifyDFData(String dfName, AgentManagementOntology.DFAgentDescriptor dfd) throws FIPAException { String replyString = myName + "-df-modify-" + (new Date()).getTime(); ACLMessage request = FipaRequestMessage(dfName, replyString); // Build a DF action object for the request AgentManagementOntology.DFAction a = new AgentManagementOntology.DFAction(); a.setName(AgentManagementOntology.DFAction.MODIFY); a.setActor(dfName); a.setArg(dfd); // Convert it to a String and write it in content field of the request StringWriter text = new StringWriter(); a.toText(text); request.setContent(text.toString()); // Send message and collect reply doFipaRequestClient(request, replyString); } /** Searches for data contained within a <b>DF</b> agent. While this task can be accomplished with regular message passing according to <b>FIPA</b> protocols, this method is meant to ease this common duty. Nevertheless, a complete, powerful search interface is provided; search constraints can be given and recursive searches are possible. The only shortcoming is that this method blocks the whole agent until the search terminates. A special <code>SearchDFBehaviour</code> can be used to perform <b>DF</b> searches without blocking. @param dfName The GUID of the <b>DF</b> agent to start search from. @param dfd A <code>DFAgentDescriptor</code> object containing data to search for; this parameter is used as a template to match data against. @param constraints A <code>Vector</code> that must be filled with all <code>Constraint</code> objects to apply to the current search. This can be <code>null</code> if no search constraints are required. @return A <code>DFSearchResult</code> object containing all found <code>DFAgentDescriptor</code> objects matching the given descriptor, subject to given search constraints for search depth and result size. @exception FIPAException A suitable exception can be thrown when a <code>refuse</code> or <code>failure</code> messages are received from the DF to indicate some error condition. @see jade.domain.AgentManagementOntology.DFAgentDescriptor @see java.util.Vector @see jade.domain.AgentManagementOntology.Constraint @see jade.domain.AgentManagementOntology.DFSearchResult */ public AgentManagementOntology.DFSearchResult searchDF(String dfName, AgentManagementOntology.DFAgentDescriptor dfd, Vector constraints) throws FIPAException { String replyString = myName + "-df-search-" + (new Date()).getTime(); ACLMessage request = FipaRequestMessage(dfName, replyString); // Build a DF action object for the request AgentManagementOntology.DFSearchAction a = new AgentManagementOntology.DFSearchAction(); a.setName(AgentManagementOntology.DFAction.SEARCH); a.setActor(dfName); a.setArg(dfd); if(constraints == null) { AgentManagementOntology.Constraint c = new AgentManagementOntology.Constraint(); c.setName(AgentManagementOntology.Constraint.DFDEPTH); c.setFn(AgentManagementOntology.Constraint.EXACTLY); c.setArg(1); a.addConstraint(c); } else { // Put constraints into action Iterator i = constraints.iterator(); while(i.hasNext()) { AgentManagementOntology.Constraint c = (AgentManagementOntology.Constraint)i.next(); a.addConstraint(c); } } // Convert it to a String and write it in content field of the request StringWriter textOut = new StringWriter(); a.toText(textOut); request.setContent(textOut.toString()); // Send message and collect reply String content = doFipaRequestClient(request, replyString); // Extract agent descriptors from reply message AgentManagementOntology.DFSearchResult found = null; StringReader textIn = new StringReader(content); try { found = AgentManagementOntology.DFSearchResult.fromText(textIn); } catch(jade.domain.ParseException jdpe) { jdpe.printStackTrace(); } catch(jade.domain.TokenMgrError jdtme) { jdtme.printStackTrace(); } return found; } // Event handling methods // Broadcast communication event to registered listeners private void broadcastEvent(CommEvent event) { synchronized(listeners) { Iterator i = listeners.iterator(); while(i.hasNext()) { CommListener l = (CommListener)i.next(); l.CommHandle(event); } } } // Register a new listener public final void addCommListener(CommListener l) { synchronized(listeners) { listeners.add(l); } } // Remove a registered listener public final void removeCommListener(CommListener l) { synchronized(listeners) { listeners.remove(l); } } // Notify listeners of the destruction of the current agent private void notifyDestruction() { synchronized(listeners) { Iterator i = listeners.iterator(); while(i.hasNext()) { CommListener l = (CommListener)i.next(); l.endSource(myName); } } } // Notify listeners of the need to move the current agent private void notifyMove() { synchronized(listeners) { Iterator i = listeners.iterator(); while(i.hasNext()) { CommListener l = (CommListener)i.next(); l.moveSource(myName, myDestination); } } } // Notify listeners of the need to copy the current agent private void notifyCopy() { synchronized(listeners) { Iterator i = listeners.iterator(); while(i.hasNext()) { CommListener l = (CommListener)i.next(); l.copySource(myName, myDestination, myNewName); } } } private void activateBehaviour(Behaviour b) { Behaviour root = b.root(); blockedBehaviours.remove(root); b.restart(); myScheduler.add(root); } private void activateAllBehaviours() { // Put all blocked behaviours back in ready queue, // atomically with respect to the Scheduler object synchronized(myScheduler) { while(!blockedBehaviours.isEmpty()) { Behaviour b = (Behaviour)blockedBehaviours.lastElement(); blockedBehaviours.removeElementAt(blockedBehaviours.size() - 1); b.restart(); myScheduler.add(b); } } } /** Put a received message into the agent message queue. The message is put at the back end of the queue. This method is called by JADE runtime system when a message arrives, but can also be used by an agent, and is just the same as sending a message to oneself (though slightly faster). @param msg The ACL message to put in the queue. @see jade.core.Agent#send(ACLMessage msg) */ public final void postMessage (ACLMessage msg) { synchronized(waitLock) { /* try { java.io.FileWriter f = new java.io.FileWriter("logs/" + getLocalName(), true); f.write("waitLock taken in postMessage() [thread " + Thread.currentThread().getName() + "]\n"); msg.toText(f); f.close(); } catch(java.io.IOException ioe) { System.out.println(ioe.getMessage()); } */ if(msg != null) msgQueue.addLast(msg); doWake(); messageCounter++; } /* try { java.io.FileWriter f = new java.io.FileWriter("logs/" + getLocalName(), true); f.write("waitLock dropped in postMessage() [thread " + Thread.currentThread().getName() + "]\n"); f.close(); } catch(java.io.IOException ioe) { System.out.println(ioe.getMessage()); } */ } Iterator messages() { return msgQueue.iterator(); } }
package jade.onto; import java.util.Map; import java.util.HashMap; import java.util.List; import java.util.ArrayList; import java.util.Iterator; public class Frame { protected static class NoSuchSlotException extends OntologyException { public NoSuchSlotException(String frameName, String slotName) { super("No slot named " + slotName + " in frame " + frameName); } } private String myName; private Map slotsByName; private List slotsByPosition; public Frame(String name) { myName = name; slotsByName = new HashMap(); slotsByPosition = new ArrayList(); } public String getName() { return myName; } public void putSlot(String name, Object value) { slotsByName.put(new Name(name), value); slotsByPosition.add(value); } public void putSlot(Object value) { // generate a name with an underscore followed by the position number String dummyName = "_" + Integer.toString(slotsByPosition.size()); // Add more underscores as needed while(slotsByName.containsKey(dummyName)) dummyName = "_" + dummyName; putSlot(dummyName, value); } public Object getSlot(String name) throws NoSuchSlotException { Object result = slotsByName.get(new Name(name)); if(result == null) throw new NoSuchSlotException(myName, name); return result; } public Object getSlot(int position) throws NoSuchSlotException { try { return slotsByPosition.get(position); } catch(IndexOutOfBoundsException ioobe) { throw new NoSuchSlotException(myName, "@" + position); } } final Iterator terms() { return slotsByPosition.iterator(); } public void dump() { Iterator i = slotsByName.entrySet().iterator(); while(i.hasNext()) { Map.Entry e = (Map.Entry)i.next(); Name name = (Name)e.getKey(); Object slot = e.getValue(); System.out.print("( " + name + " "); if(slot instanceof Frame) { Frame f = (Frame)slot; f.dump(); } else System.out.print(slot.toString()); System.out.println(" )"); } } }
// of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // all copies or substantial portions of the Software. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. package com.github.urho3d; import org.libsdl.app.SDLActivity; import java.io.File; import java.util.*; public class UrhoActivity extends SDLActivity { private static final String TAG = "Urho3D"; private static String[] mArguments = new String[0]; @Override protected String[] getArguments() { return mArguments; } @Override public void onBackPressed() { finish(); } public static ArrayList<String> getLibraryNames(SDLActivity activity) { File[] files = new File(activity.getApplicationInfo().nativeLibraryDir).listFiles((dir, filename) -> { // Only list libraries, i.e. exclude gdbserver when it presents return filename.matches("^lib.*\\.so$"); }); if (files == null) { return null; } else { Arrays.sort(files, (lhs, rhs) -> Long.valueOf(lhs.lastModified()).compareTo(rhs.lastModified())); ArrayList<String> libraryNames = new ArrayList<>(files.length); for (final File libraryFilename : files) { libraryNames.add(libraryFilename.getName().replaceAll("^lib(.*)\\.so$", "$1")); } // Load engine first and player last int index = libraryNames.indexOf("Urho3D"); if (index >= 0) { // Static builds would not contain this library. libraryNames.add(0, libraryNames.remove(index)); } index = libraryNames.indexOf("Player"); if (index >= 0) { // Static builds would not contain this library. libraryNames.add(libraryNames.size() - 1, libraryNames.remove(index)); } index = libraryNames.indexOf("c++_shared"); if (index >= 0) { // Static builds would not contain this library. libraryNames.add(0, libraryNames.remove(index)); } return libraryNames; } } }
package com.ociweb.gl.benchmark; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.atomic.AtomicInteger; import com.ociweb.gl.api.HTTPRequestReader; import com.ociweb.gl.api.HTTPResponseService; import com.ociweb.pronghorn.network.config.HTTPContentTypeDefaults; import com.ociweb.pronghorn.pipe.ObjectPipe; import io.reactiverse.pgclient.PgIterator; import io.reactiverse.pgclient.Tuple; public class ProcessUpdate { private transient ObjectPipe<ResultObject> DBUpdateInFlight; private final transient List<ResultObject> collectorDBUpdate = new ArrayList<ResultObject>(); private final transient ThreadLocalRandom localRandom = ThreadLocalRandom.current(); private final HTTPResponseService service; private final transient PoolManager pm; private final AtomicInteger requestsInFlight = new AtomicInteger(); public ProcessUpdate(int pipelineBits, HTTPResponseService service, PoolManager pm) { this.DBUpdateInFlight = new ObjectPipe<ResultObject>(pipelineBits, ResultObject.class, ResultObject::new); this.service = service; this.pm = pm; } private int randomValue() { return 1+localRandom.nextInt(10000); } public void tickEvent() { ResultObject temp = DBUpdateInFlight.tailObject(); while (null!=temp && temp.getStatus()>=0) { consumeResultObjectDBUpdate(temp); temp = DBUpdateInFlight.tailObject(); } } public boolean updateRestRequest(HTTPRequestReader request) { int queries; if (Struct.UPDATES_ROUTE_INT == request.getRouteAssoc() ) { queries = Math.min(Math.max(1, (request.structured().readInt(Field.QUERIES))),500); } else { queries = 1; } long conId = request.getConnectionId(); long seqCode = request.getSequenceCode(); int temp = requestsInFlight.incrementAndGet(); if (DBUpdateInFlight.hasRoomFor(queries) || service.hasRoomFor(temp)) { final AtomicInteger outstanding = new AtomicInteger(queries); final List<ResultObject> toUpdate = new ArrayList<ResultObject>(); int q = queries; while (--q >= 0) { final ResultObject worldObject = DBUpdateInFlight.headObject(); assert(null!=worldObject); worldObject.setConnectionId(conId); worldObject.setSequenceId(seqCode); worldObject.setStatus(-2);//out for work worldObject.setGroupSize(queries); worldObject.setId(randomValue()); pm.pool().preparedQuery("SELECT * FROM world WHERE id=$1", Tuple.of(worldObject.getId()), r -> { if (r.succeeded()) { PgIterator resultSet = r.result().iterator(); Tuple row = resultSet.next(); assert(worldObject.getId()==row.getInteger(0)); //read the existing random value and store it in the world object worldObject.setResult(row.getInteger(1)); //the object can be used here with the old value //set the new random value in this object worldObject.setResult(randomValue()); toUpdate.add(worldObject); } else { System.out.println("unable to query"); if (r.cause()!=null) { r.cause().printStackTrace(); } worldObject.setStatus(500); } if (0 == outstanding.decrementAndGet()) { //call update for all the query updates... List<Tuple> args = new ArrayList<Tuple>(); toUpdate.forEach(w-> { args.add(Tuple.of(w.getResult(), w.getId())); }); Collections.sort(args, (a,b) -> { return Integer.compare( ((Tuple)a).getInteger(0), ((Tuple)b).getInteger(0)); }); System.out.println("call for update to "+args.size()); pm.pool().preparedBatch("UPDATE world SET randomnumber=$1 WHERE id=$2", args, ar -> { int status; if (ar.succeeded()) { status = 200; } else { System.out.println("unable to update"); if (ar.cause()!=null) { ar.cause().printStackTrace(); } status = 500; } toUpdate.forEach(w->{ w.setStatus(status); }); System.out.println("finished update for "+toUpdate.size()+" status "+status); }); } }); DBUpdateInFlight.moveHeadForward(); //always move to ensure this can be read. } return true; } else { requestsInFlight.decrementAndGet(); return false; } } private void consumeResultObjectDBUpdate(final ResultObject t) { //collect all the objects collectorDBUpdate.add(t); DBUpdateInFlight.moveTailForward();//only move forward when it is consumed. if (collectorDBUpdate.size() == t.getGroupSize()) { //now ready to send, we have all the data publishMultiResponseDBUpdate(t.getConnectionId(), t.getSequenceId()); } } private void publishMultiResponseDBUpdate(long conId, long seqCode) { boolean result = service.publishHTTPResponse(conId, seqCode, 200, HTTPContentTypeDefaults.JSON, w-> { Templates.multiTemplate.render(w, collectorDBUpdate); int c = collectorDBUpdate.size(); while (--c>=0) { assert(collectorDBUpdate.get(c).getConnectionId() == conId); assert(collectorDBUpdate.get(c).getSequenceId() == seqCode); collectorDBUpdate.get(c).setStatus(-1); } collectorDBUpdate.clear(); DBUpdateInFlight.publishTailPosition(); }); assert(result) : "internal error, we should not pick up more work than we can send"; requestsInFlight.decrementAndGet(); } }
package ly.count.android.sdk; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.util.Log; import java.io.PrintWriter; import java.io.StringWriter; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.List; import java.util.Map; import java.util.HashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; public class Countly { /** * Current version of the Count.ly Android SDK as a displayable string. */ public static final String COUNTLY_SDK_VERSION_STRING = "17.05"; /** * Used as request meta data on every request */ public static final String COUNTLY_SDK_NAME = "java-native-android"; /** * Default string used in the begin session metrics if the * app version cannot be found. */ public static final String DEFAULT_APP_VERSION = "1.0"; /** * Tag used in all logging in the Count.ly SDK. */ public static final String TAG = "Countly"; /** * Determines how many custom events can be queued locally before * an attempt is made to submit them to a Count.ly server. */ private static int EVENT_QUEUE_SIZE_THRESHOLD = 10; /** * How often onTimer() is called. */ private static final long TIMER_DELAY_IN_SECONDS = 60; protected static List<String> publicKeyPinCertificates; protected static List<String> certificatePinCertificates; protected static final Map<String, Event> timedEvents = new HashMap<String, Event>(); /** * Enum used in Countly.initMessaging() method which controls what kind of * app installation it is. Later (in Countly Dashboard or when calling Countly API method), * you'll be able to choose whether you want to send a message to test devices, * or to production ones. */ public static enum CountlyMessagingMode { TEST, PRODUCTION, } private static class SingletonHolder { static final Countly instance = new Countly(); } private ConnectionQueue connectionQueue_; @SuppressWarnings("FieldCanBeLocal") private ScheduledExecutorService timerService_; private EventQueue eventQueue_; private long prevSessionDurationStartTime_; private int activityCount_; private boolean disableUpdateSessionRequests_; private boolean enableLogging_; private Countly.CountlyMessagingMode messagingMode_; private Context context_; //user data access public static UserData userData; //track views private String lastView = null; private int lastViewStart = 0; private boolean firstView = true; private boolean autoViewTracker = false; //overrides private boolean isHttpPostForced = false;//when true, all data sent to the server will be sent using HTTP POST //optional parameters for begin_session call private String optionalParameterCountryCode = null; private String optionalParameterCity = null; private String optionalParameterLocation = null; //app crawlers private boolean shouldIgnoreCrawlers = true;//ignore app crawlers by default private boolean deviceIsAppCrawler = false;//by default assume that device is not a app crawler private List<String> appCrawlerNames = new ArrayList<>(Arrays.asList("Calypso AppCrawler"));//List against which device name is checked to determine if device is app crawler //star rating private CountlyStarRating.RatingCallback starRatingCallback_;// saved callback that is used for automatic star rating //internal flags private boolean calledAtLeastOnceOnStart = false;//flag for if the onStart function has been called at least once /** * Returns the Countly singleton. */ public static Countly sharedInstance() { return SingletonHolder.instance; } /** * Constructs a Countly object. * Creates a new ConnectionQueue and initializes the session timer. */ Countly() { connectionQueue_ = new ConnectionQueue(); Countly.userData = new UserData(connectionQueue_); timerService_ = Executors.newSingleThreadScheduledExecutor(); timerService_.scheduleWithFixedDelay(new Runnable() { @Override public void run() { onTimer(); } }, TIMER_DELAY_IN_SECONDS, TIMER_DELAY_IN_SECONDS, TimeUnit.SECONDS); } public Countly init(final Context context, final String serverURL, final String appKey) { return init(context, serverURL, appKey, null, OpenUDIDAdapter.isOpenUDIDAvailable() ? DeviceId.Type.OPEN_UDID : DeviceId.Type.ADVERTISING_ID); } public Countly init(final Context context, final String serverURL, final String appKey, final String deviceID) { return init(context, serverURL, appKey, deviceID, null); } public synchronized Countly init(final Context context, final String serverURL, final String appKey, final String deviceID, DeviceId.Type idMode) { return init(context, serverURL, appKey, deviceID, idMode, -1, null, null, null, null); } public synchronized Countly init(final Context context, String serverURL, final String appKey, final String deviceID, DeviceId.Type idMode, int starRatingLimit, CountlyStarRating.RatingCallback starRatingCallback, String starRatingTextTitle, String starRatingTextMessage, String starRatingTextDismiss) { if (context == null) { throw new IllegalArgumentException("valid context is required"); } if (!isValidURL(serverURL)) { throw new IllegalArgumentException("valid serverURL is required"); } if (serverURL.charAt(serverURL.length() - 1) == '/') { if (Countly.sharedInstance().isLoggingEnabled()) { Log.i(Countly.TAG, "Removing trailing '/' from provided server url"); } serverURL = serverURL.substring(0, serverURL.length() - 1);//removing trailing '/' from server url } if (appKey == null || appKey.length() == 0) { throw new IllegalArgumentException("valid appKey is required"); } if (deviceID != null && deviceID.length() == 0) { throw new IllegalArgumentException("valid deviceID is required"); } if (deviceID == null && idMode == null) { if (OpenUDIDAdapter.isOpenUDIDAvailable()) idMode = DeviceId.Type.OPEN_UDID; else if (AdvertisingIdAdapter.isAdvertisingIdAvailable()) idMode = DeviceId.Type.ADVERTISING_ID; } if (deviceID == null && idMode == DeviceId.Type.OPEN_UDID && !OpenUDIDAdapter.isOpenUDIDAvailable()) { throw new IllegalArgumentException("valid deviceID is required because OpenUDID is not available"); } if (deviceID == null && idMode == DeviceId.Type.ADVERTISING_ID && !AdvertisingIdAdapter.isAdvertisingIdAvailable()) { throw new IllegalArgumentException("valid deviceID is required because Advertising ID is not available (you need to include Google Play services 4.0+ into your project)"); } if (eventQueue_ != null && (!connectionQueue_.getServerURL().equals(serverURL) || !connectionQueue_.getAppKey().equals(appKey) || !DeviceId.deviceIDEqualsNullSafe(deviceID, idMode, connectionQueue_.getDeviceId()) )) { throw new IllegalStateException("Countly cannot be reinitialized with different values"); } // In some cases CountlyMessaging does some background processing, so it needs a way // to start Countly on itself if (MessagingAdapter.isMessagingAvailable()) { MessagingAdapter.storeConfiguration(context, serverURL, appKey, deviceID, idMode); } //set the star rating values starRatingCallback_ = starRatingCallback; CountlyStarRating.setStarRatingInitConfig(context, starRatingLimit, starRatingTextTitle, starRatingTextMessage, starRatingTextDismiss); //app crawler check checkIfDeviceIsAppCrawler(); // if we get here and eventQueue_ != null, init is being called again with the same values, // so there is nothing to do, because we are already initialized with those values if (eventQueue_ == null) { final CountlyStore countlyStore = new CountlyStore(context); DeviceId deviceIdInstance; if (deviceID != null) { deviceIdInstance = new DeviceId(countlyStore, deviceID); } else { deviceIdInstance = new DeviceId(countlyStore, idMode); } deviceIdInstance.init(context, countlyStore, true); connectionQueue_.setServerURL(serverURL); connectionQueue_.setAppKey(appKey); connectionQueue_.setCountlyStore(countlyStore); connectionQueue_.setDeviceId(deviceIdInstance); eventQueue_ = new EventQueue(countlyStore); //do star rating related things CountlyStarRating.registerAppSession(context, starRatingCallback_); } context_ = context; // context is allowed to be changed on the second init call connectionQueue_.setContext(context); return this; } /** * Checks whether Countly.init has been already called. * @return true if Countly is ready to use */ public synchronized boolean isInitialized() { return eventQueue_ != null; } public Countly initMessaging(Activity activity, Class<? extends Activity> activityClass, String projectID, Countly.CountlyMessagingMode mode) { return initMessaging(activity, activityClass, projectID, null, mode, false); } public Countly initMessaging(Activity activity, Class<? extends Activity> activityClass, String projectID, Countly.CountlyMessagingMode mode, boolean disableUI) { return initMessaging(activity, activityClass, projectID, null, mode, disableUI); } public synchronized Countly initMessaging(Activity activity, Class<? extends Activity> activityClass, String projectID, String[] buttonNames, Countly.CountlyMessagingMode mode) { return initMessaging(activity, activityClass, projectID, null, mode, false); } public synchronized Countly initMessaging(Activity activity, Class<? extends Activity> activityClass, String projectID, String[] buttonNames, Countly.CountlyMessagingMode mode, boolean disableUI) { if (mode != null && !MessagingAdapter.isMessagingAvailable()) { throw new IllegalStateException("you need to include countly-messaging-sdk-android library instead of countly-sdk-android if you want to use Countly Messaging"); } else { messagingMode_ = mode; if (!MessagingAdapter.init(activity, activityClass, projectID, buttonNames, disableUI)) { throw new IllegalStateException("couldn't initialize Countly Messaging"); } } if (MessagingAdapter.isMessagingAvailable()) { MessagingAdapter.storeConfiguration(connectionQueue_.getContext(), connectionQueue_.getServerURL(), connectionQueue_.getAppKey(), connectionQueue_.getDeviceId().getId(), connectionQueue_.getDeviceId().getType()); } return this; } public synchronized void halt() { eventQueue_ = null; final CountlyStore countlyStore = connectionQueue_.getCountlyStore(); if (countlyStore != null) { countlyStore.clear(); } connectionQueue_.setContext(null); connectionQueue_.setServerURL(null); connectionQueue_.setAppKey(null); connectionQueue_.setCountlyStore(null); prevSessionDurationStartTime_ = 0; activityCount_ = 0; } public synchronized void onStart(Activity activity) { appLaunchDeepLink = false; if (eventQueue_ == null) { throw new IllegalStateException("init must be called before onStart"); } ++activityCount_; if (activityCount_ == 1) { onStartHelper(); } //check if there is an install referrer data String referrer = ReferrerReceiver.getReferrer(context_); if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Checking referrer: " + referrer); } if(referrer != null){ connectionQueue_.sendReferrerData(referrer); ReferrerReceiver.deleteReferrer(context_); } CrashDetails.inForeground(); if(autoViewTracker){ recordView(activity.getClass().getName()); } calledAtLeastOnceOnStart = true; } /** * Called when the first Activity is started. Sends a begin session event to the server * and initializes application session tracking. */ void onStartHelper() { prevSessionDurationStartTime_ = System.nanoTime(); connectionQueue_.beginSession(); } public synchronized void onStop() { if (eventQueue_ == null) { throw new IllegalStateException("init must be called before onStop"); } if (activityCount_ == 0) { throw new IllegalStateException("must call onStart before onStop"); } --activityCount_; if (activityCount_ == 0) { onStopHelper(); } CrashDetails.inBackground(); //report current view duration reportViewDuration(); } /** * Called when final Activity is stopped. Sends an end session event to the server, * also sends any unsent custom events. */ void onStopHelper() { connectionQueue_.endSession(roundedSecondsSinceLastSessionDurationUpdate()); prevSessionDurationStartTime_ = 0; if (eventQueue_.size() > 0) { connectionQueue_.recordEvents(eventQueue_.events()); } } /** * Called when GCM Registration ID is received. Sends a token session event to the server. */ public void onRegistrationId(String registrationId) { connectionQueue_.tokenSession(registrationId, messagingMode_); } /** * DON'T USE THIS!!!! */ public void onRegistrationId(String registrationId, CountlyMessagingMode mode) { connectionQueue_.tokenSession(registrationId, mode); } /** * Changes current device id type to the one specified in parameter. Closes current session and * reopens new one with new id. Doesn't merge user profiles on the server * @param type Device ID type to change to * @param deviceId Optional device ID for a case when type = DEVELOPER_SPECIFIED */ public void changeDeviceId(DeviceId.Type type, String deviceId) { if (eventQueue_ == null) { throw new IllegalStateException("init must be called before changeDeviceId"); } if (activityCount_ == 0) { throw new IllegalStateException("must call onStart before changeDeviceId"); } if (type == null) { throw new IllegalStateException("type cannot be null"); } connectionQueue_.endSession(roundedSecondsSinceLastSessionDurationUpdate(), connectionQueue_.getDeviceId().getId()); connectionQueue_.getDeviceId().changeToId(context_, connectionQueue_.getCountlyStore(), type, deviceId); connectionQueue_.beginSession(); } /** * Changes current device id to the one specified in parameter. Merges user profile with new id * (if any) with old profile. * @param deviceId new device id */ public void changeDeviceId(String deviceId) { if (eventQueue_ == null) { throw new IllegalStateException("init must be called before changeDeviceId"); } if (activityCount_ == 0) { throw new IllegalStateException("must call onStart before changeDeviceId"); } if (deviceId == null || "".equals(deviceId)) { throw new IllegalStateException("deviceId cannot be null or empty"); } connectionQueue_.changeDeviceId(deviceId, roundedSecondsSinceLastSessionDurationUpdate()); } public void recordEvent(final String key) { recordEvent(key, null, 1, 0); } public void recordEvent(final String key, final int count) { recordEvent(key, null, count, 0); } public void recordEvent(final String key, final int count, final double sum) { recordEvent(key, null, count, sum); } public void recordEvent(final String key, final Map<String, String> segmentation, final int count) { recordEvent(key, segmentation, count, 0); } public synchronized void recordEvent(final String key, final Map<String, String> segmentation, final int count, final double sum) { recordEvent(key, segmentation, count, sum, 0); } public synchronized void recordEvent(final String key, final Map<String, String> segmentation, final int count, final double sum, final double dur) { if (!isInitialized()) { throw new IllegalStateException("Countly.sharedInstance().init must be called before recordEvent"); } if (key == null || key.length() == 0) { throw new IllegalArgumentException("Valid Countly event key is required"); } if (count < 1) { throw new IllegalArgumentException("Countly event count should be greater than zero"); } if (segmentation != null) { for (String k : segmentation.keySet()) { if (k == null || k.length() == 0) { throw new IllegalArgumentException("Countly event segmentation key cannot be null or empty"); } if (segmentation.get(k) == null || segmentation.get(k).length() == 0) { throw new IllegalArgumentException("Countly event segmentation value cannot be null or empty"); } } } eventQueue_.recordEvent(key, segmentation, count, sum, dur); sendEventsIfNeeded(); } /** * Enable or disable automatic view tracking * @param enable boolean for the state of automatic view tracking */ public synchronized Countly setViewTracking(boolean enable){ autoViewTracker = enable; return this; } /** * Check state of automatic view tracking * @return boolean - true if enabled, false if disabled */ public synchronized boolean isViewTrackingEnabled(){ return autoViewTracker; } /** * Record a view manualy, without automatic tracking * or track view that is not automatically tracked * like fragment, Message box or transparent Activity * @param viewName String - name of the view */ public synchronized Countly recordView(String viewName){ reportViewDuration(); lastView = viewName; lastViewStart = Countly.currentTimestamp(); HashMap<String, String> segments = new HashMap<String, String>(); segments.put("name", viewName); segments.put("visit", "1"); segments.put("segment", "Android"); if(firstView) { firstView = false; segments.put("start", "1"); } recordEvent("[CLY]_view", segments, 1); return this; } /** * Sets information about user. Possible keys are: * <ul> * <li> * name - (String) providing user's full name * </li> * <li> * username - (String) providing user's nickname * </li> * <li> * email - (String) providing user's email address * </li> * <li> * organization - (String) providing user's organization's name where user works * </li> * <li> * phone - (String) providing user's phone number * </li> * <li> * picture - (String) providing WWW URL to user's avatar or profile picture * </li> * <li> * picturePath - (String) providing local path to user's avatar or profile picture * </li> * <li> * gender - (String) providing user's gender as M for male and F for female * </li> * <li> * byear - (int) providing user's year of birth as integer * </li> * </ul> * @param data Map&lt;String, String&gt; with user data * @deprecated use {@link UserData#setUserData(Map)} to set data and {@link UserData#save()} to send it to server. */ public synchronized Countly setUserData(Map<String, String> data) { return setUserData(data, null); } /** * Sets information about user with custom properties. * In custom properties you can provide any string key values to be stored with user * Possible keys are: * <ul> * <li> * name - (String) providing user's full name * </li> * <li> * username - (String) providing user's nickname * </li> * <li> * email - (String) providing user's email address * </li> * <li> * organization - (String) providing user's organization's name where user works * </li> * <li> * phone - (String) providing user's phone number * </li> * <li> * picture - (String) providing WWW URL to user's avatar or profile picture * </li> * <li> * picturePath - (String) providing local path to user's avatar or profile picture * </li> * <li> * gender - (String) providing user's gender as M for male and F for female * </li> * <li> * byear - (int) providing user's year of birth as integer * </li> * </ul> * @param data Map&lt;String, String&gt; with user data * @param customdata Map&lt;String, String&gt; with custom key values for this user * @deprecated use {@link UserData#setUserData(Map, Map)} to set data and {@link UserData#save()} to send it to server. */ public synchronized Countly setUserData(Map<String, String> data, Map<String, String> customdata) { UserData.setData(data); if(customdata != null) UserData.setCustomData(customdata); connectionQueue_.sendUserData(); UserData.clear(); return this; } /** * Sets custom properties. * In custom properties you can provide any string key values to be stored with user * @param customdata Map&lt;String, String&gt; with custom key values for this user * @deprecated use {@link UserData#setCustomUserData(Map)} to set data and {@link UserData#save()} to send it to server. */ public synchronized Countly setCustomUserData(Map<String, String> customdata) { if(customdata != null) UserData.setCustomData(customdata); connectionQueue_.sendUserData(); UserData.clear(); return this; } /** * Set user location. * * Countly detects user location based on IP address. But for geolocation-enabled apps, * it's better to supply exact location of user. * Allows sending messages to a custom segment of users located in a particular area. * * @param lat Latitude * @param lon Longitude */ public synchronized Countly setLocation(double lat, double lon) { connectionQueue_.getCountlyStore().setLocation(lat, lon); if (disableUpdateSessionRequests_) { connectionQueue_.updateSession(roundedSecondsSinceLastSessionDurationUpdate()); } return this; } /** * Sets custom segments to be reported with crash reports * In custom segments you can provide any string key values to segments crashes by * @param segments Map&lt;String, String&gt; key segments and their values */ public synchronized Countly setCustomCrashSegments(Map<String, String> segments) { if(segments != null) CrashDetails.setCustomSegments(segments); return this; } /** * Add crash breadcrumb like log record to the log that will be send together with crash report * @param record String a bread crumb for the crash report */ public synchronized Countly addCrashLog(String record) { CrashDetails.addLog(record); return this; } /** * Log handled exception to report it to server as non fatal crash * @param exception Exception to log */ public synchronized Countly logException(Exception exception) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); exception.printStackTrace(pw); connectionQueue_.sendCrashReport(sw.toString(), true); return this; } /** * Enable crash reporting to send unhandled crash reports to server */ public synchronized Countly enableCrashReporting() { //get default handler final Thread.UncaughtExceptionHandler oldHandler = Thread.getDefaultUncaughtExceptionHandler(); Thread.UncaughtExceptionHandler handler = new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(Thread t, Throwable e) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); Countly.sharedInstance().connectionQueue_.sendCrashReport(sw.toString(), false); //if there was another handler before if(oldHandler != null){ //notify it also oldHandler.uncaughtException(t,e); } } }; Thread.setDefaultUncaughtExceptionHandler(handler); return this; } /** * Start timed event with a specified key * @param key name of the custom event, required, must not be the empty string or null * @return true if no event with this key existed before and event is started, false otherwise */ public synchronized boolean startEvent(final String key) { if (!isInitialized()) { throw new IllegalStateException("Countly.sharedInstance().init must be called before recordEvent"); } if (key == null || key.length() == 0) { throw new IllegalArgumentException("Valid Countly event key is required"); } if (timedEvents.containsKey(key)) { return false; } timedEvents.put(key, new Event(key)); return true; } /** * End timed event with a specified key * @param key name of the custom event, required, must not be the empty string or null * @return true if event with this key has been previously started, false otherwise */ public synchronized boolean endEvent(final String key) { return endEvent(key, null, 1, 0); } public synchronized boolean endEvent(final String key, final Map<String, String> segmentation, final int count, final double sum) { Event event = timedEvents.remove(key); if (event != null) { if (!isInitialized()) { throw new IllegalStateException("Countly.sharedInstance().init must be called before recordEvent"); } if (key == null || key.length() == 0) { throw new IllegalArgumentException("Valid Countly event key is required"); } if (count < 1) { throw new IllegalArgumentException("Countly event count should be greater than zero"); } if (segmentation != null) { for (String k : segmentation.keySet()) { if (k == null || k.length() == 0) { throw new IllegalArgumentException("Countly event segmentation key cannot be null or empty"); } if (segmentation.get(k) == null || segmentation.get(k).length() == 0) { throw new IllegalArgumentException("Countly event segmentation value cannot be null or empty"); } } } long currentTimestamp = Countly.currentTimestampMs(); event.segmentation = segmentation; event.dur = (currentTimestamp - event.timestamp) / 1000.0; event.count = count; event.sum = sum; eventQueue_.recordEvent(event); sendEventsIfNeeded(); return true; } else { return false; } } /** * Disable periodic session time updates. * By default, Countly will send a request to the server each 30 seconds with a small update * containing session duration time. This method allows you to disable such behavior. * Note that event updates will still be sent every 10 events or 30 seconds after event recording. * @param disable whether or not to disable session time updates * @return Countly instance for easy method chaining */ public synchronized Countly setDisableUpdateSessionRequests(final boolean disable) { disableUpdateSessionRequests_ = disable; return this; } /** * Sets whether debug logging is turned on or off. Logging is disabled by default. * @param enableLogging true to enable logging, false to disable logging * @return Countly instance for easy method chaining */ public synchronized Countly setLoggingEnabled(final boolean enableLogging) { enableLogging_ = enableLogging; return this; } public synchronized boolean isLoggingEnabled() { return enableLogging_; } public synchronized Countly enableParameterTamperingProtection(String salt) { ConnectionProcessor.salt = salt; return this; } /** * Returns if the countly sdk onStart function has been called at least once * @return true - yes, it has, false - no it has not */ public synchronized boolean hasBeenCalledOnStart() { return calledAtLeastOnceOnStart; } public synchronized Countly setEventQueueSizeToSend(int size) { EVENT_QUEUE_SIZE_THRESHOLD = size; return this; } private boolean appLaunchDeepLink = true; public static void onCreate(Activity activity) { Intent launchIntent = activity.getPackageManager().getLaunchIntentForPackage(activity.getPackageName()); if (sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Activity created: " + activity.getClass().getName() + " ( main is " + launchIntent.getComponent().getClassName() + ")"); } Intent intent = activity.getIntent(); if (intent != null) { Uri data = intent.getData(); if (data != null) { if (sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Data in activity created intent: " + data + " (appLaunchDeepLink " + sharedInstance().appLaunchDeepLink + ") " ); } if (sharedInstance().appLaunchDeepLink) { DeviceInfo.deepLink = data.toString(); } } } } /** * Reports duration of last view */ void reportViewDuration(){ if(lastView != null && lastViewStart <= 0) { if (Countly.sharedInstance().isLoggingEnabled()) { Log.e(Countly.TAG, "Last view start value is not normal: [" + lastViewStart + "]"); } } //only record view if the view name is not null and if it has a reasonable duration //if the lastViewStart is equal to 0, the duration would be set to the current timestamp //and therefore will be ignored if(lastView != null && lastViewStart > 0){ HashMap<String, String> segments = new HashMap<String, String>(); segments.put("name", lastView); segments.put("dur", String.valueOf(Countly.currentTimestamp()-lastViewStart)); segments.put("segment", "Android"); recordEvent("[CLY]_view",segments,1); lastView = null; lastViewStart = 0; } } /** * Submits all of the locally queued events to the server if there are more than 10 of them. */ void sendEventsIfNeeded() { if (eventQueue_.size() >= EVENT_QUEUE_SIZE_THRESHOLD) { connectionQueue_.recordEvents(eventQueue_.events()); } } /** * Called every 60 seconds to send a session heartbeat to the server. Does nothing if there * is not an active application session. */ synchronized void onTimer() { final boolean hasActiveSession = activityCount_ > 0; if (hasActiveSession) { if (!disableUpdateSessionRequests_) { connectionQueue_.updateSession(roundedSecondsSinceLastSessionDurationUpdate()); } if (eventQueue_.size() > 0) { connectionQueue_.recordEvents(eventQueue_.events()); } } } /** * Calculates the unsent session duration in seconds, rounded to the nearest int. */ int roundedSecondsSinceLastSessionDurationUpdate() { final long currentTimestampInNanoseconds = System.nanoTime(); final long unsentSessionLengthInNanoseconds = currentTimestampInNanoseconds - prevSessionDurationStartTime_; prevSessionDurationStartTime_ = currentTimestampInNanoseconds; return (int) Math.round(unsentSessionLengthInNanoseconds / 1000000000.0d); } /** * Utility method to return a current timestamp that can be used in the Count.ly API. */ static int currentTimestamp() { return ((int)(System.currentTimeMillis() / 1000l)); } private static long lastTsMs; static synchronized long currentTimestampMs() { long ms = System.currentTimeMillis(); while (lastTsMs >= ms) { ms += 1; } lastTsMs = ms; return ms; } /** * Utility method to return a current hour of the day that can be used in the Count.ly API. */ static int currentHour(){return Calendar.getInstance().get(Calendar.HOUR_OF_DAY); } /** * Utility method to return a current day of the week that can be used in the Count.ly API. */ static int currentDayOfWeek(){ int day = Calendar.getInstance().get(Calendar.DAY_OF_WEEK); switch (day) { case Calendar.MONDAY: return 1; case Calendar.TUESDAY: return 2; case Calendar.WEDNESDAY: return 3; case Calendar.THURSDAY: return 4; case Calendar.FRIDAY: return 5; case Calendar.SATURDAY: return 6; } return 0; } /** * Utility method for testing validity of a URL. */ static boolean isValidURL(final String urlStr) { boolean validURL = false; if (urlStr != null && urlStr.length() > 0) { try { new URL(urlStr); validURL = true; } catch (MalformedURLException e) { validURL = false; } } return validURL; } public static Countly enablePublicKeyPinning(List<String> certificates) { publicKeyPinCertificates = certificates; return Countly.sharedInstance(); } public static Countly enableCertificatePinning(List<String> certificates) { certificatePinCertificates = certificates; return Countly.sharedInstance(); } /** * Shows the star rating dialog * @param activity the activity that will own the dialog * @param callback callback for the star rating dialog "rate" and "dismiss" events */ public void showStarRating(Activity activity, CountlyStarRating.RatingCallback callback){ CountlyStarRating.showStarRating(activity, callback); } /** * Set's the text's for the different fields in the star rating dialog. Set value null if for some field you want to keep the old value * @param starRatingTextTitle dialog's title text * @param starRatingTextMessage dialog's message text * @param starRatingTextDismiss dialog's dismiss buttons text */ public void setStarRatingDialogTexts(String starRatingTextTitle, String starRatingTextMessage, String starRatingTextDismiss) { if(context_ == null) { if (Countly.sharedInstance().isLoggingEnabled()) { Log.e(Countly.TAG, "Can't call this function before init has been called"); return; } } CountlyStarRating.setStarRatingInitConfig(context_, -1, starRatingTextTitle, starRatingTextMessage, starRatingTextDismiss); } /** * Set if the star rating * @param IsShownAutomatically set it true if you want to show the app star rating dialog automatically for each new version after the specified session amount */ public void setIfStarRatingShownAutomatically(boolean IsShownAutomatically) { if(context_ == null) { if (Countly.sharedInstance().isLoggingEnabled()) { Log.e(Countly.TAG, "Can't call this function before init has been called"); return; } } CountlyStarRating.setShowDialogAutomatically(context_, IsShownAutomatically); } /** * Set if the star rating is shown only once per app lifetime * @param disableAsking set true if you want to disable asking the app rating for each new app version (show it only once per apps lifetime) */ public void setStarRatingDisableAskingForEachAppVersion(boolean disableAsking) { if(context_ == null) { if (Countly.sharedInstance().isLoggingEnabled()) { Log.e(Countly.TAG, "Can't call this function before init has been called"); return; } } CountlyStarRating.setShowDialogAutomatically(context_, disableAsking); } /** * Set after how many sessions the automatic star rating will be shown for each app version * @param limit app session amount for the limit */ public void setAutomaticStarRatingSessionLimit(int limit) { if(context_ == null) { if (Countly.sharedInstance().isLoggingEnabled()) { Log.e(Countly.TAG, "Can't call this function before init has been called"); return; } } CountlyStarRating.setStarRatingInitConfig(context_, limit, null, null, null); } /** * Set the override for forcing to use HTTP POST for all connections to the server * @param isItForced the flag for the new status, set "true" if you want it to be forced */ public void setHttpPostForced(boolean isItForced) { isHttpPostForced = isItForced; } /** * Get the status of the override for HTTP POST * @return return "true" if HTTP POST ir forced */ public boolean isHttpPostForced() { return isHttpPostForced; } /** * Set optional parameters that are added to all begin_session requests * @param country_code ISO Country code for the user's country * @param city Name of the user's city * @param location comma separate lat and lng values. For example, "56.42345,123.45325" */ public void setOptionalParametersForInitialization(String country_code, String city, String location){ optionalParameterCountryCode = country_code; optionalParameterCity = city; optionalParameterLocation = location; } public String getOptionalParameterCountryCode() { return optionalParameterCountryCode; } public String getOptionalParameterCity() { return optionalParameterCity; } public String getOptionalParameterLocation() { return optionalParameterLocation; } private void checkIfDeviceIsAppCrawler(){ String deviceName = DeviceInfo.getDevice(); for(int a = 0 ; a < appCrawlerNames.size() ; a++) { if(deviceName.equals(appCrawlerNames.get(a))){ deviceIsAppCrawler = true; return; } } } /** * Set if Countly SDK should ignore app crawlers * @param shouldIgnore if crawlers should be ignored */ public void setShouldIgnoreCrawlers(boolean shouldIgnore){ shouldIgnoreCrawlers = shouldIgnore; } /** * Add app crawler device name to the list of names that should be ignored * @param crawlerName the name to be ignored */ public void addAppCrawlerName(String crawlerName) { if(crawlerName != null && !crawlerName.isEmpty()) { appCrawlerNames.add(crawlerName); } } /** * Return if current device is detected as a app crawler * @return returns if devices is detected as a app crawler */ public boolean isDeviceAppCrawler() { return deviceIsAppCrawler; } /** * Return if the countly sdk should ignore app crawlers * @return */ public boolean ifShouldIgnoreCrawlers(){ return shouldIgnoreCrawlers; } /** * Returns the device id used by countly for this device * @return device ID */ public String getDeviceID() { if(!isInitialized()) { throw new IllegalStateException("init must be called before getDeviceID"); } return connectionQueue_.getDeviceId().getId(); } /** * Returns the type of the device ID used by countly for this decice. * @return device ID type */ public DeviceId.Type getDeviceIDType(){ if(!isInitialized()) { throw new IllegalStateException("init must be called before getDeviceID"); } return connectionQueue_.getDeviceId().getType(); } // for unit testing ConnectionQueue getConnectionQueue() { return connectionQueue_; } void setConnectionQueue(final ConnectionQueue connectionQueue) { connectionQueue_ = connectionQueue; } ExecutorService getTimerService() { return timerService_; } EventQueue getEventQueue() { return eventQueue_; } void setEventQueue(final EventQueue eventQueue) { eventQueue_ = eventQueue; } long getPrevSessionDurationStartTime() { return prevSessionDurationStartTime_; } void setPrevSessionDurationStartTime(final long prevSessionDurationStartTime) { prevSessionDurationStartTime_ = prevSessionDurationStartTime; } int getActivityCount() { return activityCount_; } synchronized boolean getDisableUpdateSessionRequests() { return disableUpdateSessionRequests_; } public void stackOverflow() { this.stackOverflow(); } public synchronized Countly crashTest(int crashNumber) { if (crashNumber == 1){ if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Running crashTest 1"); } stackOverflow(); }else if (crashNumber == 2){ if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Running crashTest 2"); } int test = 10/0; }else if (crashNumber == 3){ if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Running crashTest 3"); } Object[] o = null; while (true) { o = new Object[] { o }; } }else if (crashNumber == 4){ if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Running crashTest 4"); } throw new RuntimeException("This is a crash"); } else{ if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Running crashTest 5"); } String test = null; test.charAt(1); } return Countly.sharedInstance(); } }
package com.exedio.cope; import java.io.File; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Set; import com.exedio.cope.util.CacheInfo; import com.exedio.cope.util.CacheQueryInfo; import com.exedio.cope.util.ConnectionPoolInfo; import com.exedio.dsmf.SQLRuntimeException; import com.exedio.dsmf.Schema; public final class Model { private final Type<Item>[] types; private final Type<Item>[] concreteTypes; final int concreteTypeCount; private final List<Type<Item>> typeList; private final List<Type<Item>> concreteTypeList; private final HashMap<String, Type> typesByID = new HashMap<String, Type>(); // set by setPropertiesInitially private Properties properties; private Object propertiesLock = new Object(); private Database database; private Cache cache; private final ThreadLocal<Transaction> transactionThreads = new ThreadLocal<Transaction>(); private final Set<Transaction> openTransactions = Collections.synchronizedSet(new HashSet<Transaction>()); public Model(final Type[] types) { this.types = castTypeArray(types); this.typeList = Collections.unmodifiableList(Arrays.asList(this.types)); int concreteTypeCount = 0; int abstractTypeCount = -1; final ArrayList<Type<Item>> concreteTypes = new ArrayList<Type<Item>>(); for(final Type<Item> type : this.types) { final boolean isAbstract = type.isAbstract(); type.initialize(this, isAbstract ? abstractTypeCount-- : concreteTypeCount++); if(!isAbstract) concreteTypes.add(type); } this.concreteTypeCount = concreteTypeCount; this.concreteTypes = castTypeArray(concreteTypes.toArray(new Type[concreteTypeCount])); this.concreteTypeList = Collections.unmodifiableList(Arrays.asList(this.concreteTypes)); assert this.concreteTypeCount==this.concreteTypes.length; } @SuppressWarnings("unchecked") // OK: no generic array creation private static final Type<Item>[] castTypeArray(final Type[] ts) { return (Type<Item>[])ts; } /** * Initially sets the properties for this model. * Can be called multiple times, but only the first time * takes effect. * Any subsequent calls must give properties equal to properties given * on the first call, otherwise a RuntimeException is thrown. * <p> * Usually you may want to use this method, if you want to initialize model * from different servlets with equal properties in an undefined order. * * @throws RuntimeException if a subsequent call provides properties different * to the first call. */ public void setPropertiesInitially(final Properties properties) { if(properties==null) throw new NullPointerException(); synchronized(propertiesLock) { if(this.properties==null) { if(this.database!=null) throw new RuntimeException(); this.properties = properties; this.database = properties.createDatabase(); final HashSet<Type> typeSet = new HashSet<Type>(Arrays.asList(types)); final HashSet<Type> materialized = new HashSet<Type>(); for(int i = 0; i<types.length; i++) { final ArrayList<Type> stack = new ArrayList<Type>(); for(Type type = types[i]; type!=null; type=type.getSupertype()) { if(!typeSet.contains(type)) throw new RuntimeException("type "+type.id+ " is supertype of " + types[i].id + " but not part of the model"); stack.add(type); } for(ListIterator<Type> j = stack.listIterator(stack.size()); j.hasPrevious(); ) { final Type type = j.previous(); if(!materialized.contains(type)) { type.materialize(database); if(typesByID.put(type.id, type)!=null) throw new RuntimeException(type.id); materialized.add(type); } } } if(!materialized.equals(typeSet)) throw new RuntimeException(materialized.toString()+"<->"+typeSet.toString()); final int[] cacheMapSizeLimits = new int[concreteTypeCount]; final int cacheMapSizeLimit = properties.getCacheLimit() / concreteTypeCount; Arrays.fill(cacheMapSizeLimits, cacheMapSizeLimit); final Properties p = getProperties(); this.cache = new Cache(cacheMapSizeLimits, p.getCacheQueryLimit(), p.getCacheQueryLogging()); return; } } // can be done outside the synchronized block this.properties.ensureEquality(properties); } public List<Type<Item>> getTypes() { return typeList; } public List<Type<Item>> getConcreteTypes() { return concreteTypeList; } public Type findTypeByID(final String id) { if(this.properties==null) throw newNotInitializedException(); return typesByID.get(id); } private RuntimeException newNotInitializedException() { throw new RuntimeException("model not yet initialized, use setPropertiesInitially"); } public Properties getProperties() { if(properties==null) throw newNotInitializedException(); return properties; } public boolean supportsCheckConstraints() { return database.supportsCheckConstraints(); } /** * Returns, whether the database can store empty strings. * <p> * If true, an empty string can be stored into a {@link StringAttribute} * like any other string via {@link FunctionAttribute#set(Item,Object)}. * A subsequent retrieval of that string via {@link FunctionAttribute#get(Item)} * returns an empty string. * If false, an empty string stored into a {@link StringAttribute} is * converted to null, thus a subsequent retrieval of that string returns * null. * <p> * Up to now, only Oracle does not support empty strings. */ public boolean supportsEmptyStrings() { return !getProperties().getDatabaseDontSupportEmptyStrings() && database.supportsEmptyStrings(); } public boolean supportsRightOuterJoins() { return database.supportsRightOuterJoins(); } Database getDatabase() { if(database==null) throw newNotInitializedException(); return database; } /** * @return the listener previously registered for this model */ DatabaseListener setDatabaseListener(final DatabaseListener listener) { return database.setListener(listener); } public void createDatabase() { for(int i = 0; i<types.length; i++) createDataDirectories(types[i]); database.createDatabase(); clearCache(); } public void createDatabaseConstraints() { database.createDatabaseConstraints(); } private void createDataDirectories(final Type type) { File typeDirectory = null; for(Iterator i = type.getAttributes().iterator(); i.hasNext(); ) { final Attribute attribute = (Attribute)i.next(); if((attribute instanceof DataAttribute) && !((DataAttribute)attribute).impl.blob) { if(typeDirectory==null) { final File directory = properties.getDatadirPath(); typeDirectory = new File(directory, type.id); typeDirectory.mkdir(); } final File attributeDirectory = new File(typeDirectory, attribute.getName()); attributeDirectory.mkdir(); } } } private void dropDataDirectories(final Type type) { File typeDirectory = null; for(Iterator i = type.getAttributes().iterator(); i.hasNext(); ) { final Attribute attribute = (Attribute)i.next(); if(attribute instanceof DataAttribute && !((DataAttribute)attribute).impl.blob) { if(typeDirectory==null) { final File directory = properties.getDatadirPath(); typeDirectory = new File(directory, type.id); } final File attributeDirectory = new File(typeDirectory, attribute.getName()); final File[] files = attributeDirectory.listFiles(); for(int j = 0; j<files.length; j++) { final File file = files[j]; if(!file.delete()) throw new RuntimeException("delete failed: "+file.getAbsolutePath()); } if(!attributeDirectory.delete()) throw new RuntimeException("delete failed: "+attributeDirectory.getAbsolutePath()); } } if(typeDirectory!=null) { if(!typeDirectory.delete()) throw new RuntimeException("delete failed: "+typeDirectory.getAbsolutePath()); } } private void tearDownDataDirectories(final Type type) { File typeDirectory = null; for(Iterator i = type.getAttributes().iterator(); i.hasNext(); ) { final Attribute attribute = (Attribute)i.next(); if(attribute instanceof DataAttribute && !((DataAttribute)attribute).impl.blob) { if(typeDirectory==null) { final File directory = properties.getDatadirPath(); typeDirectory = new File(directory, type.id); } final File attributeDirectory = new File(typeDirectory, attribute.getName()); if(attributeDirectory.exists()) { final File[] files = attributeDirectory.listFiles(); for(int j = 0; j<files.length; j++) files[j].delete(); attributeDirectory.delete(); } } } if(typeDirectory!=null) typeDirectory.delete(); } public void checkDatabase() { // TODO: check for data attribute directories database.checkDatabase(getCurrentTransaction().getConnection()); } public void checkEmptyDatabase() { database.checkEmptyDatabase(getCurrentTransaction().getConnection()); } public void dropDatabase() { // TODO: rework this method final List<Type<Item>> types = typeList; for(ListIterator<Type<Item>> i = types.listIterator(types.size()); i.hasPrevious(); ) i.previous().onDropTable(); database.dropDatabase(); for(int i = 0; i<this.types.length; i++) dropDataDirectories(this.types[i]); clearCache(); } public void dropDatabaseConstraints() { database.dropDatabaseConstraints(); } public void tearDownDatabase() { database.tearDownDatabase(); for(int i = 0; i<this.types.length; i++) tearDownDataDirectories(this.types[i]); clearCache(); } public void tearDownDatabaseConstraints() { database.tearDownDatabaseConstraints(); } public void close() { database.getConnectionPool().flush(); } public Schema getVerifiedSchema() { // TODO: check data directories return database.makeVerifiedSchema(); } public Schema getSchema() { return database.makeSchema(); } /** * Returns the item with the given ID. * Always returns {@link Item#activeCopeItem() active} objects. * @see Item#getCopeID() * @throws NoSuchIDException if there is no item with the given id. */ public Item findByID(final String id) throws NoSuchIDException { final int pos = id.lastIndexOf('.'); if(pos<=0) throw new NoSuchIDException(id, true, "no dot in id"); final String typeID = id.substring(0, pos); final Type type = findTypeByID(typeID); if(type==null) throw new NoSuchIDException(id, true, "type <" + typeID + "> does not exist"); if(type.isAbstract()) throw new NoSuchIDException(id, true, "type is abstract"); final String idString = id.substring(pos+1); final long idNumber; try { idNumber = Long.parseLong(idString); } catch(NumberFormatException e) { throw new NoSuchIDException(id, e, idString); } final int pk = type.getPkSource().id2pk(idNumber, id); final Item result = type.getItemObject(pk); if ( ! result.existsCopeItem() ) { throw new NoSuchIDException(id, false, "item <"+idNumber+"> does not exist"); } return result; } public CacheInfo[] getCacheInfo() { if(cache==null) throw newNotInitializedException(); return cache.getInfo(concreteTypes); } public int[] getCacheQueryInfo() { if(cache==null) throw newNotInitializedException(); return cache.getQueryInfo(); } public CacheQueryInfo[] getCacheQueryHistogram() { if(cache==null) throw newNotInitializedException(); return cache.getQueryHistogram(); } public ConnectionPoolInfo getConnectionPoolInfo() { if(database==null) throw newNotInitializedException(); return database.getConnectionPool().getInfo(); } public java.util.Properties getDatabaseInfo() { if(database==null) throw newNotInitializedException(); final ConnectionPool cp = database.getConnectionPool(); Connection c = null; try { c = cp.getConnection(); final DatabaseMetaData dmd = c.getMetaData(); final java.util.Properties result = new java.util.Properties(); result.setProperty("database.name", dmd.getDatabaseProductName()); result.setProperty("database.version", dmd.getDatabaseProductVersion() + ' ' + '(' + dmd.getDatabaseMajorVersion() + '.' + dmd.getDatabaseMinorVersion() + ')'); result.setProperty("driver.name", dmd.getDriverName()); result.setProperty("driver.version", dmd.getDriverVersion() + ' ' + '(' + dmd.getDriverMajorVersion() + '.' + dmd.getDriverMinorVersion() + ')'); return result; } catch(SQLException e) { throw new SQLRuntimeException(e, "getMetaData"); } finally { try { if(c!=null) cp.putConnection(c); } catch(SQLException e) { // ooops } } } public Transaction startTransaction() { return startTransaction(null); } /** * @param name * a name for the transaction, useful for debugging. * This name is used in {@link Transaction#toString()}. * @throws RuntimeException * if there is already a transaction bound * to the current thread for this model */ public Transaction startTransaction(final String name) { if(database==null) throw newNotInitializedException(); if( hasCurrentTransaction() ) throw new RuntimeException("there is already a transaction bound to current thread"); final Transaction result = new Transaction(this, name); setTransaction( result ); openTransactions.add( result ); return result; } public Transaction leaveTransaction() { Transaction tx = getCurrentTransaction(); tx.unbindThread(); setTransaction( null ); return tx; } public void joinTransaction( Transaction tx ) { if ( hasCurrentTransaction() ) throw new RuntimeException("there is already a transaction bound to current thread"); setTransaction(tx); } public boolean hasCurrentTransaction() { return getCurrentTransactionIfAvailable()!=null; } /** * Returns the transaction for this model, * that is bound to the currently running thread. * @see Thread#currentThread() */ public Transaction getCurrentTransaction() { final Transaction result = getCurrentTransactionIfAvailable(); if(result==null) { throw new RuntimeException("there is no cope transaction bound to this thread, see Model#startTransaction"); } return result; } private Transaction getCurrentTransactionIfAvailable() { final Transaction result = transactionThreads.get(); if( result!=null ) { result.assertBoundToCurrentThread(); } return result; } private void setTransaction(final Transaction transaction) { if(transaction!=null) { transaction.bindToCurrentThread(); } transactionThreads.set(transaction); } public void rollback() { Transaction tx = getCurrentTransaction(); openTransactions.remove( tx ); tx.rollbackInternal(); setTransaction(null); } public void rollbackIfNotCommitted() { final Transaction t = getCurrentTransactionIfAvailable(); if( t!=null ) { rollback(); } } public void commit() { Transaction tx = getCurrentTransaction(); openTransactions.remove( tx ); tx.commitInternal(); setTransaction(null); } /** * Returns true if the database supports READ_COMMITTED or any more strict transaction isolation level. */ boolean supportsReadCommitted() { try { return !database.fakesSupportReadCommitted() && getCurrentTransaction().getConnection().getMetaData().supportsTransactionIsolationLevel( Connection.TRANSACTION_READ_COMMITTED ); } catch (SQLException e) { throw new RuntimeException( e ); } } /** * Returns the collection of open {@link Transaction}s * on this model. * <p> * Returns a unmodifiable synchronized view on the actual data, * so iterating over the collection on a live server may cause * {@link java.util.ConcurrentModificationException}s. * For such cases you may want to create a copy of the collection first. */ public Collection<Transaction> getOpenTransactions() { return Collections.unmodifiableCollection( openTransactions ); } Cache getCache() { if(cache==null) throw newNotInitializedException(); return cache; } public void clearCache() { cache.clear(); } }
package edu.wustl.catissuecore.util.global; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; /** * Utility Class contain general methods used through out the application. * @author kapil_kaveeshwar */ public class Utility { /** * Parses the string format of date in the given format and returns the Data object. * @param date the string containing date. * @param pattern the pattern in which the date is present. * @return the string format of date in the given format and returns the Data object. * @throws ParseException */ public static Date parseDate(String date,String pattern) throws ParseException { if(date!=null && !date.trim().equals("")) { try { SimpleDateFormat dateFormat = new SimpleDateFormat(pattern); Date dateObj = dateFormat.parse(date); return dateObj; } catch(Exception e) { throw new ParseException("Date '"+date+"' is not in format of "+pattern,0); } } else { return null; } } /** * Parses the Date in given format and returns the string representation. * @param date the Date to be parsed. * @param pattern the pattern of the date. * @return */ public static String parseDateToString(Date date, String pattern) { String d = ""; //TODO Check for null if(date!=null) { SimpleDateFormat dateFormat = new SimpleDateFormat(pattern); d = dateFormat.format(date); } return d; } public static String toString(Object obj) { if(obj == null) return ""; return obj.toString(); } // public static void main(String[] args) // try{ // String date = "2005-10-22"; // String pattern = "yyyy-MM-dd HH:mm aa"; // Date d = parseDate(date,pattern); // String dd = parseDateToString(d,pattern); // System.out.println("Date........."+d); // System.out.println("String......."+dd); // catch(ParseException pexcp) // System.out.println("Exception"+pexcp.getMessage()); }
package net.md_5.bungee; import com.google.common.base.Preconditions; import gnu.trove.set.hash.THashSet; import io.netty.bootstrap.Bootstrap; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.socket.nio.NioSocketChannel; import java.net.InetSocketAddress; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.logging.Level; import lombok.AccessLevel; import lombok.Getter; import lombok.Setter; import lombok.Synchronized; import net.md_5.bungee.api.ChatColor; import net.md_5.bungee.api.ProxyServer; import net.md_5.bungee.api.config.ServerInfo; import net.md_5.bungee.api.connection.PendingConnection; import net.md_5.bungee.api.connection.ProxiedPlayer; import net.md_5.bungee.api.event.PermissionCheckEvent; import net.md_5.bungee.api.event.ServerConnectEvent; import net.md_5.bungee.api.scoreboard.Scoreboard; import net.md_5.bungee.netty.HandlerBoss; import net.md_5.bungee.netty.PipelineUtils; import net.md_5.bungee.packet.*; public final class UserConnection implements ProxiedPlayer { public final Packet2Handshake handshake; private final ProxyServer bungee; public final Channel ch; final Packet1Login forgeLogin; final List<PacketFAPluginMessage> loginMessages; @Getter private final PendingConnection pendingConnection; @Getter @Setter(AccessLevel.PACKAGE) private ServerConnection server; // reconnect stuff public int clientEntityId; public int serverEntityId; // ping stuff public int trackingPingId; public long pingTime; @Getter private String name; @Getter private String displayName; @Getter @Setter private int ping = 1000; private final Collection<String> playerGroups = new THashSet<>(); private final Collection<String> permissions = new THashSet<>(); private final Object permMutex = new Object(); @Getter private final Object switchMutex = new Object(); public PacketCCSettings settings; public final Scoreboard serverSentScoreboard = new Scoreboard(); public UserConnection(BungeeCord bungee, Channel channel, PendingConnection pendingConnection, Packet2Handshake handshake, Packet1Login forgeLogin, List<PacketFAPluginMessage> loginMessages) { this.bungee = bungee; this.ch = channel; this.handshake = handshake; this.pendingConnection = pendingConnection; this.forgeLogin = forgeLogin; this.loginMessages = loginMessages; this.name = handshake.username; this.displayName = name; Collection<String> g = bungee.getConfigurationAdapter().getGroups( name ); for ( String s : g ) { addGroups( s ); } } public void sendPacket(DefinedPacket p) { ch.write( p ); } @Override public void setDisplayName(String name) { Preconditions.checkArgument( name.length() <= 16, "Display name cannot be longer than 16 characters" ); displayName=name; bungee.getTabListHandler().onDisconnect( this ); bungee.getTabListHandler().onConnect( this ); } @Override public void connect(ServerInfo target) { if ( getServer() != null && getServer().getInfo() == target ) { sendMessage( ChatColor.RED + "Cannot connect to server you are already on!" ); } else { connect( target, false ); } } public void connectNow(ServerInfo target) { ch.write( Packet9Respawn.DIM1_SWITCH ); ch.write( Packet9Respawn.DIM2_SWITCH ); connect( target ); } public void connect(ServerInfo info, final boolean retry) { ServerConnectEvent event = new ServerConnectEvent( this, info ); ProxyServer.getInstance().getPluginManager().callEvent( event ); final ServerInfo target = event.getTarget(); // Update in case the event changed target if ( getServer() != null && getServer().getInfo() == target ) { return; } new Bootstrap() .channel( NioSocketChannel.class ) .group( BungeeCord.getInstance().eventLoops ) .handler( new ChannelInitializer() { @Override protected void initChannel(Channel ch) throws Exception { PipelineUtils.BASE.initChannel( ch ); ch.pipeline().get( HandlerBoss.class ).setHandler( new ServerConnector( bungee, UserConnection.this, target ) ); } } ) .option( ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000 ) // TODO: Configurable .remoteAddress( target.getAddress() ) .connect().addListener( new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if ( !future.isSuccess() ) { future.channel().close(); ServerInfo def = ProxyServer.getInstance().getServers().get( getPendingConnection().getListener().getDefaultServer() ); if ( retry & target != def && ( getServer() == null || def != getServer().getInfo() ) ) { sendMessage( ChatColor.RED + "Could not connect to target server, you have been moved to the default server" ); connect( def, false ); } else { if ( server == null ) { disconnect( "Could not connect to default server, please try again later: " + future.cause().getClass().getName() ); } else { sendMessage( ChatColor.RED + "Could not connect to selected server, please try again later: " + future.cause().getClass().getName() ); } } } } } ); } @Override public synchronized void disconnect(String reason) { if ( ch.isActive() ) { bungee.getLogger().log( Level.INFO, "[" + getName() + "] disconnected with: " + reason ); ch.write( new PacketFFKick( reason ) ); ch.close(); if ( server != null ) { server.disconnect( "Quitting" ); } } } @Override public void chat(String message) { Preconditions.checkState( server != null, "Not connected to server" ); server.getCh().write( new Packet3Chat( message ) ); } @Override public void sendMessage(String message) { ch.write( new Packet3Chat( message ) ); } @Override public void sendMessages(String... messages) { for ( String message : messages ) { sendMessage( message ); } } @Override public void sendData(String channel, byte[] data) { ch.write( new PacketFAPluginMessage( channel, data ) ); } @Override public InetSocketAddress getAddress() { return (InetSocketAddress) ch.remoteAddress(); } @Override @Synchronized("permMutex") public Collection<String> getGroups() { return Collections.unmodifiableCollection( playerGroups ); } @Override @Synchronized("permMutex") public void addGroups(String... groups) { for ( String group : groups ) { playerGroups.add( group ); for ( String permission : bungee.getConfigurationAdapter().getPermissions( group ) ) { setPermission( permission, true ); } } } @Override @Synchronized("permMutex") public void removeGroups(String... groups) { for ( String group : groups ) { playerGroups.remove( group ); for ( String permission : bungee.getConfigurationAdapter().getPermissions( group ) ) { setPermission( permission, false ); } } } @Override @Synchronized("permMutex") public boolean hasPermission(String permission) { return bungee.getPluginManager().callEvent( new PermissionCheckEvent( this, permission, permissions.contains( permission ) ) ).hasPermission(); } @Override @Synchronized("permMutex") public void setPermission(String permission, boolean value) { if ( value ) { permissions.add( permission ); } else { permissions.remove( permission ); } } @Override public String toString() { return name; } }
package minimesh; import java.io.File; import java.io.IOException; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Properties; import com.opensymphony.module.sitemesh.html.BasicRule; import com.opensymphony.module.sitemesh.html.HTMLProcessor; import com.opensymphony.module.sitemesh.html.Tag; import com.opensymphony.module.sitemesh.html.util.CharArray; import com.opensymphony.module.sitemesh.parser.PageBuilder; import com.opensymphony.module.sitemesh.parser.rules.BodyTagRule; import com.opensymphony.module.sitemesh.parser.rules.HeadExtractingRule; import com.opensymphony.module.sitemesh.parser.rules.MetaTagRule; import com.opensymphony.module.sitemesh.parser.rules.TitleExtractingRule; /** * A single page in a website, including title, filename and content. * * All this information is loaded from an HTML file (using the SiteMesh library). * * @author Joe Walnes */ public class Page { private Properties properties; private String filename; private String head; private String body; private Collection links = new HashSet(); public Page(File htmlFile) { try { filename = htmlFile.getName(); FileSystem fileSystem = new FileSystem(); char[] rawHTML = fileSystem.readFile(htmlFile); extractContentFromHTML(rawHTML); } catch (IOException e) { throw new CannotParsePageException(e); } } public Page(String filename, String htmlContent) { try { this.filename = filename; extractContentFromHTML(htmlContent.toCharArray()); } catch (IOException e) { throw new CannotParsePageException(e); } } private void extractContentFromHTML(char[] rawHTML) throws IOException { // where to dump properties extracted from the page properties = new Properties(); PageBuilder pageBuilder = new PageBuilder() { public void addProperty(String key, String value) { properties.setProperty(key, value); } }; // buffers to hold head and body content CharArray headBuffer = new CharArray(64); CharArray bodyBuffer = new CharArray(4096); // setup rules for html processor HTMLProcessor htmlProcessor = new HTMLProcessor(rawHTML, bodyBuffer); htmlProcessor.addRule(new BodyTagRule(pageBuilder, bodyBuffer)); htmlProcessor.addRule(new HeadExtractingRule(headBuffer)); htmlProcessor.addRule(new TitleExtractingRule(pageBuilder)); htmlProcessor.addRule(new MetaTagRule(pageBuilder)); htmlProcessor.addRule(new LinkExtractingRule()); htmlProcessor.process(); this.head = headBuffer.toString(); this.body = bodyBuffer.toString(); } public String getTitle() { if (properties.containsKey("meta.short")) { return properties.getProperty("meta.short"); } else { return properties.getProperty("title"); } } public String getHead() { return head.toString(); } public String getBody() { return body.toString(); } public String getFilename() { return filename; } public String getHref() { return getFilename(); } public Collection getLinks() { return Collections.unmodifiableCollection(links); } public static class CannotParsePageException extends RuntimeException { public CannotParsePageException(Throwable cause) { super(cause); } } /** * Rule for HTMLProcessor that records all <a href=""> links. */ private class LinkExtractingRule extends BasicRule { public boolean shouldProcess(String tag) { return tag.equalsIgnoreCase("a"); } public void process(Tag tag) { if (tag.hasAttribute("href", false)) { links.add(tag.getAttributeValue("href", false)); } tag.writeTo(currentBuffer()); } } }
package excel; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.text.SimpleDateFormat; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.ZoneId; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.apache.poi.ss.usermodel.*; import org.apache.poi.EncryptedDocumentException; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import sadeh.ActicalEpoch; public class ActicalExcelParser { // The index of the row with the time when the data point was recorded private static final int EPOCH_TIME_INDEX = 0; // Index of the header row containing the data column headers private static final int HEADER_ROW_INDEX = 2; // The data doesn't start immediately after the header row private static final int BEGIN_DATA_ROW_INDEX = 15; // Times are formatted similarly to military time e.g. 23:59:00 private static final SimpleDateFormat acticalTimeFormat = new SimpleDateFormat("HH:mm:ss"); // Workbook name where the data is stored private static final String actigraphWorkbook = "Data from ActiCal"; /** * Parses an excel document containing Actigraph data representing sleep * activity for a participant. Each document only contains data about a * single participant but will contain multiple columns, one for each day * when data was collected. The data is an integer representing activity * level and it is collected each minute, one excel row for each minute of * the day. * * @param path * Path to the Excel document * @return * @throws IOException * @throws Exception */ public static List<ActicalEpoch> parseSadehExcelDocument(File excel) throws ParticipantDataParseException { List<ActicalEpoch> epochs = new ArrayList<>(); Workbook wb = null; // Parse the sleep data from the body rows of the excel document Row row = null; String time = null; // the time an epoch of activity data was collected int rowIdx = BEGIN_DATA_ROW_INDEX; int totalEpochs = 0; try { FileInputStream fis = new FileInputStream(excel); wb = WorkbookFactory.create(fis); Sheet ws = wb.getSheet(actigraphWorkbook); // The epoch data is in non-contiguous columns with known names, this finds the columns indices. List<ActigraphDataHeader> headers = parseHeader(ws); do { row = ws.getRow(rowIdx); if (row != null) { time = parseTimeActivityRecorded(row); if (time != null) { for (ActigraphDataHeader header : headers) { Cell cell = row.getCell(header.getColumnIndex()); if (!isCellEmpty(cell)) { String dataCollectionDay = header.getDayOfWeek(); int activityLevel = (int) cell.getNumericCellValue(); ActicalEpoch epoch = new ActicalEpoch(); epoch.setActivityLevel(activityLevel); epoch.setDayOfWeek(dataCollectionDay); LocalDate ld = header.getDate(); LocalDateTime epochTime = getLocalDateTime(ld, time); epoch.setDateTime(epochTime); epoch.setDate(ld); epochs.add(epoch); totalEpochs++; } } } } rowIdx++; } while (row != null && time != null); } catch (FileNotFoundException ex) { throw new ParticipantDataParseException("File " + excel.getAbsolutePath() + " cannot be opened, it must be manually processed."); } catch (IOException io) { throw new ParticipantDataParseException("IO error occurred processing the file " + excel.getAbsolutePath() + ", it must be manually processed."); } catch (InvalidFormatException io) { throw new ParticipantDataParseException("Invalid format processing the file " + excel.getAbsolutePath() + ", it must be manually processed."); } catch (EncryptedDocumentException ex){ throw new ParticipantDataParseException("Encrypted document error occurred processing the file " + excel.getAbsolutePath() + ", it must be manually processed."); } finally { if (wb != null) try { wb.close(); } catch (IOException e) { throw new ParticipantDataParseException("IO error occurred processing the file " + excel.getAbsolutePath() + ", it must be manually processed."); } } System.out.println("Total epochs in document: " + totalEpochs); return epochs; } private static LocalDateTime getLocalDateTime(LocalDate ld, String actigraphTime) { try { String[] ata = actigraphTime.split(":"); int hour = Integer.parseInt(ata[0]); int minute = Integer.parseInt(ata[1]); int second = Integer.parseInt(ata[2]); return ld.atTime(hour, minute, second); } catch (Exception e) { } return null; } @SuppressWarnings("deprecation") public static boolean isCellEmpty(final Cell cell) { if (cell == null || cell.getCellType() == Cell.CELL_TYPE_BLANK) { return true; } if (cell.getCellType() == Cell.CELL_TYPE_STRING && cell.getStringCellValue().isEmpty()) { return true; } return false; } /** * Each row contains a time in the format HH:mm:ss (participant data is * collected once per minute). This parses the value from the Excel * document. * * @param row * @return */ private static String parseTimeActivityRecorded(Row row) { Cell cell = row.getCell(EPOCH_TIME_INDEX); Date date = parseDate(cell); if (date != null) { return acticalTimeFormat.format(date); } else { return null; } } private static Date parseDate(Cell cell) { if (!isCellEmpty(cell)) { return cell.getDateCellValue(); } else { return null; } } private static List<ActigraphDataHeader> parseHeader(Sheet ws) { List<ActigraphDataHeader> headers = new ArrayList<>(8); // There should // be no more // than 8 // columns Row row = ws.getRow(HEADER_ROW_INDEX); Row dateRow = ws.getRow(BEGIN_DATA_ROW_INDEX); int maxColIdx = 26; // There cannot be headers past this column for (int i = 0; i < maxColIdx; i++) { Cell cell = row.getCell(i); if (cell != null) { try { String value = cell.getStringCellValue(); if (value != null && !value.equalsIgnoreCase("") && getHeaderName(value) != null) { ActigraphDataHeader header = new ActigraphDataHeader(); if (i - 2 >= 1) { Date date = parseDate(dateRow.getCell(i - 2)); LocalDate ld = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(); header.setDate(ld); } else { throw new Exception("Date cannot be found for header column " + i); } header.setColumnIndex(i); header.setHeader(value); header.setDayOfWeek(getHeaderName(value)); headers.add(header); } } catch (Exception e) { } } } return headers; } /** * If the name is a day of the week, returns it in standard format, * otherwise, returns null. */ public static String getHeaderName(String name) { String temp = name.toLowerCase(); if (temp.contains("mon")) { return "Monday"; } else if (temp.contains("tue")) { return "Tuesday"; } else if (temp.contains("wed")) { return "Wednesday"; } else if (temp.contains("thu")) { return "Thursday"; } else if (temp.contains("fri")) { return "Friday"; } else if (temp.contains("sat")) { return "Saturday"; } else if (temp.contains("sun")) { return "Sunday"; } return null; } /** * The Actigraphy data is arranged into columns where the first column is * the minute of day, the second column is Monday, the third Tuesday, etc. * Under Monday, Tuesday, and the other days of the week, the value at each * cell is the activity level of the participant for that time of day. * * We're collecting data for each day of the week so this helps us know what * day of the week we're parsing data for. * * @author kyle_ * */ public static class ActigraphDataHeader { String header; String dayOfWeek; int columnIndex; LocalDate date; public LocalDate getDate() { return date; } public void setDate(LocalDate date) { this.date = date; } public String getHeader() { return header; } public void setHeader(String header) { this.header = header; } public String getDayOfWeek() { return dayOfWeek; } public void setDayOfWeek(String dayOfWeek) { this.dayOfWeek = dayOfWeek; } public int getColumnIndex() { return columnIndex; } public void setColumnIndex(int columnIndex) { this.columnIndex = columnIndex; } } }
package domain; public class Constants { public static final String API_URL = "https://api.icndb.com/jokes/random?limitTo=[nerdy]&escape=javascript"; }
package org.javacs; import java.nio.file.Path; import java.time.Instant; import java.util.HashMap; import java.util.Map; import java.util.Objects; /** Cache maps a file + an arbitrary key to a value. When the file is modified, the mapping expires. */ class Cache<K, V> { private static class Key<K> { final Path file; final K key; Key(Path file, K key) { this.file = file; this.key = key; } @Override public boolean equals(Object other) { if (other.getClass() != Cache.Key.class) return false; var that = (Cache.Key) other; return Objects.equals(this.key, that.key) && Objects.equals(this.file, that.file); } @Override public int hashCode() { return Objects.hash(file, key); } } private class Value { final V value; final Instant created = Instant.now(); Value(V value) { this.value = value; } } private final Map<Key, Value> map = new HashMap<>(); boolean has(Path file, K k) { return !needs(file, k); } boolean needs(Path file, K k) { // If key is not in map, it needs to be loaded var key = new Key<K>(file, k); if (!map.containsKey(key)) return true; // If key was loaded before file was last modified, it needs to be reloaded var value = map.get(key); var modified = FileStore.modified(file); // TODO remove all keys associated with file when file changes return value.created.isBefore(modified); } void load(Path file, K k, V v) { // TODO limit total size of cache var key = new Key<K>(file, k); var value = new Value(v); map.put(key, value); } V get(Path file, K k) { var key = new Key<K>(file, k); if (!map.containsKey(key)) { throw new IllegalArgumentException(k + " is not in map " + map); } return map.get(key).value; } }
package sesim; /** * * @author 7u83 */ public abstract class AutoTrader implements Scheduler.TimerTask { protected double account_id; protected Exchange se; protected AutoTraderConfig config; protected String name; public AutoTrader(Exchange se, long id, String name, double money, double shares, AutoTraderConfig config) { account_id = se.createAccount(money, shares); this.se = se; this.config = config; this.name = name; this.id=id; } public void setName(String name) { this.name = name; } public String getName() { return name; } @Override public long getID(){ return id; } private final long id; public Exchange.Account getAccount(){ return se.getAccount(account_id); } public abstract void start(); }
package ui; import java.util.ArrayList; import dummy.LogicDummy; import dummy.LogicInterfaceDummy; import dummy.TaskDummy; public class UserInterface implements IUserInterface { private static final String UI_MESSAGE_INIT = "Initializing UI..."; private static final String UI_MESSAGE_INITED = "Initialization Completed!"; private static final String UI_MESSAGE_WELCOME = "Welcome to JFDI! :) " + "What would you like to do now?"; private static final String UI_MESSAGE_USERCMD = "Your input: %1$s"; private static final String UI_MESSAGE_QUIT = "Bye Bye! See you next time! :)"; LogicInterfaceDummy logic; private MainController controller; public UserInterface() { // what to do for constructor? } @Override public void init() { showToUser(UI_MESSAGE_INIT); // Initialize Logic logic = new LogicDummy(); logic.init(); // Error: if fail to get data (logic issue), query user for filename showToUser(UI_MESSAGE_INITED); } @Override public void displayWelcome() { // Create and display a default view // display default list controller.clearFeedback(); controller.displayFeedback(UI_MESSAGE_WELCOME); } @Override public void processInput(String input) { // Clear controller first controller.clearCommandBox(); controller.clearFeedback(); // Show user the command recognized in the feedback area controller.displayFeedback(String.format(UI_MESSAGE_USERCMD, input)); // Relay user input to logic and wait for reply String feedback = logic.handleInput(input); // Update UI according to reply from logic switch (feedback) { case "QUIT": doQuit(); break; default: doUserCmd(); break; } } @Override public ArrayList<TaskDummy> getList() { // get list of tasks from storage if command is completed (ArrayList<Task>) return null; } @Override public void setController(MainController controller) { this.controller = controller; } private void showToUser(String string) { System.out.println(string); } private void doQuit() { showToUser(UI_MESSAGE_QUIT); System.exit(0); } private void doUserCmd() { } }
package water; import java.io.*; import java.net.URI; import java.net.URISyntaxException; import java.util.Arrays; import water.api.Constants.Schemes; import water.hdfs.PersistHdfs; import water.util.Log; // Persistence backend for the local storage device // Stores all keys as files, or if leveldb is enabled, stores values smaller // than arraylet chunk size in a leveldb format. // Metadata stored are the value type and the desired replication factor of the // key. // @author peta, cliffc public abstract class PersistIce { protected static final String ROOT; public static final String DEFAULT_ROOT = "/tmp"; private static final String ICE_DIR = "ice"; private static final String LOG_FILENAME = "h2o.log"; private static final URI iceRoot; public static final File logFile; // Load into the K/V store all the files found on the local disk static void initialize() {} static { ROOT = (H2O.OPT_ARGS.ice_root==null) ? DEFAULT_ROOT : H2O.OPT_ARGS.ice_root; H2O.OPT_ARGS.ice_root = ROOT; try { String uri = (ROOT+"/"+ICE_DIR+H2O.API_PORT).replace("\\","/"); iceRoot = new URI(uri); if(Schemes.HDFS.equals(iceRoot.getScheme())) logFile = new File(DEFAULT_ROOT+File.separator+LOG_FILENAME); else logFile = new File(iceRoot+File.separator+LOG_FILENAME); } catch( URISyntaxException e ) { throw new RuntimeException(e); } // Make the directory as-needed if(Schemes.HDFS.equals(iceRoot.getScheme())) PersistHdfs.mkdir(iceRoot); else { File f = new File(iceRoot.getPath()); f.mkdirs(); if( !(f.isDirectory() && f.canRead() && f.canWrite()) ) Log.die("ice_root not a read/writable directory"); } // By popular demand, clear out ICE on startup instead of trying to preserve it if( H2O.OPT_ARGS.keepice == null ) { if(Schemes.HDFS.equals(iceRoot.getScheme())) PersistHdfs.cleanIce(iceRoot); else cleanIce(new File(iceRoot.getPath())); } else initializeFilesFromFolder(new File(iceRoot)); } // Clear the ICE directory public static void cleanIce(File dir) { for( File f : dir.listFiles() ) { if( f.isDirectory() ) cleanIce(f); f.delete(); } } // Initializes Key/Value pairs for files on the local disk. private static void initializeFilesFromFolder(File dir) { for (File f : dir.listFiles()) { if( f.isDirectory() ) { initializeFilesFromFolder(f); // Recursively keep loading K/V pairs } else { Key k = decodeKey(f); Value ice = new Value(k,(int)f.length()); ice.setdsk(); H2O.putIfAbsent_raw(k,ice); } } } public static FileWriter logFile() { try { return new FileWriter(logFile); } catch( IOException e ) { /*do not log errors when trying to open the log file*/ return null; } } // the filename can be either byte encoded if it starts with % followed by // a number, or is a normal key name with special characters encoded in // special ways. // It is questionable whether we need this because the only keys we have on // ice are likely to be arraylet chunks // Verify bijection of key/file-name mappings. private static String key2Str(Key k, byte type) { String s = key2Str_impl(k,type); Key x; assert (x=str2Key_impl(s)).equals(k) : "bijection fail "+k+"."+(char)type+" <-> "+s+" <-> "+x; return s; } // Verify bijection of key/file-name mappings. private static Key str2Key(String s) { Key k = str2Key_impl(s); assert key2Str_impl(k,decodeType(s)).equals(s) : "bijection fail "+s+" <-> "+k; return k; } private static byte decodeType(String s) { String ext = s.substring(s.lastIndexOf('.')+1); return (byte)ext.charAt(0); } // Convert a Key to a suitable filename string private static String key2Str_impl(Key k, byte type) { // check if we are system key StringBuilder sb = new StringBuilder(k._kb.length/2+4); int i=0; if( k._kb[0]<32 ) { // System keys: hexalate all the leading non-ascii bytes sb.append('%'); int j=k._kb.length-1; // Backwards scan for 1st non-ascii while( j >= 0 && k._kb[j] >= 32 && k._kb[j] < 128 ) j for( ; i<=j; i++ ) { byte b = k._kb[i]; int nib0 = ((b>>>4)&15)+'0'; if( nib0 > '9' ) nib0 += 'A'-10-'0'; int nib1 = ((b>>>0)&15)+'0'; if( nib1 > '9' ) nib1 += 'A'-10-'0'; sb.append((char)nib0).append((char)nib1); } sb.append('%'); } // Escape the special bytes from 'i' to the end return escapeBytes(k._kb,i,sb).append('.').append((char)type).toString(); } private static StringBuilder escapeBytes(byte[] bytes, int i, StringBuilder sb) { for( ; i<bytes.length; i++ ) { byte b = bytes[i]; switch( b ) { case '%': sb.append("%%"); break; case '.': sb.append("%d"); break; // dot case '/': sb.append("%s"); break; // slash case ':': sb.append("%c"); break; // colon case '\\': sb.append("%b"); break; // backslash case '"': sb.append("%q"); break; // quote case '\0': sb.append("%z"); break; // nullbit default: sb.append((char)b); break; } } return sb; } // Convert a filename string to a Key private static Key str2Key_impl(String s) { String key = s.substring(0,s.lastIndexOf('.')); // Drop extension byte[] kb = new byte[(key.length()-1)/2]; int i = 0, j = 0; if( (key.length()>2) && (key.charAt(0)=='%') && (key.charAt(1)>='0') && (key.charAt(1)<='9') ) { // Dehexalate until '%' for( i = 1; i < key.length(); i+=2 ) { if( key.charAt(i)=='%' ) break; char b0 = (char)(key.charAt(i+0)-'0'); if( b0 > 9 ) b0 += '0'+10-'A'; char b1 = (char)(key.charAt(i+1)-'0'); if( b1 > 9 ) b1 += '0'+10-'A'; kb[j++] = (byte)((b0<<4)|b1); // De-hexelated byte } i++; // Skip the trailing '%' } // a normal key - ASCII with special characters encoded after % sign for( ; i < key.length(); ++i ) { byte b = (byte)key.charAt(i); if( b == '%' ) { switch( key.charAt(++i) ) { case '%': b = '%' ; break; case 'b': b = '\\'; break; case 'c': b = ':' ; break; case 'd': b = '.' ; break; case 'q': b = '"' ; break; case 's': b = '/' ; break; case 'z': b = '\0'; break; default: Log.warn("Invalid format of filename " + s + " at index " + i); } } if( j>=kb.length ) kb = Arrays.copyOf(kb,Math.max(2,j*2)); kb[j++] = b; } // now in kb we have the key name return Key.make(Arrays.copyOf(kb,j)); } private static final Key decodeKey(File f) { return str2Key(f.getName()); } private static File encodeKeyToFile(Value v) { return new File(encodeKey(v)); } private static String encodeKey(Value v) { return encodeKey(v._key,(byte)(v.isArray()?'A':'V')); } private static String encodeKey(Key k, byte type) { return iceRoot.toString()+File.separator+getDirectoryForKey(k)+File.separator+key2Str(k,type); } private static String getDirectoryForKey(Key key) { if( key._kb[0] != Key.ARRAYLET_CHUNK ) return "not_an_arraylet"; // Reverse arraylet key generation byte[] b = ValueArray.getArrayKeyBytes(key); return escapeBytes(b,0,new StringBuilder(b.length)).toString(); } // Read up to 'len' bytes of Value. Value should already be persisted to // disk. A racing delete can trigger a failure where we get a null return, // but no crash (although one could argue that a racing load&delete is a bug // no matter what). static byte[] fileLoad(Value v) { if(Schemes.HDFS.equals(iceRoot.getScheme())) { return PersistHdfs.fileLoad(v, iceRoot.getPath() + File.separatorChar + encodeKeyToFile(v)); } else { File f = encodeKeyToFile(v); if( f.length() < v._max ) { // Should be fully on disk... or assert !v.isPersisted() : f.length() + " " + v._max + " " + v._key; // or it's a racey delete of a spilled value return null; // No value } try { FileInputStream s = new FileInputStream(f); try { AutoBuffer ab = new AutoBuffer(s.getChannel(),true,Value.ICE); byte[] b = ab.getA1(v._max); ab.close(); return b; } finally { s.close(); } } catch( IOException e ) { // Broken disk / short-file??? throw new RuntimeException(Log.err("File load failed: ",e)); } } } public static class PersistIceException extends Exception {} // Store Value v to disk. static void fileStore(Value v) throws IOException { // A perhaps useless cutout: the upper layers should test this first. if( v.isPersisted() ) return; if(Schemes.HDFS.equals(iceRoot.getScheme())) { PersistHdfs.store(encodeKey(v), v); } else { new File(iceRoot.toString(),getDirectoryForKey(v._key)).mkdirs(); // Nuke any prior file. FileOutputStream s = null; try { s = new FileOutputStream(encodeKeyToFile(v)); } catch (FileNotFoundException e) { throw new RuntimeException(Log.err("Encoding a key to a file failed!\nKey: "+v._key.toString()+"\nEncoded: "+encodeKeyToFile(v),e)); } try { byte[] m = v.memOrLoad(); // we are not single threaded anymore assert m != null && m.length == v._max : " "+v._key+" "+m; // Assert not saving partial files new AutoBuffer(s.getChannel(),false,Value.ICE).putA1(m,m.length).close(); v.setdsk(); // Set as write-complete to disk } finally { if( s != null ) s.close(); } } } static void fileDelete(Value v) { assert !v.isPersisted(); // Upper layers already cleared out File f = encodeKeyToFile(v); f.delete(); if( v.isArray() ) { // Also nuke directory if the top-level ValueArray dies f = new File(iceRoot.toString(),getDirectoryForKey(v._key)); f.delete(); } } static Value lazyArrayChunk( Key key ) { assert key._kb[0] == Key.ARRAYLET_CHUNK; assert key.home(); // Only do this on the home node File f = new File(encodeKey(key,(byte)'V'/*typed as a Value chunk, not the array header*/)); if( !f.isFile() ) return null; Value val = new Value(key,(int)f.length()); val.setdsk(); // But its already on disk. return val; } }
package water.util; import hex.rng.*; import hex.rng.H2ORandomRNG.RNGKind; import hex.rng.H2ORandomRNG.RNGType; import java.io.*; import java.net.Socket; import java.net.URL; import java.security.SecureRandom; import java.text.DecimalFormat; import java.util.*; import java.util.zip.*; import org.apache.commons.lang.ArrayUtils; import water.*; import water.api.DocGen.FieldDoc; import water.parser.ParseDataset; import water.parser.ValueString; import water.parser.ParseDataset.Compression; public class Utils { /** Returns the index of the largest value in the array. * In case of a tie, an the index is selected randomly. */ public static int maxIndex(int[] from, Random rand) { assert rand != null; int result = 0; int maxCount = 0; // count of maximal element for a 1 item reservoir sample for( int i = 1; i < from.length; ++i ) { if( from[i] > from[result] ) { result = i; maxCount = 1; } else if( from[i] == from[result] ) { if( rand.nextInt(++maxCount) == 0 ) result = i; } } return result; } public static int maxIndex(int[] from) { int result = 0; for (int i = 1; i<from.length; ++i) if (from[i]>from[result]) result = i; return result; } public static int maxIndex(float[] from) { int result = 0; for (int i = 1; i<from.length; ++i) if (from[i]>from[result]) result = i; return result; } public static double lnF(double what) { return (what < 1e-06) ? 0 : what * Math.log(what); } public static String p2d(double d) { return !Double.isNaN(d) ? new DecimalFormat ("0.##" ).format(d) : "nan"; } public static String p5d(double d) { return !Double.isNaN(d) ? new DecimalFormat ("0. public static int set4( byte[] buf, int off, int x ) { for( int i=0; i<4; i++ ) buf[i+off] = (byte)(x>>(i<<3)); return 4; } public static int get4( byte[] buf, int off ) { int sum=0; for( int i=0; i<4; i++ ) sum |= (0xff&buf[off+i])<<(i<<3); return sum; } public static int set8d( byte[] buf, int off, double d ) { long x = Double.doubleToLongBits(d); for( int i=0; i<8; i++ ) buf[i+off] = (byte)(x>>(i<<3)); return 8; } public static double get8d( byte[] buf, int off ) { long sum=0; for( int i=0; i<8; i++ ) sum |= ((long)(0xff&buf[off+i]))<<(i<<3); return Double.longBitsToDouble(sum); } public static int sum(int[] from) { int result = 0; for (int d: from) result += d; return result; } public static float sum(float[] from) { float result = 0; for (float d: from) result += d; return result; } public static String sampleToString(int[] val, int max) { if (val == null || val.length < max) return Arrays.toString(val); StringBuilder b = new StringBuilder(); b.append('['); max -= 10; int valMax = val.length -1; for (int i = 0; ; i++) { b.append(val[i]); if (i == max) { b.append(", ..."); i = val.length - 10; } if ( i == valMax) { return b.append(']').toString(); } b.append(", "); } } /* Always returns a deterministic java.util.Random RNG. * * The determinism is important for re-playing sampling. */ public static Random getDeterRNG(long seed) { return new H2ORandomRNG(seed); } public static void setUsedRNGKind(final RNGKind kind) { switch (kind) { case DETERMINISTIC: setUsedRNGType(RNGType.MersenneTwisterRNG); break; case NON_DETERMINISTIC: setUsedRNGType(RNGType.SecureRNG); break; } } /* Returns the configured random generator */ public synchronized static Random getRNG(long... seed) { assert _rngType != null : "Random generator type has to be configured"; switch (_rngType) { case JavaRNG: assert seed.length >= 1; return new H2ORandomRNG(seed[0]); case MersenneTwisterRNG: // do not copy the seeds - use them, and initialize the first two ints by seeds based given argument // the call is locked, and also MersenneTwisterRNG will just copy the seeds into its datastructures assert seed.length == 1; int[] seeds = MersenneTwisterRNG.SEEDS; int[] inSeeds = unpackInts(seed); seeds[0] = inSeeds[0]; seeds[1] = inSeeds[1]; return new MersenneTwisterRNG(seeds); case XorShiftRNG: assert seed.length >= 1; return new XorShiftRNG(seed[0]); case SecureRNG: return new SecureRandom(); } throw new IllegalArgumentException("Unknown random generator type: " + _rngType); } private static RNGType _rngType = RNGType.MersenneTwisterRNG; public static void setUsedRNGType(RNGType rngType) { Utils._rngType = rngType; } public static RNGType getUsedRNGType() { return Utils._rngType; } public static RNGKind getUsedRNGKind() { return Utils._rngType.kind(); } /* * Compute entropy value for an array of bytes. * * The returned number represents entropy per bit! * For good long number seed (8bytes seed) it should be in range <2.75,3> (higher is better) * * For large set of bytes (>100) it should be almost 8 (means almost 8 random bits per byte). */ public static float entropy(byte[] f) { int counts[] = new int[256]; float entropy = 0; float total = f.length; for (byte b : f) counts[b+128]++; for (int c : counts) { if (c == 0) continue; float p = c / total; /* Compute entropy per bit in byte. * * To compute entropy per byte compute log with base 256 = log(p)/log(256). */ entropy -= p * Math.log(p)/Math.log(2); } return entropy; } public static int[] unpackInts(long... longs) { int len = 2*longs.length; int result[] = new int[len]; int i = 0; for (long l : longs) { result[i++] = (int) (l & 0xffffffffL); result[i++] = (int) (l>>32); } return result; } public static void shuffleArray(long[] a) { int n = a.length; Random random = new Random(); random.nextInt(); for (int i = 0; i < n; i++) { int change = i + random.nextInt(n - i); swap(a, i, change); } } private static void swap(long[] a, int i, int change) { long helper = a[i]; a[i] = a[change]; a[change] = helper; } public static void close(Closeable...closeable) { for(Closeable c : closeable) try { if( c != null ) c.close(); } catch( IOException _ ) { } } public static void close(Socket s) { try { if( s != null ) s.close(); } catch( IOException _ ) { } } public static String readConsole() { BufferedReader console = new BufferedReader(new InputStreamReader(System.in)); try { return console.readLine(); } catch( IOException e ) { throw Log.errRTExcept(e); } } public static File writeFile(String content) { try { return writeFile(File.createTempFile("h2o", null), content); } catch( IOException e ) { throw Log.errRTExcept(e); } } public static File writeFile(File file, String content) { FileWriter w = null; try { w = new FileWriter(file); w.write(content); } catch(IOException e) { Log.errRTExcept(e); } finally { close(w); } return file; } public static void writeFileAndClose(File file, InputStream in) { OutputStream out = null; try { out = new FileOutputStream(file); byte[] buffer = new byte[1024]; int len = in.read(buffer); while (len > 0) { out.write(buffer, 0, len); len = in.read(buffer); } } catch(IOException e) { throw Log.errRTExcept(e); } finally { close(in, out); } } public static String readFile(File file) { FileReader r = null; try { r = new FileReader(file); char[] data = new char[(int) file.length()]; r.read(data); return new String(data); } catch(IOException e) { throw Log.errRTExcept(e); } finally { close(r); } } public static void readFile(File file, OutputStream out) { BufferedInputStream in = null; try { in = new BufferedInputStream(new FileInputStream(file)); byte[] buffer = new byte[1024]; while( true ) { int count = in.read(buffer); if( count == -1 ) break; out.write(buffer, 0, count); } } catch(IOException e) { throw Log.errRTExcept(e); } finally { close(in); } } public static String join(char sep, Object[] array) { return join(sep, Arrays.asList(array)); } public static String join(char sep, Iterable it) { String s = ""; for( Object o : it ) s += (s.length() == 0 ? "" : sep) + o.toString(); return s; } public static byte[] or(byte[] a, byte[] b) { for(int i = 0; i < a.length; i++ ) a[i] |= b[i]; return a; } public static byte[] add(byte[] a, byte[] b) { for(int i = 0; i < a.length; i++ ) a[i] += b[i]; return a; } public static int[] add(int[] a, int[] b) { for(int i = 0; i < a.length; i++ ) a[i] += b[i]; return a; } public static int[][] add(int[][] a, int[][] b) { for(int i = 0; i < a.length; i++ ) add(a[i],b[i]); return a; } public static long[] add(long[] a, long[] b) { for(int i = 0; i < a.length; i++ ) a[i] += b[i]; return a; } public static long[][] add(long[][] a, long[][] b) { for(int i = 0; i < a.length; i++ ) add(a[i],b[i]); return a; } public static float[] add(float[] a, float[] b) { for(int i = 0; i < a.length; i++ ) a[i] += b[i]; return a; } public static float[][] add(float[][] a, float[][] b) { for(int i = 0; i < a.length; i++ ) add(a[i],b[i]); return a; } public static double[] add(double[] a, double[] b) { if( a==null ) return b; for(int i = 0; i < a.length; i++ ) a[i] += b[i]; return a; } public static double[][] add(double[][] a, double[][] b) { for(int i = 0; i < a.length; i++ ) a[i] = add(a[i],b[i]); return a; } public static double[][] append(double[][] a, double[][] b) { double[][] res = new double[a.length + b.length][]; System.arraycopy(a, 0, res, 0, a.length); System.arraycopy(b, 0, res, a.length, b.length); return res; } public static int[] append(int[] a, int[] b) { int[] res = new int[a.length + b.length]; System.arraycopy(a, 0, res, 0, a.length); System.arraycopy(b, 0, res, a.length, b.length); return res; } public static String[] append(String[] a, String[] b) { String[] res = new String[a.length + b.length]; System.arraycopy(a, 0, res, 0, a.length); System.arraycopy(b, 0, res, a.length, b.length); return res; } public static <T> T[] append(T[] a, T... b) { return (T[]) ArrayUtils.addAll(a, b); } public static <T> T[] remove(T[] a, int i) { return (T[]) ArrayUtils.remove(a, i); } public static <T> T[] subarray(T[] a, int off, int len) { return (T[]) ArrayUtils.subarray(a, off, off + len); } public static void clearFolder(String folder) { clearFolder(new File(folder)); } public static void clearFolder(File folder) { if (folder.exists()) { for (File child : folder.listFiles()) { if (child.isDirectory()) clearFolder(child); if (!child.delete()) throw new RuntimeException("Cannot delete " + child); } } } /** * Returns the system temporary folder, e.g. /tmp */ public static File tmp() { try { return File.createTempFile("h2o", null).getParentFile(); } catch( IOException e ) { throw new RuntimeException(e); } } public static ValueArray loadAndParseKey(String path) { return loadAndParseKey(Key.make(), path); } public static ValueArray loadAndParseKey(Key okey, String path) { FileIntegrityChecker c = FileIntegrityChecker.check(new File(path),false); Futures fs = new Futures(); Key k = c.importFile(0, fs); fs.blockForPending(); ParseDataset.forkParseDataset(okey, new Key[] { k }, null).get(); UKV.remove(k); ValueArray res = DKV.get(okey).get(); return res; } public static byte [] getFirstUnzipedBytes(Key k){ return getFirstUnzipedBytes(DKV.get(k)); } public static byte [] getFirstUnzipedBytes(Value v){ byte [] bits = v.getFirstBytes(); try{ return unzipBytes(bits, guessCompressionMethod(bits)); } catch(Exception e){return null;} } public static Compression guessCompressionMethod(byte [] bits){ AutoBuffer ab = new AutoBuffer(bits); // Look for ZIP magic if( bits.length > ZipFile.LOCHDR && ab.get4(0) == ZipFile.LOCSIG ) return Compression.ZIP; if( bits.length > 2 && ab.get2(0) == GZIPInputStream.GZIP_MAGIC ) return Compression.GZIP; return Compression.NONE; } public static byte [] unzipBytes(byte [] bs, Compression cmp) { InputStream is = null; int off = 0; try { switch(cmp) { case NONE: // No compression return bs; case ZIP: { ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(bs)); ZipEntry ze = zis.getNextEntry(); // Get the *FIRST* entry // There is at least one entry in zip file and it is not a directory. if( ze != null && !ze.isDirectory() ) { is = zis; break; } zis.close(); return bs; // Don't crash, ignore file if cannot unzip } case GZIP: is = new GZIPInputStream(new ByteArrayInputStream(bs)); break; default: assert false:"cmp = " + cmp; } // If reading from a compressed stream, estimate we can read 2x uncompressed assert( is != null ):"is is NULL, cmp = " + cmp; bs = new byte[bs.length * 2]; // Now read from the (possibly compressed) stream while( off < bs.length ) { int len = is.read(bs, off, bs.length - off); if( len < 0 ) break; off += len; if( off == bs.length ) { // Dataset is uncompressing alot! Need more space... if( bs.length >= ValueArray.CHUNK_SZ ) break; // Already got enough bs = Arrays.copyOf(bs, bs.length * 2); } } } catch( IOException ioe ) { // Stop at any io error Log.err(ioe); } finally { Utils.close(is); } return bs; } /** * Simple wrapper around ArrayList with support for H2O serialization * @author tomasnykodym * @param <T> */ public static class IcedArrayList<T extends Iced> extends ArrayList<T> implements Freezable { private static final int I; static { I = TypeMap.onLoad(IcedArrayList.class.getName()); } @Override public AutoBuffer write(AutoBuffer bb) { bb.put4(size()); for(T t:this) bb.put(t); return bb; } @Override public IcedArrayList<T> read(AutoBuffer bb) { int n = bb.get4(); for(int i = 0; i < n; ++i) add(bb.<T>get()); return this; } @Override public <T2 extends Freezable> T2 newInstance() { return (T2)new IcedArrayList<T>(); } @Override public int frozenType() { return I; } @Override public AutoBuffer writeJSONFields(AutoBuffer bb) { return bb; } @Override public FieldDoc[] toDocField() { return null; } } public static class IcedInt extends Iced { public final int _val; public IcedInt(int v){_val = v;} } /** * Simple wrapper around HashMap with support for H2O serialization * @author tomasnykodym * @param <T> */ public static class IcedHashMap<K extends Iced, V extends Iced> extends HashMap<K,V> implements Freezable { private static final int I; static { I = TypeMap.onLoad(IcedHashMap.class.getName()); } @Override public AutoBuffer write(AutoBuffer bb) { bb.put4(size()); for(Map.Entry<K, V> e:entrySet())bb.put(e.getKey()).put(e.getValue()); return bb; } @Override public IcedHashMap<K,V> read(AutoBuffer bb) { int n = bb.get4(); for(int i = 0; i < n; ++i) put(bb.<K>get(),bb.<V>get()); return this; } @Override public <T2 extends Freezable> T2 newInstance() { return (T2)new IcedHashMap<K,V>(); } @Override public int frozenType() { return I; } @Override public AutoBuffer writeJSONFields(AutoBuffer bb) { return bb; } @Override public FieldDoc[] toDocField() { return null; } } public static final boolean hasNaNsOrInfs(double [] arr){ for(double d:arr) if(Double.isNaN(d) || Double.isInfinite(d))return true; return false; } public static class ExpectedExceptionForDebug extends RuntimeException { } public static String getStackAsString(Throwable t) { Writer result = new StringWriter(); PrintWriter printWriter = new PrintWriter(result); t.printStackTrace(printWriter); return result.toString(); } // Deduce if we are looking at a Date/Time value, or not. // If so, return time as msec since Jan 1, 1970 or Long.MIN_VALUE. // I tried java.util.SimpleDateFormat, but it just throws too many // exceptions, including ParseException, NumberFormatException, and // ArrayIndexOutOfBoundsException... and the Piece de resistance: a // ClassCastException deep in the SimpleDateFormat code: // "sun.util.calendar.Gregorian$Date cannot be cast to sun.util.calendar.JulianCalendar$Date" public static int digit( int x, int c ) { if( x < 0 || c < '0' || c > '9' ) return -1; return x*10+(c-'0'); } // So I just brutally parse "dd-MMM-yy". public static final byte MMS[][][] = new byte[][][] { {"jan".getBytes(),null}, {"feb".getBytes(),null}, {"mar".getBytes(),null}, {"apr".getBytes(),null}, {"may".getBytes(),null}, {"jun".getBytes(),"june".getBytes()}, {"jul".getBytes(),"july".getBytes()}, {"aug".getBytes(),null}, {"sep".getBytes(),"sept".getBytes()}, {"oct".getBytes(),null}, {"nov".getBytes(),null}, {"dec".getBytes(),null} }; public static long attemptTimeParse( ValueString str ) { long t0 = attemptTimeParse_0(str); // "yyyy-MM-dd HH:mm:ss.SSS" if( t0 != Long.MIN_VALUE ) return t0; long t1 = attemptTimeParse_1(str); // "dd-MMM-yy" if( t1 != Long.MIN_VALUE ) return t1; return Long.MIN_VALUE; } // So I just brutally parse "yyyy-MM-dd HH:mm:ss.SSS" private static long attemptTimeParse_0( ValueString str ) { final byte[] buf = str.get_buf(); int i=str.get_off(); final int end = i+str.get_length(); while( i < end && buf[i] == ' ' ) i++; if ( i < end && buf[i] == '"' ) i++; if( (end-i) < 19 ) return Long.MIN_VALUE; int yy=0, MM=0, dd=0, HH=0, mm=0, ss=0, SS=0; yy = digit(yy,buf[i++]); yy = digit(yy,buf[i++]); yy = digit(yy,buf[i++]); yy = digit(yy,buf[i++]); if( yy < 1970 ) return Long.MIN_VALUE; if( buf[i++] != '-' ) return Long.MIN_VALUE; MM = digit(MM,buf[i++]); MM = digit(MM,buf[i++]); if( MM < 1 || MM > 12 ) return Long.MIN_VALUE; if( buf[i++] != '-' ) return Long.MIN_VALUE; dd = digit(dd,buf[i++]); dd = digit(dd,buf[i++]); if( dd < 1 || dd > 31 ) return Long.MIN_VALUE; if( buf[i++] != ' ' ) return Long.MIN_VALUE; HH = digit(HH,buf[i++]); HH = digit(HH,buf[i++]); if( HH < 0 || HH > 23 ) return Long.MIN_VALUE; if( buf[i++] != ':' ) return Long.MIN_VALUE; mm = digit(mm,buf[i++]); mm = digit(mm,buf[i++]); if( mm < 0 || mm > 59 ) return Long.MIN_VALUE; if( buf[i++] != ':' ) return Long.MIN_VALUE; ss = digit(ss,buf[i++]); ss = digit(ss,buf[i++]); if( ss < 0 || ss > 59 ) return Long.MIN_VALUE; if( i<end && buf[i] == '.' ) { i++; if( i<end ) SS = digit(SS,buf[i++]); if( i<end ) SS = digit(SS,buf[i++]); if( i<end ) SS = digit(SS,buf[i++]); if( SS < 0 || SS > 999 ) return Long.MIN_VALUE; } if( i<end && buf[i] == '"' ) i++; if( i<end ) return Long.MIN_VALUE; return new GregorianCalendar(yy,MM,dd,HH,mm,ss).getTimeInMillis()+SS; } private static long attemptTimeParse_1( ValueString str ) { final byte[] buf = str.get_buf(); int i=str.get_off(); final int end = i+str.get_length(); while( i < end && buf[i] == ' ' ) i++; if ( i < end && buf[i] == '"' ) i++; if( (end-i) < 8 ) return Long.MIN_VALUE; int yy=0, MM=0, dd=0; dd = digit(dd,buf[i++]); if( buf[i] != '-' ) dd = digit(dd,buf[i++]); if( dd < 1 || dd > 31 ) return Long.MIN_VALUE; if( buf[i++] != '-' ) return Long.MIN_VALUE; byte[]mm=null; OUTER: for( ; MM<MMS.length; MM++ ) { byte[][] mms = MMS[MM]; INNER: for( int k=0; k<mms.length; k++ ) { mm = mms[k]; if( mm == null ) continue; for( int j=0; j<mm.length; j++ ) if( mm[j] != Character.toLowerCase(buf[i+j]) ) continue INNER; break OUTER; } } if( MM == MMS.length ) return Long.MIN_VALUE; // No matching month i += mm.length; // Skip month bytes MM++; // 1-based month if( buf[i++] != '-' ) return Long.MIN_VALUE; yy = digit(yy,buf[i++]); yy = digit(yy,buf[i++]); yy += 2000; // Y2K bug if( i<end && buf[i] == '"' ) i++; if( i<end ) return Long.MIN_VALUE; return new GregorianCalendar(yy,MM,dd).getTimeInMillis(); } /** Returns a mapping of given domain to values (0, ... max(dom)). * Unused domain items has mapping to -1. */ public static int[] mapping(int[] dom) { int max = dom[dom.length-1]; int[] result = new int[max+1]; for (int i=0; i<result.length; i++) result[i] = -1; // not used fields for (int i=0; i<dom.length; i++) result[dom[i]] = i; return result; } public static String[] toStringMap(int[] dom) { String[] result = new String[dom.length]; for (int i=0; i<dom.length; i++) result[i] = String.valueOf(dom[i]); return result; } public static int[] compose(int[] first, int[] transf) { for (int i=0; i<first.length; i++) { if (first[i]!=-1) first[i] = transf[first[i]]; } return first; } private static final DecimalFormat default_dformat = new DecimalFormat("0. public static String pprint(double[][] arr){ return pprint(arr,default_dformat); } // pretty print Matrix(2D array of doubles) public static String pprint(double[][] arr,DecimalFormat dformat) { int colDim = 0; for( double[] line : arr ) colDim = Math.max(colDim, line.length); StringBuilder sb = new StringBuilder(); int max_width = 0; int[] ilengths = new int[colDim]; Arrays.fill(ilengths, -1); for( double[] line : arr ) { for( int c = 0; c < line.length; ++c ) { double d = line[c]; String dStr = dformat.format(d); if( dStr.indexOf('.') == -1 ) dStr += ".0"; ilengths[c] = Math.max(ilengths[c], dStr.indexOf('.')); int prefix = (d >= 0 ? 1 : 2); max_width = Math.max(dStr.length() + prefix, max_width); } } for( double[] line : arr ) { for( int c = 0; c < line.length; ++c ) { double d = line[c]; String dStr = dformat.format(d); if( dStr.indexOf('.') == -1 ) dStr += ".0"; for( int x = dStr.indexOf('.'); x < ilengths[c] + 1; ++x ) sb.append(' '); sb.append(dStr); if( dStr.indexOf('.') == -1 ) sb.append('.'); for( int i = dStr.length() - Math.max(0, dStr.indexOf('.')); i <= 5; ++i ) sb.append('0'); } sb.append("\n"); } return sb.toString(); } static public boolean isEmpty(int[] a) { return a==null || a.length == 0; } static public boolean contains(int[] a, int d) { for(int i=0; i<a.length; i++) if (a[i]==d) return true; return false; } static public int[] difference(int a[], int b[]) { int[] r = new int[a.length]; int cnt = 0; for (int i=0; i<a.length; i++) { if (!contains(b, a[i])) r[cnt++] = a[i]; } return Arrays.copyOf(r, cnt); } /** Generates sequence <start, stop) of integers: (start, start+1, ...., stop-1) */ static public int[] seq(int start, int stop) { assert start<stop; int len = stop-start; int[] res = new int[len]; for(int i=start; i<stop;i++) res[i-start] = i; return res; } public static String className(String path) { return path.replace('\\', '/').replace('/', '.').substring(0, path.length() - 6); } public static double avg(double[] nums) { double sum = 0; for(double n: nums) sum+=n; return sum/nums.length; } public static double avg(long[] nums) { long sum = 0; for(long n: nums) sum+=n; return sum/nums.length; } public static float[] div(float[] nums, int n) { for (int i=0; i<nums.length; i++) nums[i] = nums[i] / n; return nums; } public static float[] div(float[] nums, float n) { for (int i=0; i<nums.length; i++) nums[i] = nums[i] / n; return nums; } }
package test.java.javamain; import com.sun.star.comp.loader.FactoryHelper; import com.sun.star.lang.XMain; import com.sun.star.lang.XMultiServiceFactory; import com.sun.star.lang.XSingleServiceFactory; import com.sun.star.registry.XRegistryKey; import com.sun.star.uno.XComponentContext; import test.java.tester.Tester; public final class JavaMain implements XMain { public JavaMain(XComponentContext context) { this.context = context; } public int run(String[] arguments) { Tester.test(context); return 0; } public static boolean __writeRegistryServiceInfo(XRegistryKey key) { return FactoryHelper.writeRegistryServiceInfo( IMPLEMENTATION_NAME, SERVICE_NAME, key); } public static XSingleServiceFactory __getServiceFactory( String name, XMultiServiceFactory factory, XRegistryKey key) { if (name.equals(IMPLEMENTATION_NAME)) { return FactoryHelper.getServiceFactory( JavaMain.class, SERVICE_NAME, factory, key); } else { return null; } } private static final String IMPLEMENTATION_NAME = "test.java.javamain.Component"; private static final String SERVICE_NAME = "test.dummy.JavaMain"; private final XComponentContext context; }
package org.neo4j.kernel.impl.ha; import org.neo4j.graphdb.GraphDatabaseService; public interface Broker { void invalidateMaster(); Master getMaster(); void setLastCommittedTxId( long txId ); boolean thisIsMaster(); int getMyMachineId(); // I know... this isn't supposed to be here Object instantiateMasterServer( GraphDatabaseService graphDb ); void shutdown(); }
package com.adyen.v6.commands; import java.util.Date; import org.apache.log4j.Logger; import com.adyen.model.modification.ModificationResult; import com.adyen.v6.factory.AdyenPaymentServiceFactory; import com.adyen.v6.repository.BaseStoreRepository; import com.adyen.v6.service.AdyenPaymentService; import de.hybris.platform.payment.commands.VoidCommand; import de.hybris.platform.payment.commands.request.VoidRequest; import de.hybris.platform.payment.commands.result.VoidResult; import de.hybris.platform.payment.dto.TransactionStatus; import de.hybris.platform.payment.dto.TransactionStatusDetails; import de.hybris.platform.store.BaseStoreModel; /** * Issues a Cancel request */ public class AdyenVoidCommand implements VoidCommand { private static final Logger LOG = Logger.getLogger(AdyenVoidCommand.class); private final String CANCELORREFUND_RECEIVED_RESPONSE = "[cancelOrRefund-received]"; private AdyenPaymentServiceFactory adyenPaymentServiceFactory; private BaseStoreRepository baseStoreRepository; @Override public VoidResult perform(VoidRequest request) { LOG.info("Cancellation request received " + request.getRequestId() + ", " + request.getRequestToken()); VoidResult result = new VoidResult(); result.setRequestTime(new Date()); result.setTransactionStatus(TransactionStatus.ERROR); result.setTransactionStatusDetails(TransactionStatusDetails.UNKNOWN_CODE); result.setAmount(request.getTotalAmount()); result.setCurrency(request.getCurrency()); String authReference = request.getRequestId(); String reference = request.getRequestToken(); BaseStoreModel baseStore = baseStoreRepository.findByOrder(reference); if (baseStore == null) { return result; } AdyenPaymentService adyenPaymentService = adyenPaymentServiceFactory.createFromBaseStore(baseStore); try { ModificationResult modificationResult = adyenPaymentService.cancelOrRefund(authReference, reference); if (CANCELORREFUND_RECEIVED_RESPONSE.equals(modificationResult.getResponse())) { result.setTransactionStatus(TransactionStatus.ACCEPTED); result.setTransactionStatusDetails(TransactionStatusDetails.REVIEW_NEEDED); } else { result.setTransactionStatus(TransactionStatus.REJECTED); result.setTransactionStatusDetails(TransactionStatusDetails.UNKNOWN_CODE); } } catch (Exception e) { LOG.error("Cancellation exception", e); } LOG.info("Cancellation status: " + result.getTransactionStatus().name() + ":" + result.getTransactionStatusDetails().name()); return result; } public AdyenPaymentServiceFactory getAdyenPaymentServiceFactory() { return adyenPaymentServiceFactory; } public void setAdyenPaymentServiceFactory(AdyenPaymentServiceFactory adyenPaymentServiceFactory) { this.adyenPaymentServiceFactory = adyenPaymentServiceFactory; } public BaseStoreRepository getBaseStoreRepository() { return baseStoreRepository; } public void setBaseStoreRepository(BaseStoreRepository baseStoreRepository) { this.baseStoreRepository = baseStoreRepository; } }
package koopa.app.components.overview; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Point; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.File; import java.io.IOException; import java.util.LinkedList; import java.util.List; import javax.swing.JPanel; import javax.swing.JProgressBar; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.ListSelectionModel; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import koopa.app.Application; import koopa.app.ApplicationSupport; import koopa.app.Configurable; import koopa.app.actions.ParsingProvider; import koopa.app.batchit.BatchResults; import koopa.app.batchit.ParseDetails; import koopa.app.components.detailstable.DetailsTable; import koopa.app.components.detailstable.DetailsTableListener; import koopa.app.components.misc.DecimalFormattingRenderer; import koopa.app.components.misc.StatusRenderer; import koopa.parsers.ParseResults; import koopa.parsers.cobol.ParsingCoordinator; import koopa.parsers.cobol.ParsingListener; import koopa.tokenizers.cobol.SourceFormat; import koopa.tokenizers.generic.IntermediateTokenizer; import koopa.tokens.Token; import koopa.util.Tuple; import org.jdesktop.swingx.JXTable; import org.jdesktop.swingx.decorator.HighlighterFactory; @SuppressWarnings("serial") public class Overview extends JPanel implements ParsingProvider, Configurable { private Application application = null; private JProgressBar progress = null; private BatchResults results = new BatchResults(); private ParseDetails parseDetails = new ParseDetails(); private ParsingCoordinator coordinator = null; private boolean parsing = false; private boolean quitParsing = false; public Overview(Application application) { this.application = application; coordinator = new ParsingCoordinator(); coordinator.setKeepingTrackOfTokens(true); // TODO Can do this better, I think. ApplicationSupport.configureFromProperties("batching.properties", this); setLayout(new BorderLayout()); setupComponents(); setupProgressBar(); setBorder(null); } private void setupProgressBar() { progress = new JProgressBar(); progress.setStringPainted(true); progress.setString("no parsing in progress"); add(progress, BorderLayout.SOUTH); } private void setupComponents() { final JXTable overviewTable = new JXTable(); overviewTable.setBorder(null); overviewTable.setModel(results); overviewTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); overviewTable .setHighlighters(HighlighterFactory.createSimpleStriping()); overviewTable.getColumnModel().getColumn(BatchResults.STATUS_COLUMN) .setPreferredWidth(70); overviewTable.getColumnModel().getColumn(BatchResults.ERRORS_COLUMN) .setPreferredWidth(70); overviewTable.getColumnModel().getColumn(BatchResults.WARNINGS_COLUMN) .setPreferredWidth(70); overviewTable.getColumnModel() .getColumn(BatchResults.TOKEN_COUNT_COLUMN) .setPreferredWidth(70); overviewTable.getColumnModel().getColumn(BatchResults.COVERAGE_COLUMN) .setPreferredWidth(70); overviewTable.getColumnModel().getColumn(BatchResults.FILE_COLUMN) .setPreferredWidth(150); overviewTable.getColumnModel().getColumn(BatchResults.PATH_COLUMN) .setPreferredWidth(600); overviewTable.getColumnModel().getColumn(BatchResults.STATUS_COLUMN) .setCellRenderer(new StatusRenderer()); overviewTable.getColumnModel().getColumn(BatchResults.COVERAGE_COLUMN) .setCellRenderer(new DecimalFormattingRenderer("0.0")); JScrollPane overviewScroll = new JScrollPane(overviewTable); overviewScroll.setBorder(null); final DetailsTable detailsTable = new DetailsTable(parseDetails); detailsTable.addListener(new DetailsTableListener() { @Override public void userSelectedDetail(Tuple<Token, String> detail) { final int selected = overviewTable .convertRowIndexToModel(overviewTable.getSelectedRow()); final File file = results.getResults(selected).getFile(); application.openFile(file, coordinator.getFormat(), detail); } }); JScrollPane detailsScroll = new JScrollPane(detailsTable); detailsScroll.setBorder(null); JSplitPane split = new JSplitPane(JSplitPane.VERTICAL_SPLIT, overviewScroll, detailsScroll); split.setResizeWeight(0.8); add(split, BorderLayout.CENTER); overviewTable.getSelectionModel().addListSelectionListener( new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { if (!e.getValueIsAdjusting()) { final int selected = overviewTable .convertRowIndexToModel(overviewTable .getSelectedRow()); if (selected >= 0) { parseDetails.setParseResults(results .getResults(selected)); } } } }); overviewTable.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) { int row = overviewTable.rowAtPoint(new Point(e.getX(), e .getY())); if (row >= 0) { final int selected = overviewTable .convertRowIndexToModel(row); final File file = results.getResults(selected) .getFile(); application.openFile(file, coordinator.getFormat()); } } } }); } public boolean isParsing() { return parsing; } public void walkAndParse(File file) { if (parsing) return; try { parsing = true; quitParsing = false; application.walkingAndParsing(); progress.setIndeterminate(true); List<File> targets = new LinkedList<File>(); walk(file, targets); progress.setValue(0); progress.setMaximum(targets.size()); progress.setIndeterminate(false); int count = 0; int ok = 0; int withWarning = 0; int withError = 0; for (File target : targets) { ParseResults results = parse(target); if (results.getErrorCount() > 0) withError += 1; else if (results.getWarningCount() > 0) withWarning += 1; else ok += 1; progress.setValue(++count); progress.setString("Parsing: " + ok + " ok, " + withWarning + " with warnings, " + withError + " in error"); if (quitParsing) { progress.setValue(0); break; } } if (quitParsing) progress.setString("Parsing aborted: " + ok + " ok, " + withWarning + " with warnings, " + withError + " in error"); else progress.setString("Parsing done: " + ok + " ok, " + withWarning + " with warnings, " + withError + " in error"); } finally { parsing = false; application.doneWalkingAndParsing(); } } private void walk(File file, List<File> targets) { if (file == null || !file.exists()) { return; } if (file.isDirectory()) { for (File child : file.listFiles()) { walk(child, targets); } return; } if (ApplicationSupport.isCobolFile(file)) { targets.add(file); } } private ParseResults parse(File file) { try { final ParseResults parseResults = coordinator.parse(file); results.add(parseResults); return parseResults; } catch (IOException e) { ParseResults failed = new ParseResults(file); failed.setValidInput(false); failed.addError(null, e.getMessage()); results.add(failed); e.printStackTrace(); return failed; } } public void addParseResults(ParseResults parseResults) { results.add(parseResults.copy()); } public Component getGUI() { return this; } public void setOption(String name, String value) { if (name.startsWith("parsing-listener")) { installParsingListener(value); } else if (name.startsWith("intermediate-tokenizer")) { installIntermediateTokenizer(value); } } private void installIntermediateTokenizer(String classname) { try { Class<?> clazz = Class.forName(classname); Object o = clazz.newInstance(); if (o instanceof IntermediateTokenizer) { coordinator.addIntermediateTokenizer((IntermediateTokenizer) o); } } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void installParsingListener(String classname) { try { Class<?> clazz = Class.forName(classname); Object o = clazz.newInstance(); if (o instanceof ParsingListener) { coordinator.addParsingListener((ParsingListener) o); } } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void clearResults() { results.clear(); parseDetails.setParseResults(null); application.resultsWereCleared(); } public BatchResults getResults() { return results; } public SourceFormat getSourceFormat() { return coordinator.getFormat(); } public void setSourceFormat(SourceFormat format) { coordinator.setFormat(format); } public void quitParsing() { quitParsing = true; } }
package io.github.emanual.java.app.ui; import io.github.emanual.java.app.CoreService; import io.github.emanual.java.app.R; import io.github.emanual.java.app.adapter.MainFragmentPagerAdapter; import io.github.emanual.java.app.fragment.NewFeeds; import io.github.emanual.java.app.fragment.ResourceCenter; import io.github.emanual.java.app.widget.NewVersionDialog; import java.util.ArrayList; import java.util.List; import android.app.ActionBar; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.view.ViewPager; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import butterknife.ButterKnife; import butterknife.InjectView; import com.astuetz.PagerSlidingTabStrip; public class Main extends BaseActivity { ActionBar mActionBar; @InjectView(R.id.tabs) PagerSlidingTabStrip tabs; @InjectView(R.id.viewpager) ViewPager viewPager; List<Fragment> fragments = new ArrayList<Fragment>(); String[] titles; NewVersionDialog dialog; MainBroadcastReceiver mReceiver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.acty_main); ButterKnife.inject(this); initData(); initLayout(); mReceiver = new MainBroadcastReceiver(); IntentFilter filter = new IntentFilter(); filter.addAction(CoreService.Action_CheckVersion); registerReceiver(mReceiver, filter); Intent service = new Intent(getContext(), CoreService.class); service.setAction(CoreService.Action_CheckVersion); startService(service); } @Override protected void onDestroy() { super.onDestroy(); if(mReceiver != null) unregisterReceiver(mReceiver); } @Override protected void initData() { titles = getResources().getStringArray(R.array.title_main); } @Override protected void initLayout() { mActionBar = getActionBar(); fragments.add(new NewFeeds()); fragments.add(new ResourceCenter()); if(viewPager == null)Log.d("debug", "viewPager is null"); viewPager.setAdapter(new MainFragmentPagerAdapter( getSupportFragmentManager(), fragments, titles)); tabs.setViewPager(viewPager); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_about: startActivity(new Intent(getContext(), About.class)); return true; case R.id.action_favourite: startActivity(new Intent(getContext(), FavouriteList.class)); return true; default: return super.onOptionsItemSelected(item); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } class MainBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(CoreService.Action_CheckVersion)) { String description = intent.getStringExtra("description"); String url = intent.getStringExtra("url"); if (dialog == null) dialog = new NewVersionDialog(getContext(), description, url); dialog.show(); } } } }
package cs.spectrum; import android.Manifest; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.Point; import android.graphics.RectF; import android.graphics.drawable.BitmapDrawable; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.os.Parcel; import android.provider.MediaStore; import android.provider.Settings; import android.support.design.widget.Snackbar; import android.support.v4.app.ActivityCompat; import android.support.v4.content.FileProvider; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Display; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.widget.Button; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import android.util.Log; import android.widget.ImageView.ScaleType; import com.google.android.gms.common.api.GoogleApiClient; import com.squareup.picasso.Picasso; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Random; import uk.co.senab.photoview.PhotoView; import uk.co.senab.photoview.PhotoViewAttacher; import uk.co.senab.photoview.PhotoViewAttacher.OnMatrixChangedListener; import uk.co.senab.photoview.PhotoViewAttacher.OnPhotoTapListener; import static android.os.Environment.getExternalStoragePublicDirectory; public class MainActivity extends AppCompatActivity { /* start touch variables */ private static final String DEBUG_TAG = "SJL"; private final float TOUCH_SCALE_FACTOR = 180.0f / 320; private static final int RESULT_TAKE_PHOTO = 1; private static final int RESULT_LOAD_IMG = 2; private static final int RESIZED_IMG_WIDTH = 1080; //pixel width and height of device private static int DISPLAY_WIDTH; private static int DISPLAY_HEIGHT; //pixel width and height of primaryImage imageView private static int PRIMARY_IMAGE_VIEW_WIDTH; private static int PRIMARY_IMAGE_VIEW_HEIGHT; //pixel width and height of bitmap loaded into primaryImage private static int BITMAP_IMAGE_VIEW_WIDTH; private static int BITMAP_IMAGE_VIEW_HEIGHT; private Uri mCurrentPhotoUri = null; private PhotoView photoView; static final String PHOTO_TAP_TOAST_STRING = "Photo Tap! X: %.2f %% Y:%.2f %% ID: %d"; static final String SCALE_TOAST_STRING = "Scaled to: %.2ff"; static final String FLING_LOG_STRING = "Fling velocityX: %.2f, velocityY: %.2f"; private TextView mCurrMatrixTv; private PhotoViewAttacher mAttacher; private Toast mCurrentToast; private Matrix mCurrentDisplayMatrix = null; private final String[] PERMISSIONS = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}; private final int PERMISSION_ALL = 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); if (!hasPermissions(this, PERMISSIONS)){ ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_ALL); } getDisplaySize(); //BUG PhotoView mImageView = (PhotoView) findViewById(R.id.primaryImage); mCurrMatrixTv = (TextView) findViewById(R.id.tv_current_matrix); // The MAGIC happens here! mAttacher = new PhotoViewAttacher(mImageView); mAttacher.setOnMatrixChangeListener(new MatrixChangeListener()); mAttacher.setOnPhotoTapListener(new PhotoTapListener()); mAttacher.setOnSingleFlingListener(new SingleFlingListener()); ImageButton cameraButton = (ImageButton) findViewById(R.id.cameraButton); ImageButton importButton = (ImageButton) findViewById(R.id.importButton); //cameraButton listener cameraButton.setOnClickListener( new View.OnClickListener() { @Override public void onClick( View view ) { dispatchTakePictureIntent(); } }); //import button listener importButton.setOnClickListener( new View.OnClickListener() { @Override public void onClick( View view ) { loadImageFromGallery( view ); } }); photoView = (PhotoView) findViewById(R.id.primaryImage); if (savedInstanceState != null) { System.out.println("LOADING URI" ); mCurrentPhotoUri = savedInstanceState.getParcelable("imageUri"); System.out.println("Reloading image."); Picasso .with(photoView.getContext()) .load(mCurrentPhotoUri) .error(R.mipmap.ic_failed) .resize(DISPLAY_WIDTH,0) .onlyScaleDown() .into(photoView); } } @Override public void onSaveInstanceState(Bundle outState) { outState.putParcelable("imageUri", mCurrentPhotoUri); super.onSaveInstanceState(outState); } @Override public void onDestroy() { super.onDestroy(); mAttacher.cleanup(); } private class PhotoTapListener implements OnPhotoTapListener { @Override public void onPhotoTap(View view, float x, float y) { float xPercentage = x * 100f; float yPercentage = y * 100f; showToast(String.format(PHOTO_TAP_TOAST_STRING, xPercentage, yPercentage, view == null ? 0 : view.getId())); getColorInfo(view, x, y); } @Override public void onOutsidePhotoTap() { showToast("Please tap within the image."); } } private void showToast(CharSequence text) { if (null != mCurrentToast) { mCurrentToast.cancel(); } mCurrentToast = Toast.makeText(MainActivity.this, text, Toast.LENGTH_SHORT); mCurrentToast.show(); } private class MatrixChangeListener implements OnMatrixChangedListener { @Override public void onMatrixChanged(RectF rect) { mCurrMatrixTv.setText(rect.toString()); } } private class SingleFlingListener implements PhotoViewAttacher.OnSingleFlingListener { @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { if (BuildConfig.DEBUG) { Log.d("PhotoView", String.format(FLING_LOG_STRING, velocityX, velocityY)); } return true; } } @Override public boolean onPrepareOptionsMenu(Menu menu) { MenuItem zoomToggle = menu.findItem(R.id.menu_zoom_toggle); assert null != zoomToggle; zoomToggle.setTitle(mAttacher.canZoom() ? R.string.menu_zoom_disable : R.string.menu_zoom_enable); return super.onPrepareOptionsMenu(menu); } private void getDisplaySize(){ //BUG Display display = getWindowManager().getDefaultDisplay(); Point size = new Point(); display.getSize(size); DISPLAY_WIDTH = size.x; DISPLAY_HEIGHT = size.y; System.out.println("Display width x height: " + DISPLAY_WIDTH + " x " + DISPLAY_HEIGHT); } @Override public boolean onOptionsItemSelected(MenuItem item) { ImageButton cameraButton; ImageButton importButton; switch (item.getItemId()) { case R.id.action_Hide_Buttons: cameraButton = (ImageButton)findViewById(R.id.cameraButton); importButton = (ImageButton)findViewById(R.id.importButton); cameraButton.setVisibility(View.GONE); importButton.setVisibility(View.GONE); return true; case R.id.action_Show_Buttons: cameraButton = (ImageButton)findViewById(R.id.cameraButton); importButton = (ImageButton)findViewById(R.id.importButton); cameraButton.setVisibility(View.VISIBLE); importButton.setVisibility(View.VISIBLE); return true; case R.id.menu_zoom_toggle: mAttacher.setZoomable(!mAttacher.canZoom()); return true; case R.id.menu_scale_fit_center: mAttacher.setScaleType(ScaleType.FIT_CENTER); return true; case R.id.menu_scale_fit_start: mAttacher.setScaleType(ScaleType.FIT_START); return true; case R.id.menu_scale_fit_end: mAttacher.setScaleType(ScaleType.FIT_END); return true; case R.id.menu_scale_fit_xy: mAttacher.setScaleType(ScaleType.FIT_XY); return true; case R.id.menu_scale_scale_center: mAttacher.setScaleType(ScaleType.CENTER); return true; case R.id.menu_scale_scale_center_crop: mAttacher.setScaleType(ScaleType.CENTER_CROP); return true; case R.id.menu_scale_scale_center_inside: mAttacher.setScaleType(ScaleType.CENTER_INSIDE); return true; case R.id.menu_scale_random_animate: case R.id.menu_scale_random: Random r = new Random(); float minScale = mAttacher.getMinimumScale(); float maxScale = mAttacher.getMaximumScale(); float randomScale = minScale + (r.nextFloat() * (maxScale - minScale)); mAttacher.setScale(randomScale, item.getItemId() == R.id.menu_scale_random_animate); showToast(String.format(SCALE_TOAST_STRING, randomScale)); return true; } return super.onOptionsItemSelected(item); } private void dispatchTakePictureIntent() { Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); // Ensure that there's a camera activity to handle the intent if (takePictureIntent.resolveActivity(getPackageManager()) != null) { // Create the File where the photo should go File photoFile = null; try { photoFile = createImageFile(); } catch (IOException ex) { // Error occurred while creating the File } // Continue only if the File was successfully created if (photoFile != null) { Uri photoURI = FileProvider.getUriForFile(this, "cs.spectrum.fileprovider", photoFile); mCurrentPhotoUri = photoURI; takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI); startActivityForResult(takePictureIntent, RESULT_TAKE_PHOTO); System.out.println("Picture taken."); } } } public void loadImageFromGallery(View view) { // Create intent to Open Image applications like Gallery, Google Photos Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); // Start the Intent startActivityForResult(galleryIntent, RESULT_LOAD_IMG); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); try { photoView = (PhotoView) findViewById(R.id.primaryImage); // When an Image is picked from gallery if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK && null != data) { // Get the Image from data Uri selectedImage = data.getData(); // Set the Image in ImageView after resizing if too large Picasso .with(photoView.getContext()) .load(selectedImage) .error(R.mipmap.ic_failed) .resize(DISPLAY_WIDTH,0) .onlyScaleDown() .into(photoView); mCurrentPhotoUri = selectedImage; // When an image is taken from camera } else if (requestCode == RESULT_TAKE_PHOTO && resultCode == RESULT_OK){ // Set the Image in ImageView after resizing if too large Picasso .with(photoView.getContext()) .load(mCurrentPhotoUri) .error(R.mipmap.ic_failed) .rotate(90) .resize(DISPLAY_WIDTH,0) .onlyScaleDown() .into(photoView); } else { Toast.makeText(this, "You haven't selected an image.", Toast.LENGTH_LONG).show(); } PRIMARY_IMAGE_VIEW_HEIGHT = photoView.getHeight(); PRIMARY_IMAGE_VIEW_WIDTH = photoView.getWidth(); } catch (Exception e) { System.out.println("******************************************************"); e.printStackTrace(); System.out.println("******************************************************"); Toast.makeText(this, "Something went wrong.", Toast.LENGTH_LONG) .show(); } } //returns a unique filename using a date-time stamp private File createImageFile() throws IOException { // Create an image file name String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); String imageFileName = "JPEG_" + timeStamp + "_"; File storageDir = getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES); File image = File.createTempFile( imageFileName, /* prefix */ ".jpg", /* suffix */ storageDir /* directory */ ); return image; } public static boolean hasPermissions(Context context, String... permissions) { if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) { for (String permission : permissions) { if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) { return false; } } } return true; } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } private void getColorInfo( View v, float x, float y) { Bitmap bitmap = ((BitmapDrawable) photoView.getDrawable()).getBitmap(); /* debug */ String resolution = "h:" + bitmap.getHeight() + " x:" + bitmap.getWidth(); System.out.println(resolution); /* debug */ int tap_location_x = (int)(bitmap.getWidth() * x); int tap_location_y = (int)(bitmap.getHeight()* y); String tap_location = "x: " + tap_location_x + " y: " + tap_location_y; System.out.println(tap_location); try { int pixel = bitmap.getPixel(tap_location_x, tap_location_y); //touched pixel int red = Color.red(pixel); int green = Color.green(pixel); int blue = Color.blue(pixel); /* //totals to be used for averaging int redTotal = 0; int greenTotal = 0; int blueTotal = 0; //square property setup for gathering pixel info int squareWidth = Math.round(DISPLAY_WIDTH * .05f); //square width is 5% of screen size int numPixels = Math.round((float)Math.pow(squareWidth, 2)); //number of pixels in square int offset = (int)Math.floor((float)squareWidth/2.0f); System.out.println("Square width: " + squareWidth); System.out.println("Number of pixels in square: " + numPixels); System.out.println("offset: " + offset); for (int i = x - offset; i < x + offset; i++) { for (int j = y - offset; j < y + offset; j++) { //totalling the RGB values redTotal += Color.red(bitmap.getPixel(i,j)); greenTotal += Color.green(bitmap.getPixel(i,j)); blueTotal += Color.blue(bitmap.getPixel(i,j)); } } System.out.println("Red Total: " + redTotal + " Green Total: " + greenTotal + " Blue Total: " + blueTotal); //calculating average values int avgRed = redTotal/numPixels; int avgGreen = greenTotal/numPixels; int avgBlue = blueTotal/numPixels; System.out.println("Average Red: " + avgRed); System.out.println("Average Green: " + avgGreen); System.out.println("Average Blue: " + avgBlue); */ String color = "R: " + red + " B: " + blue + " G: " + green; final Snackbar alert = Snackbar.make(findViewById(R.id.primaryImage), color, Snackbar.LENGTH_INDEFINITE).setActionTextColor(Color.parseColor("#bbbbbb")); View snackBarView = alert.getView(); snackBarView.setBackgroundColor(Color.parseColor("#313031")); alert.setAction("Dismiss", new View.OnClickListener() { @Override public void onClick(View v) { alert.dismiss(); } }); alert.show(); } catch (Exception e) { System.out.println("getColor died, may it RIP"); e.printStackTrace(); } } }
package cs.spectrum; import android.Manifest; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.Point; import android.graphics.drawable.BitmapDrawable; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.os.Parcel; import android.provider.MediaStore; import android.provider.Settings; import android.support.design.widget.Snackbar; import android.support.v4.app.ActivityCompat; import android.support.v4.content.FileProvider; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Display; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.widget.Button; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.Toast; import android.util.Log; import com.squareup.picasso.Picasso; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import uk.co.senab.photoview.PhotoView; import uk.co.senab.photoview.PhotoViewAttacher; import static android.os.Environment.getExternalStoragePublicDirectory; public class MainActivity extends AppCompatActivity { /* start touch variables */ private static final String DEBUG_TAG = "SJL"; private final float TOUCH_SCALE_FACTOR = 180.0f / 320; private static final int RESULT_TAKE_PHOTO = 1; private static final int RESULT_LOAD_IMG = 2; private static final int RESIZED_IMG_WIDTH = 1080; //pixel width and height of device private static int DISPLAY_WIDTH; private static int DISPLAY_HEIGHT; //pixel width and height of primaryImage imageView private static int PRIMARY_IMAGE_VIEW_WIDTH; private static int PRIMARY_IMAGE_VIEW_HEIGHT; //pixel width and height of bitmap loaded into primaryImage private static int BITMAP_IMAGE_VIEW_WIDTH; private static int BITMAP_IMAGE_VIEW_HEIGHT; private Uri mCurrentPhotoUri = null; private ImageView imgView; private PhotoViewAttacher mAttacher; private final String[] PERMISSIONS = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}; private final int PERMISSION_ALL = 1; //value after request granted @Override public void onSaveInstanceState(Bundle outState) { outState.putParcelable("imageUri", mCurrentPhotoUri); super.onSaveInstanceState(outState); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); if (!hasPermissions(this, PERMISSIONS)){ ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_ALL); } getDisplaySize(); ImageButton cameraButton = (ImageButton) findViewById(R.id.cameraButton); ImageButton importButton = (ImageButton) findViewById(R.id.importButton); //cameraButton listener cameraButton.setOnClickListener( new View.OnClickListener() { @Override public void onClick( View view ) { dispatchTakePictureIntent(); } }); //import button listener importButton.setOnClickListener( new View.OnClickListener() { @Override public void onClick( View view ) { loadImageFromGallery( view ); } }); imgView = (ImageView) findViewById(R.id.primaryImage); mAttacher = new PhotoViewAttacher(imgView); mAttacher.update(); //addTouchListener(); // stephen if (savedInstanceState != null) { System.out.println("LOADING URI" ); mCurrentPhotoUri = savedInstanceState.getParcelable("imageUri"); System.out.println("Reloading image."); Picasso .with(imgView.getContext()) .load(mCurrentPhotoUri) .error(R.mipmap.ic_failed) .resize(DISPLAY_WIDTH,0) .onlyScaleDown() .into(imgView); //reloadImage(mCurrentPhotoUri); } } private void getDisplaySize(){ Display display = getWindowManager().getDefaultDisplay(); Point size = new Point(); display.getSize(size); DISPLAY_WIDTH = size.x; DISPLAY_HEIGHT = size.y; System.out.println("Display width x height: " + DISPLAY_WIDTH + " x " + DISPLAY_HEIGHT); } /* start touch functions */ private void addTouchListener() { imgView = (ImageView)findViewById(R.id.primaryImage); imgView.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_UP) { //only runs the following code when finger is lifted try { ImageView image = (ImageView)findViewById(R.id.primaryImage); float[] coord = getPointerCoords(image,event); System.out.println(coord[0] + ", " + coord[1]); int X_Image = Math.round(coord[0]); int Y_Image = Math.round(coord[1]); getBitmapSize(v); System.out.println("Get colors of: (" + X_Image + ", " + Y_Image + ")"); if (X_Image <= BITMAP_IMAGE_VIEW_WIDTH && Y_Image <= BITMAP_IMAGE_VIEW_HEIGHT ) { getColorInfo(v, X_Image,Y_Image); } else { Toast.makeText(getApplicationContext(), "Touched outside of image.", Toast.LENGTH_SHORT).show(); } } catch (Exception e) { } } return false; } }); } final float[] getPointerCoords(ImageView view, MotionEvent e) { final int index = e.getActionIndex(); final float[] coords = new float[] { e.getX(index), e.getY(index) }; Matrix matrix = new Matrix(); view.getImageMatrix().invert(matrix); matrix.postTranslate(view.getScrollX(), view.getScrollY()); matrix.mapPoints(coords); return coords; } public boolean onTouchEvent(MotionEvent e) { float x = e.getX(); float y = e.getY(); switch (e.getAction()) { case MotionEvent.ACTION_DOWN: System.out.print("Pressed"); } return true; } /* end touch functions */ private void dispatchTakePictureIntent() { Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); // Ensure that there's a camera activity to handle the intent if (takePictureIntent.resolveActivity(getPackageManager()) != null) { // Create the File where the photo should go File photoFile = null; try { photoFile = createImageFile(); } catch (IOException ex) { // Error occurred while creating the File } // Continue only if the File was successfully created if (photoFile != null) { Uri photoURI = FileProvider.getUriForFile(this, "cs.spectrum.fileprovider", photoFile); mCurrentPhotoUri = photoURI; takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI); startActivityForResult(takePictureIntent, RESULT_TAKE_PHOTO); System.out.println("Picture taken."); } } } public void loadImageFromGallery(View view) { // Create intent to Open Image applications like Gallery, Google Photos Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); // Start the Intent startActivityForResult(galleryIntent, RESULT_LOAD_IMG); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); try { imgView = (ImageView) findViewById(R.id.primaryImage); // When an Image is picked from gallery if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK && null != data) { // Get the Image from data Uri selectedImage = data.getData(); // Set the Image in ImageView after resizing if too large Picasso .with(imgView.getContext()) .load(selectedImage) .error(R.mipmap.ic_failed) .resize(DISPLAY_WIDTH,0) .onlyScaleDown() .into(imgView); mCurrentPhotoUri = selectedImage; // When an image is taken from camera } else if (requestCode == RESULT_TAKE_PHOTO && resultCode == RESULT_OK){ // Set the Image in ImageView after resizing if too large Picasso .with(imgView.getContext()) .load(mCurrentPhotoUri) .error(R.mipmap.ic_failed) .rotate(90) .resize(DISPLAY_WIDTH,0) .onlyScaleDown() .into(imgView); } else { Toast.makeText(this, "You haven't selected an image.", Toast.LENGTH_LONG).show(); } PRIMARY_IMAGE_VIEW_HEIGHT = imgView.getHeight(); PRIMARY_IMAGE_VIEW_WIDTH = imgView.getWidth(); } catch (Exception e) { System.out.println("******************************************************"); e.printStackTrace(); System.out.println("******************************************************"); Toast.makeText(this, "Something went wrong.", Toast.LENGTH_LONG) .show(); } } private void getBitmapSize( View v ) { ImageView imageView = ((ImageView) v); Bitmap bitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap(); BITMAP_IMAGE_VIEW_HEIGHT = bitmap.getHeight(); BITMAP_IMAGE_VIEW_WIDTH = bitmap.getWidth(); System.out.println("Bitmap Height: " + BITMAP_IMAGE_VIEW_HEIGHT); System.out.println("Bitmap Width: " + BITMAP_IMAGE_VIEW_WIDTH); } private void getColorInfo( View v, int x, int y){ ImageView imageView = ((ImageView)v); Bitmap bitmap = ((BitmapDrawable)imageView.getDrawable()).getBitmap(); System.out.println("BITMAP SIZE w x h: " + bitmap.getHeight() + " x " + bitmap.getWidth()); try { int pixel = bitmap.getPixel(x, y); //touched pixel int red = Color.red(pixel); int green = Color.green(pixel); int blue = Color.blue(pixel); //totals to be used for averaging int redTotal = 0; int greenTotal = 0; int blueTotal = 0; //square property setup for gathering pixel info int squareWidth = Math.round(DISPLAY_WIDTH * .05f); //square width is 5% of screen size int numPixels = Math.round((float)Math.pow(squareWidth, 2)); //number of pixels in square int offset = (int)Math.floor((float)squareWidth/2.0f); System.out.println("Square width: " + squareWidth); System.out.println("Number of pixels in square: " + numPixels); System.out.println("offset: " + offset); for (int i = x - offset; i < x + offset; i++) { for (int j = y - offset; j < y + offset; j++) { //totalling the RGB values redTotal += Color.red(bitmap.getPixel(i,j)); greenTotal += Color.green(bitmap.getPixel(i,j)); blueTotal += Color.blue(bitmap.getPixel(i,j)); } } System.out.println("Red Total: " + redTotal + " Green Total: " + greenTotal + " Blue Total: " + blueTotal); //calculating average values int avgRed = redTotal/numPixels; int avgGreen = greenTotal/numPixels; int avgBlue = blueTotal/numPixels; System.out.println("Average Red: " + avgRed); System.out.println("Average Green: " + avgGreen); System.out.println("Average Blue: " + avgBlue); System.out.println("Pixel Color: R " + red + " G " + green + " B " + blue); String message = "Average RGB: " + avgRed + ", " + avgGreen + ", " + avgBlue; final Snackbar alert = Snackbar.make(findViewById(R.id.primaryImage), message, Snackbar.LENGTH_INDEFINITE).setActionTextColor(Color.parseColor("#bbbbbb")); View snackBarView = alert.getView(); snackBarView.setBackgroundColor(Color.parseColor("#313031")); alert.setAction("Dismiss", new View.OnClickListener() { @Override public void onClick(View v) { alert.dismiss(); } }); alert.show(); } catch (Exception e){ System.out.println("EXCEPTION IN GETCOLORINFO."); e.printStackTrace(); } } //returns a unique filename using a date-time stamp private File createImageFile() throws IOException { // Create an image file name String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); String imageFileName = "JPEG_" + timeStamp + "_"; File storageDir = getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES); File image = File.createTempFile( imageFileName, /* prefix */ ".jpg", /* suffix */ storageDir /* directory */ ); return image; } public static boolean hasPermissions(Context context, String... permissions) { if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) { for (String permission : permissions) { if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) { return false; } } } return true; } //currently unused from default activity @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } //currently unused from default activity @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_Hide_Buttons) { ImageButton cameraButton = (ImageButton)findViewById(R.id.cameraButton); ImageButton importButton = (ImageButton)findViewById(R.id.importButton); cameraButton.setVisibility(View.GONE); importButton.setVisibility(View.GONE); } else if (id == R.id.action_Show_Buttons) { ImageButton cameraButton = (ImageButton)findViewById(R.id.cameraButton); ImageButton importButton = (ImageButton)findViewById(R.id.importButton); cameraButton.setVisibility(View.VISIBLE); importButton.setVisibility(View.VISIBLE); } return super.onOptionsItemSelected(item); } }
// Tapestry Web Application Framework // Howard Lewis Ship // mailto:hship@users.sf.net // This library is free software. // You may redistribute it and/or modify it under the terms of the GNU // included with this distribution, you may find a copy at the FSF web // Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139 USA. // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU package net.sf.tapestry.form; import java.sql.Date; import java.text.SimpleDateFormat; import java.util.Iterator; import java.util.Map; import net.sf.tapestry.BaseComponent; import net.sf.tapestry.IBinding; import net.sf.tapestry.IPage; import net.sf.tapestry.IRequestCycle; import net.sf.tapestry.RequestCycleException; /** * Provides a Form <tt>java.sql.Date</tt> field component for selecting dates. * * [<a href="../../../../../ComponentReference/DateEdit.html">Component Reference</a>] * * @author Paul Geertz * @author Malcolm Edgar * @version $Id$ */ public class DateEdit extends BaseComponent { private static final String FIRST_USE_ATTRIBUTE_KEY = "net.sf.tapestry.DateEdit-first"; private Date _value = new Date(System.currentTimeMillis()); private IBinding _valueBinding; private SimpleDateFormat _dateFormat = new SimpleDateFormat("dd MMM yyyy"); private boolean _firstTime; public IBinding getValueBinding() { return _valueBinding; } public void setValueBinding(IBinding value) { _valueBinding = value; } public Date readValue() { return (Date) (_valueBinding.getObject()); } public void updateValue(Date value) { _valueBinding.setObject(value); } public String getText() { return _dateFormat.format(_value); } public void setText(String text) { // ignore } /** * @return a <tt>String</tt> long value for the date * **/ public String getLongValue() { return Long.toString(_value.getTime()); } /** * <tt>setLongValue</tt> sets the long value of the date * * @param v a <tt>String</tt> value * **/ public void setLongValue(String v) { setValue(new Date(Long.parseLong(v))); } public Date getValue() { return _value; } public void setValue(Date value) { _value = value; updateValue(_value); } public void setFormat(String format) { _dateFormat = new SimpleDateFormat(format); } public String getFormat() { return _dateFormat.toPattern(); } public boolean isFirstTime() { return _firstTime; } protected void prepareForRender(IRequestCycle cycle) throws RequestCycleException { _firstTime = (cycle.getAttribute(FIRST_USE_ATTRIBUTE_KEY) == null); if (_firstTime) cycle.setAttribute(FIRST_USE_ATTRIBUTE_KEY, Boolean.TRUE); super.prepareForRender(cycle); } }
package com.mapswithme.maps.widget; import android.annotation.TargetApi; import android.content.Context; import android.content.res.Configuration; import android.content.res.Resources; import android.os.Build; import android.support.annotation.DrawableRes; import android.support.annotation.Nullable; import android.support.annotation.StringRes; import android.support.v4.view.ViewCompat; import android.support.v4.view.WindowInsetsCompat; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.TextView; import com.mapswithme.maps.R; import com.mapswithme.util.UiUtils; public class PlaceholderView extends FrameLayout { @Nullable private ImageView mImage; @Nullable private TextView mTitle; @Nullable private TextView mSubtitle; private final float mImageSizeFull; private final float mImageSizeSmall; private final float mPaddingImage; private final float mPaddingNoImage; private final float mScreenHeight; private final float mScreenWidth; private int mOrientation; public PlaceholderView(Context context) { this(context, null, 0, 0); } public PlaceholderView(Context context, @Nullable AttributeSet attrs) { this(context, attrs, 0, 0); } public PlaceholderView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { this(context, attrs, defStyleAttr, 0); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) public PlaceholderView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); Resources res = getResources(); mImageSizeFull = res.getDimension(R.dimen.placeholder_size); mImageSizeSmall = res.getDimension(R.dimen.placeholder_size_small); mPaddingImage = res.getDimension(R.dimen.placeholder_margin_top); mPaddingNoImage = res.getDimension(R.dimen.placeholder_margin_top_no_image); mScreenHeight = res.getDisplayMetrics().heightPixels; mScreenWidth = res.getDisplayMetrics().widthPixels; LayoutInflater.from(context).inflate(R.layout.placeholder, this, true); } @Override protected void onFinishInflate() { super.onFinishInflate(); mImage = (ImageView) findViewById(R.id.image); mTitle = (TextView) findViewById(R.id.title); mSubtitle = (TextView) findViewById(R.id.subtitle); ViewCompat.setOnApplyWindowInsetsListener(this, new android.support.v4.view.OnApplyWindowInsetsListener() { @Override public WindowInsetsCompat onApplyWindowInsets(View v, WindowInsetsCompat insets) { int height = (int) (mOrientation == Configuration.ORIENTATION_LANDSCAPE ? mScreenWidth : mScreenHeight); int[] location = new int[2]; getLocationOnScreen(location); ViewGroup.LayoutParams lp = getLayoutParams(); lp.height = height - insets.getSystemWindowInsetBottom() - location[1]; setLayoutParams(lp); return insets; } }); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { //isInEditMode() need for correct editor visualization if (isInEditMode() || mImage == null) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); return; } if (mOrientation == Configuration.ORIENTATION_LANDSCAPE) { UiUtils.hide(mImage); setPadding(getPaddingLeft(), (int) mPaddingNoImage, getPaddingRight(), getPaddingBottom()); super.onMeasure(widthMeasureSpec, heightMeasureSpec); return; } setPadding(getPaddingLeft(), (int) mPaddingImage, getPaddingRight(), getPaddingBottom()); UiUtils.show(mImage); ViewGroup.LayoutParams lp = mImage.getLayoutParams(); lp.width = (int) mImageSizeFull; lp.height = (int) mImageSizeFull; mImage.setLayoutParams(lp); super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)); if (getMeasuredHeight() > MeasureSpec.getSize(heightMeasureSpec)) { lp.width = (int) mImageSizeSmall; lp.height = (int) mImageSizeSmall; mImage.setLayoutParams(lp); super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)); if (getMeasuredHeight() > MeasureSpec.getSize(heightMeasureSpec)) { UiUtils.hide(mImage); setPadding(getPaddingLeft(), (int) mPaddingNoImage, getPaddingRight(), getPaddingBottom()); } } super.onMeasure(widthMeasureSpec, heightMeasureSpec); } @Override protected void onConfigurationChanged(Configuration newConfig) { mOrientation = newConfig.orientation; } public void setContent(@DrawableRes int imageRes, @StringRes int titleRes, @StringRes int subtitleRes) { if (mImage != null) mImage.setImageResource(imageRes); if (mTitle != null) mTitle.setText(titleRes); if (mSubtitle != null) mSubtitle.setText(subtitleRes); } }
package com.imagepicker.utils; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Matrix; import android.media.ExifInterface; import android.media.MediaScannerConnection; import android.net.Uri; import android.os.Environment; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Log; import com.facebook.react.bridge.ReadableMap; import com.imagepicker.ImagePickerModule; import com.imagepicker.ResponseHelper; import com.imagepicker.media.ImageConfig; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.nio.channels.FileChannel; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.TimeZone; import java.util.UUID; import static com.imagepicker.ImagePickerModule.REQUEST_LAUNCH_IMAGE_CAPTURE; public class MediaUtils { public static @Nullable File createNewFile(@NonNull final Context reactContext, @NonNull final ReadableMap options, @NonNull final boolean forceLocal) { final String filename = new StringBuilder("image-") .append(UUID.randomUUID().toString()) .append(".jpg") .toString(); final File path = ReadableMapUtils.hasAndNotNullReadableMap(options, "storageOptions") && !forceLocal ? Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) : reactContext.getExternalFilesDir(Environment.DIRECTORY_PICTURES); File result = new File(path, filename); try { path.mkdirs(); result.createNewFile(); } catch (IOException e) { e.printStackTrace(); result = null; } return result; } /** * Create a resized image to fulfill the maxWidth/maxHeight, quality and rotation values * * @param context * @param options * @param imageConfig * @param initialWidth * @param initialHeight * @return updated ImageConfig */ public static @NonNull ImageConfig getResizedImage(@NonNull final Context context, @NonNull final ReadableMap options, @NonNull final ImageConfig imageConfig, int initialWidth, int initialHeight, final int requestCode) { BitmapFactory.Options imageOptions = new BitmapFactory.Options(); imageOptions.inScaled = false; imageOptions.inSampleSize = 1; if (imageConfig.maxWidth != 0 || imageConfig.maxHeight != 0) { while ((imageConfig.maxWidth == 0 || initialWidth > 2 * imageConfig.maxWidth) && (imageConfig.maxHeight == 0 || initialHeight > 2 * imageConfig.maxHeight)) { imageOptions.inSampleSize *= 2; initialHeight /= 2; initialWidth /= 2; } } Bitmap photo = BitmapFactory.decodeFile(imageConfig.original.getAbsolutePath(), imageOptions); if (photo == null) { return null; } ImageConfig result = imageConfig; Bitmap scaledPhoto = null; if (imageConfig.maxWidth == 0 || imageConfig.maxWidth > initialWidth) { result = result.withMaxWidth(initialWidth); } if (imageConfig.maxHeight == 0 || imageConfig.maxWidth > initialHeight) { result = result.withMaxHeight(initialHeight); } double widthRatio = (double) result.maxWidth / initialWidth; double heightRatio = (double) result.maxHeight / initialHeight; double ratio = (widthRatio < heightRatio) ? widthRatio : heightRatio; Matrix matrix = new Matrix(); matrix.postRotate(result.rotation); matrix.postScale((float) ratio, (float) ratio); ExifInterface exif; try { exif = new ExifInterface(result.original.getAbsolutePath()); int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 0); switch (orientation) { case 6: matrix.postRotate(90); break; case 3: matrix.postRotate(180); break; case 8: matrix.postRotate(270); break; } } catch (IOException e) { e.printStackTrace(); } scaledPhoto = Bitmap.createBitmap(photo, 0, 0, photo.getWidth(), photo.getHeight(), matrix, true); ByteArrayOutputStream bytes = new ByteArrayOutputStream(); scaledPhoto.compress(Bitmap.CompressFormat.JPEG, result.quality, bytes); final boolean forceLocal = requestCode == REQUEST_LAUNCH_IMAGE_CAPTURE; final File resized = createNewFile(context, options, !forceLocal); if (resized == null) { if (photo != null) { photo.recycle(); photo = null; } if (scaledPhoto != null) { scaledPhoto.recycle(); scaledPhoto = null; } return imageConfig; } result = result.withResizedFile(resized); FileOutputStream fos; try { fos = new FileOutputStream(result.resized); fos.write(bytes.toByteArray()); } catch (IOException e) { e.printStackTrace(); } if (photo != null) { photo.recycle(); photo = null; } if (scaledPhoto != null) { scaledPhoto.recycle(); scaledPhoto = null; } return result; } public static void removeUselessFiles(final int requestCode, @NonNull final ImageConfig imageConfig) { if (requestCode != ImagePickerModule.REQUEST_LAUNCH_IMAGE_CAPTURE) { return; } if (imageConfig.original != null && imageConfig.original.exists()) { imageConfig.original.delete(); } if (imageConfig.resized != null && imageConfig.resized.exists()) { imageConfig.resized.delete(); } } public static void fileScan(@Nullable final Context reactContext, @NonNull final String path) { if (reactContext == null) { return; } MediaScannerConnection.scanFile(reactContext, new String[] { path }, null, new MediaScannerConnection.OnScanCompletedListener() { public void onScanCompleted(String path, Uri uri) { Log.i("TAG", new StringBuilder("Finished scanning ").append(path).toString()); } }); } public static ReadExifResult readExifInterface(@NonNull ResponseHelper responseHelper, @NonNull final ImageConfig imageConfig) { ReadExifResult result; int currentRotation = 0; try { ExifInterface exif = new ExifInterface(imageConfig.original.getAbsolutePath()); // extract lat, long, and timestamp and add to the response float[] latlng = new float[2]; exif.getLatLong(latlng); float latitude = latlng[0]; float longitude = latlng[1]; if(latitude != 0f || longitude != 0f) { responseHelper.putDouble("latitude", latitude); responseHelper.putDouble("longitude", longitude); } final String timestamp = exif.getAttribute(ExifInterface.TAG_DATETIME); final SimpleDateFormat exifDatetimeFormat = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss"); final DateFormat isoFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); isoFormat.setTimeZone(TimeZone.getTimeZone("UTC")); try { final String isoFormatString = new StringBuilder(isoFormat.format(exifDatetimeFormat.parse(timestamp))) .append("Z").toString(); responseHelper.putString("timestamp", isoFormatString); } catch (Exception e) {} int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL); boolean isVertical = true; switch (orientation) { case ExifInterface.ORIENTATION_ROTATE_270: isVertical = false; currentRotation = 270; break; case ExifInterface.ORIENTATION_ROTATE_90: isVertical = false; currentRotation = 90; break; case ExifInterface.ORIENTATION_ROTATE_180: currentRotation = 180; break; } responseHelper.putInt("originalRotation", currentRotation); responseHelper.putBoolean("isVertical", isVertical); result = new ReadExifResult(currentRotation, null); } catch (IOException e) { e.printStackTrace(); result = new ReadExifResult(currentRotation, e); } return result; } public static @Nullable RolloutPhotoResult rolloutPhotoFromCamera(@NonNull final ImageConfig imageConfig) { RolloutPhotoResult result = null; final File oldFile = imageConfig.resized == null ? imageConfig.original: imageConfig.resized; final File newDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM); final File newFile = new File(newDir.getPath(), oldFile.getName()); try { moveFile(oldFile, newFile); ImageConfig newImageConfig; if (imageConfig.resized != null) { newImageConfig = imageConfig.withResizedFile(newFile); } else { newImageConfig = imageConfig.withOriginalFile(newFile); } result = new RolloutPhotoResult(newImageConfig, null); } catch (IOException e) { e.printStackTrace(); result = new RolloutPhotoResult(imageConfig, e); } return result; } /** * Move a file from one location to another. * * This is done via copy + deletion, because Android will throw an error * if you try to move a file across mount points, e.g. to the SD card. */ private static void moveFile(@NonNull final File oldFile, @NonNull final File newFile) throws IOException { FileChannel oldChannel = null; FileChannel newChannel = null; try { oldChannel = new FileInputStream(oldFile).getChannel(); newChannel = new FileOutputStream(newFile).getChannel(); oldChannel.transferTo(0, oldChannel.size(), newChannel); oldFile.delete(); } finally { try { if (oldChannel != null) oldChannel.close(); if (newChannel != null) newChannel.close(); } catch (IOException e) { e.printStackTrace(); } } } public static class RolloutPhotoResult { public final ImageConfig imageConfig; public final Throwable error; public RolloutPhotoResult(@NonNull final ImageConfig imageConfig, @Nullable final Throwable error) { this.imageConfig = imageConfig; this.error = error; } } public static class ReadExifResult { public final int currentRotation; public final Throwable error; public ReadExifResult(int currentRotation, @Nullable final Throwable error) { this.currentRotation = currentRotation; this.error = error; } } }
package org.jasig.portal.services; import java.io.File; import java.io.StringWriter; import java.io.PrintWriter; import java.io.FileInputStream; import java.util.Properties; import org.apache.log4j.Category; import org.apache.log4j.FileAppender; import org.apache.log4j.PatternLayout; import org.apache.log4j.Priority; import org.apache.log4j.Appender; import org.jasig.portal.GenericPortalBean; import org.jasig.portal.services.PortalFileAppender; /** * The Logger class is used to output messages to a log file. * The first call to a log method triggers an initialization which * renames old logs and creates a new log with a message stating the * current time and log level. The maximum number of backup log files * is specified as a member variable and can be set by calling * setMaxBackupLogFiles (). When calling a log method, it is necessary * to specify a log level which can be either NONE, SEVERE, ERROR, WARN, * INFO, or DEBUG (listed in order of decreasing severity). Log messages * will only be logged if their log level is the same or more severe than * the static member log level, which can be changed by calling setLogLevel(). * * @author Ken Weiner, kweiner@interactivebusiness.com * @author Bernie Durfee, bdurfee@interactivebusiness.com * @version $Revision$ */ public class LogService extends GenericPortalBean { // Log levels public static final int NONE = 0; public static final int SEVERE = 1; public static final int ERROR = 2; public static final int WARN = 3; public static final int INFO = 4; public static final int DEBUG = 5; private static int iLogLevelSetting = DEBUG; private static String sLogLevelSetting = "DEBUG"; private static final String sIllArgExMessage = "Log level must be NONE, SEVERE, ERROR, WARN, INFO, or DEBUG"; private static final String fs = File.separator; private static String sLogRelativePath = "logs"; private static boolean bInitialized = false; private static Category m_catFramework = null; private static PortalFileAppender m_logFile = null; // Maximum number of log files (Default is 10) private static int m_maxBackupIndex = 10; // Maximum size of each log file (Default is 500k) private static int m_maxFileSize = 500000; private static LogService m_logger; /** * Protected constructor to make this class a singleton */ protected void LogService () {} /** * Return an instance of logger */ public static LogService instance () { if (m_logger == null) { m_logger = new LogService(); } return (m_logger); } /** * Sets the current log level. Use one of the static integer members * of this class ranging from Logger.DEBUG to Logger.NONE. * The log level setting will determine the severity threshold of all log * messages. The more lenient the log level, the more log messages will be logged. * * @param a log level * * @todo The appender must be abstracted out so that other can be swapped in. */ public void setLogLevel (int iLogLevel) { if (!bInitialized) { initialize(); } if (iLogLevel <= DEBUG) { iLogLevelSetting = iLogLevel; } else { throw new IllegalArgumentException(sIllArgExMessage); } } /** * Gets the current log level setting * * @return the current log level setting */ public int getLogLevel () { return (iLogLevelSetting); } /** * Increments the old logs and creates a new log with the * current time and log level written at the top * * @todo If the file cannot be created, the log write should be pointed at stdout */ public void initialize () { String sPortalBaseDir = getPortalBaseDir(); File propertiesFile = null; try { // Load the portal properties file propertiesFile = new File(sPortalBaseDir + "/properties/portal.properties"); if (propertiesFile != null && propertiesFile.exists()) { Properties portalProperties = new Properties(); portalProperties.load(new FileInputStream(propertiesFile)); if (portalProperties.getProperty("logger.level") != null) { sLogLevelSetting = portalProperties.getProperty("logger.level"); } else { System.out.println("Defaulting to " + sLogLevelSetting + " for portal log level."); } if (portalProperties.getProperty("logger.maxLogFiles") != null) { m_maxBackupIndex = Integer.parseInt(portalProperties.getProperty("logger.maxLogFiles")); } else { System.out.println("Defaulting to " + m_maxBackupIndex + " for maximum number of portal log files."); } if (portalProperties.getProperty("logger.maxFileSize") != null) { m_maxFileSize = Integer.parseInt(portalProperties.getProperty("logger.maxFileSize")); } else { System.out.println("Defaulting to " + m_maxFileSize + " for maximum log file size."); } } else { System.out.println("The file portal.properties could not be loaded, using default properties."); } } catch (Exception e) { e.printStackTrace(); } try { if (sPortalBaseDir != null && new File(sPortalBaseDir).exists()) { PatternLayout patternLayout = new PatternLayout("%-5p %-23d{ISO8601} %m%n"); // Make sure the relative path ends with a seperator if (!sLogRelativePath.endsWith(File.separator)) { sLogRelativePath = sLogRelativePath + File.separator; } // Make sure the portal base directory path ends with a seperator if (!sPortalBaseDir.endsWith(File.separator)) { sPortalBaseDir = sPortalBaseDir + File.separator; } // Create the log file directory path String logFileDirectoryPath = sPortalBaseDir + sLogRelativePath; File logFileDirectory = new File(logFileDirectoryPath); // Make sure the log file directory exists if (!logFileDirectory.exists()) { if (!logFileDirectory.mkdir() || !logFileDirectory.exists() || !logFileDirectory.isDirectory()) { System.out.println("Could not create log file directory!"); } } // Create the file appender m_logFile = new PortalFileAppender(patternLayout, logFileDirectoryPath + "portal.log"); // Make sure to roll the logs to start fresh m_logFile.rollOver(); m_logFile.setMaxBackupIndex(m_maxBackupIndex); m_logFile.setMaxFileSize(m_maxFileSize); m_catFramework = Category.getRoot(); m_catFramework.addAppender(m_logFile); m_catFramework.setPriority(Priority.toPriority(sLogLevelSetting)); // Insures that initialization is only done once bInitialized = true; } else { System.out.println("Logger.initialize(): PortalBaseDir is not set or does not exist!"); } } catch (Exception e) { System.err.println("Problem writing to log."); e.printStackTrace(); } catch (Error er) { System.err.println("Problem writing to log."); er.printStackTrace(); } } /** * put your documentation comment here * @param iLogLevel * @param sMessage * @param ex */ public void log (int iLogLevel, String sMessage, Throwable ex) { log(iLogLevel, sMessage); log(iLogLevel, ex); } /** * Log a message at the specified log level * * @param Level at which to log the file * @param Message to send to the log * */ public void log (int iLogLevel, String sMessage) { try { if (!bInitialized) { initialize(); } switch (iLogLevel) { case NONE: return; case SEVERE: m_catFramework.fatal(sMessage); return; case ERROR: m_catFramework.error(sMessage); return; case WARN: m_catFramework.warn(sMessage); return; case INFO: m_catFramework.info(sMessage); return; case DEBUG: m_catFramework.debug(sMessage); return; default: throw new IllegalArgumentException(); } } catch (Exception e) { System.err.println("Problem writing to log."); e.printStackTrace(); } catch (Error er) { System.err.println("Problem writing to log."); er.printStackTrace(); } } /** * * @param the log level * @param an exception to log */ public void log (int iLogLevel, Throwable ex) { try { if (!bInitialized) { initialize(); } StringWriter stackTrace = new StringWriter(); ex.printStackTrace(new PrintWriter(stackTrace)); switch (iLogLevel) { case NONE: return; case SEVERE: m_catFramework.fatal(stackTrace.toString()); return; case ERROR: m_catFramework.error(stackTrace.toString()); return; case WARN: m_catFramework.warn(stackTrace.toString()); return; case INFO: m_catFramework.info(stackTrace.toString()); return; case DEBUG: m_catFramework.debug(stackTrace.toString()); return; default: throw new IllegalArgumentException(); } } catch (Exception e) { System.err.println("Problem writing to log."); e.printStackTrace(); } catch (Error er) { System.err.println("Problem writing to log."); er.printStackTrace(); } } private String getLogLevel (int iLogLevel) { String sLogLevel = null; switch (iLogLevel) { case NONE: sLogLevel = "NONE "; break; case SEVERE: sLogLevel = "SEVERE"; break; case ERROR: sLogLevel = "ERROR "; break; case WARN: sLogLevel = "WARN "; break; case INFO: sLogLevel = "INFO "; break; case DEBUG: sLogLevel = "DEBUG "; break; default: throw new IllegalArgumentException(); } return sLogLevel; } }
package ch.trvlr.trvlr.ui; import android.app.Activity; import android.content.Intent; import android.content.res.Configuration; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.NavigationView; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.view.Menu; import android.view.MenuItem; import android.view.SubMenu; import android.widget.FrameLayout; import android.widget.Toast; import com.android.volley.AuthFailureError; import com.android.volley.NetworkResponse; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.HttpHeaderParser; import com.android.volley.toolbox.JsonArrayRequest; import com.android.volley.toolbox.JsonObjectRequest; import com.android.volley.toolbox.StringRequest; import com.google.firebase.auth.FirebaseAuth; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.UnsupportedEncodingException; import java.util.HashMap; import java.util.LinkedList; import java.util.Map; import ch.trvlr.trvlr.AppController; import ch.trvlr.trvlr.R; import ch.trvlr.trvlr.model.Chat; import ch.trvlr.trvlr.model.Traveler; public class BaseDrawerActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{ public static final String TAG = BaseDrawerActivity.class.getSimpleName(); protected DrawerLayout mDrawerLayout; protected FrameLayout mFrameLayout; protected NavigationView mNavigationView; protected ActionBarDrawerToggle mDrawerToggle; protected Menu menu; protected int travelerId = -1; protected int chatId = -1; protected Traveler currentUser = null; protected AppController appController = null; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); super.setContentView(R.layout.activity_base_drawer); appController = (AppController) this.getApplicationContext(); mFrameLayout = (FrameLayout) findViewById(R.id.content_frame); getSupportActionBar().setDisplayHomeAsUpEnabled(true); mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); mDrawerToggle = new ActionBarDrawerToggle( this, mDrawerLayout, R.string.navigation_drawer_open, R.string.navigation_drawer_close ); mDrawerToggle.setDrawerIndicatorEnabled(true); mDrawerLayout.addDrawerListener(mDrawerToggle); mDrawerToggle.syncState(); mNavigationView = (NavigationView) findViewById(R.id.nav_view); mNavigationView.setNavigationItemSelectedListener(this); menu = mNavigationView.getMenu(); rebuildMenu(); loadTravelerId(); } @Override protected void onResume() { super.onResume(); appController.setCurrentActivity(this); rebuildMenu(); } @Override protected void onPause() { clearReferences(); super.onPause(); } @Override protected void onDestroy() { clearReferences(); super.onDestroy(); } private void loadTravelerId() { if (travelerId > 0) return; Map<String, String> params = new HashMap(); String firebaseId = ""; String firebaseToken = ""; try { firebaseId = FirebaseAuth.getInstance().getCurrentUser().getUid(); firebaseToken = FirebaseAuth.getInstance().getCurrentUser().getToken(false).getResult().getToken(); } catch (Exception e) { e.printStackTrace(); } params.put("firebaseId", firebaseId); params.put("firebaseToken", firebaseToken); JSONObject parameters = new JSONObject(params); AppController.getInstance().addToRequestQueue(new JsonObjectRequest( Request.Method.POST, "http://trvlr.ch:8080/api/traveler/auth", parameters, loadTravelerIdSuccess(), loadError() )); } private Response.Listener<JSONObject> loadTravelerIdSuccess() { return new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { try { travelerId = response.getInt("id"); currentUser = new Traveler( response.getInt("id"), response.getString("firstName"), response.getString("lastName"), response.getString("email"), response.getString("uid") ); // Make the current user for other activities available. AppController.getInstance().setCurrentUser(currentUser); // Load the private chats of this user. AppController.getInstance().addToRequestQueue(new JsonArrayRequest(Request.Method.GET, "http://trvlr.ch:8080/api/private-chats/list/" + currentUser.getId(), null, loadTravelerChatsSuccess(AppController.CHATROOM_TYPE_PRIVATE), loadError() )); // Load the public chats of this user. AppController.getInstance().addToRequestQueue(new JsonArrayRequest(Request.Method.GET, "http://trvlr.ch:8080/api/public-chats/list/" + currentUser.getId(), null, loadTravelerChatsSuccess(AppController.CHATROOM_TYPE_PUBLIC), loadError() )); } catch (JSONException e) { Toast.makeText(BaseDrawerActivity.this, TAG + ": " + e.getMessage(), Toast.LENGTH_SHORT).show(); } } }; } private Response.Listener<JSONArray> loadTravelerChatsSuccess(final int chatType) { return new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { try { if (response.length() == 0) { // TODO: check if empty json array is also response.length() == 0 // Toast.makeText(BaseDrawerActivity.this, "Can not chats (Type: " + chatType + ")", Toast.LENGTH_LONG).show(); } else { for (int i = 0; i < response.length(); i++) { Chat bo = null; if (chatType == AppController.CHATROOM_TYPE_PRIVATE) { JSONArray travelers = response.getJSONObject(i).getJSONArray("allTravelers"); if (travelers.length() > 1) { int uId1 = travelers.getJSONObject(0).getInt("id"); int uId2 = travelers.getJSONObject(1).getInt("id"); int indexToLoad = uId1 != currentUser.getId() ? 0 : 1; Traveler chatPartner = new Traveler( travelers.getJSONObject(indexToLoad).getInt("id"), travelers.getJSONObject(indexToLoad).getString("firstName"), travelers.getJSONObject(indexToLoad).getString("lastName"), travelers.getJSONObject(indexToLoad).getString("email"), travelers.getJSONObject(indexToLoad).getString("uid") ); bo = new Chat(response.getJSONObject(i).getInt("id"), chatPartner.getFullname(), chatPartner); } } else { String from = response.getJSONObject(i).getJSONObject("from").getString("name"); String to = response.getJSONObject(i).getJSONObject("to").getString("name"); bo = new Chat(response.getJSONObject(i).getInt("id"), from + " - " + to, Chat.CHATROOM_TYPE_PUBLIC); } if (bo != null) { AppController.getInstance().addChat(chatType, bo); } } rebuildMenu(); } } catch (JSONException e) { Toast.makeText(BaseDrawerActivity.this, TAG + ": " + e.getMessage(), Toast.LENGTH_SHORT).show(); } } }; } /** * Handle back button */ @Override public void onBackPressed() { if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) { mDrawerLayout.closeDrawer(GravityCompat.START); } else { Chat activeChat = appController.getCurrentActiveChat(); Chat activePublicChat = appController.getCurrentActivePublicChat(); Activity currentActivity = appController.getCurrentActivity(); String currentActivityClass = ""; if (currentActivity != null) { currentActivityClass = appController.getCurrentActivity().getLocalClassName(); } switch (currentActivityClass) { case "ui.ChatActivity": if (activeChat.getChatType() == AppController.CHATROOM_TYPE_PRIVATE && activePublicChat != null) { appController.setCurrentActiveChat(AppController.CHATROOM_TYPE_PRIVATE, null); appController.setCurrentActiveChat(AppController.CHATROOM_TYPE_PUBLIC, activePublicChat); startActivity(new Intent(getApplicationContext(), ChatActivity.class)); } else { appController.setCurrentActiveChat(AppController.CHATROOM_TYPE_PUBLIC, null); appController.setCurrentActiveChat(AppController.CHATROOM_TYPE_PRIVATE, null); startActivity(new Intent(getApplicationContext(), FindConnectionActivity.class)); } break; case "ui.ListPublicChatMembersActivity": if (activePublicChat != null) { appController.setCurrentActiveChat(AppController.CHATROOM_TYPE_PUBLIC, activePublicChat); startActivity(new Intent(getApplicationContext(), ChatActivity.class)); } else { appController.setCurrentActiveChat(AppController.CHATROOM_TYPE_PUBLIC, null); appController.setCurrentActiveChat(AppController.CHATROOM_TYPE_PRIVATE, null); startActivity(new Intent(getApplicationContext(), FindConnectionActivity.class)); } break; case "ui.FindConnectionActivity": logout(); break; default: appController.setCurrentActiveChat(AppController.CHATROOM_TYPE_PUBLIC, null); appController.setCurrentActiveChat(AppController.CHATROOM_TYPE_PRIVATE, null); startActivity(new Intent(getApplicationContext(), FindConnectionActivity.class)); break; } } } /** * Handle for navigation action * * @param item MenuItem * @return Boolean */ @Override public boolean onNavigationItemSelected(MenuItem item) { int id = item.getItemId(); if (item.isChecked()){ mDrawerLayout.closeDrawer(GravityCompat.START); return false; } uncheckItems(); // TODO maybe there's a better way... Intent i; Bundle b; switch (id) { case R.layout.activity_login: FirebaseAuth.getInstance().signOut(); startActivity(new Intent(getApplicationContext(), LoginActivity.class)); finish(); break; case R.layout.activity_findconn: appController.setCurrentActiveChat(AppController.CHATROOM_TYPE_PUBLIC, null); appController.setCurrentActiveChat(AppController.CHATROOM_TYPE_PRIVATE, null); startActivity(new Intent(getApplicationContext(), FindConnectionActivity.class)); break; case R.layout.activity_chat: i = new Intent(getApplicationContext(), ChatActivity.class); // Get the right bo of this chat room. Chat bo = ((AppController) getApplication()).getChat(item.getTitle().toString()); if (bo.isPublicChat()) { appController.setCurrentActivePublicChat(bo); appController.setCurrentActiveChatTypeToPublic(); } else { appController.setCurrentActivePrivateChat(bo); appController.setCurrentActiveChatTypeToPrivate(); } startActivity(i); break; default: Toast.makeText(BaseDrawerActivity.this, TAG + ": " + "Activity unavailable", Toast.LENGTH_SHORT).show(); } mDrawerLayout.closeDrawer(GravityCompat.START); return true; } private void uncheckItems() { Menu menu = mNavigationView.getMenu(); for (int i = 0; i < menu.size(); i++) menu.getItem(i).setChecked(false); } public Response.ErrorListener loadError() { return new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(BaseDrawerActivity.this, TAG + ": " + error.getMessage(), Toast.LENGTH_SHORT).show(); } }; } /** * Rebuild the options menu * * @param menu Menu * @return Boolean */ @Override public boolean onPrepareOptionsMenu(final Menu menu) { rebuildMenu(); return super.onCreateOptionsMenu(menu); } protected void rebuildMenu() { // Clear menu. menu.clear(); // Add default menu items. SubMenu startChattingMenu = menu.addSubMenu("Get started"); startChattingMenu.add(Menu.NONE, R.layout.activity_findconn, Menu.NONE, "Find connection"); // Add public chat menu items. SubMenu publicChatsMenu = menu.addSubMenu("Public chats"); LinkedList<Chat> publicChats = ((AppController) this.getApplication()).getPublicChats(); for (Chat bo : publicChats) { publicChatsMenu.add(Menu.NONE, R.layout.activity_chat, Menu.NONE, bo.getChatName()); } // Add private chat menu items. SubMenu privateChatsMenu = menu.addSubMenu("Private chats"); LinkedList<Chat> privateChats = ((AppController) this.getApplication()).getPrivateChats(); for (Chat bo : privateChats) { privateChatsMenu.add(Menu.NONE, R.layout.activity_chat, Menu.NONE, bo.getChatName()); } } /** * Handler after onCreate is completed * * This hook is used to sync the state of the navigation drawer * * @param savedInstanceState Bundle */ @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); mDrawerToggle.syncState(); } /** * Handler for configuration changes * * @param newConfig Configuration */ @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); mDrawerToggle.onConfigurationChanged(newConfig); } /** * Initialize options menu * * @param menu Menu * @return Boolean */ @Override public boolean onCreateOptionsMenu(final Menu menu) { getMenuInflater().inflate(R.menu.settings, menu); Chat activeChat = appController.getCurrentActiveChat(); Activity currentActivity = appController.getCurrentActivity(); String currentActivityClass = ""; if (currentActivity != null) { currentActivityClass = appController.getCurrentActivity().getLocalClassName(); } boolean isChat = currentActivityClass.equals("ui.ChatActivity"); boolean isPublicChat = isChat && activeChat.isPublicChat(); if (!isChat) { menu.removeItem(R.id.leave_chat_room); } if (!isPublicChat) { menu.removeItem(R.id.list_travelers); } return super.onCreateOptionsMenu(menu); } /** * Handler for options item action * * @param item MenuItem * @return Boolean */ @Override public boolean onOptionsItemSelected(MenuItem item) { Intent i; Bundle b; if (mDrawerToggle.onOptionsItemSelected(item)) { return true; } switch (item.getItemId()) { case R.id.list_travelers: i = new Intent(getApplicationContext(), ListPublicChatMembersActivity.class); b = new Bundle(); b.putInt("chatId", chatId); i.putExtras(b); startActivity(i); break; case R.id.logout: logout(); break; case R.id.leave_chat_room: leaveChat(); break; default: return super.onOptionsItemSelected(item); } return true; } private void leaveChat() { try { Chat bo = AppController.getInstance().getCurrentActiveChat(); String chat = bo.isPublicChat() ? "public-chats" : "private-chats"; int chatId = bo.getChatId(); final String json = new JSONObject().put("travelerId", currentUser.getId()).toString(); AppController.getInstance().addToRequestQueue(new StringRequest(Request.Method.POST, "http://trvlr.ch:8080/api/" + chat + "/" + chatId + "/leave", leaveChatSuccess(), loadError()) { @Override public String getBodyContentType() { return "application/json; charset=utf-8"; } @Override public byte[] getBody() throws AuthFailureError { try { return json == null ? null : json.getBytes("utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); return null; } } @Override protected Response<String> parseNetworkResponse(NetworkResponse response) { String responseString = ""; if (response != null) { responseString = String.valueOf(response.statusCode); } return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response)); } }); } catch (JSONException e) { e.printStackTrace(); } } private Response.Listener leaveChatSuccess() { return new Response.Listener() { @Override public void onResponse(Object response) { AppController controller = AppController.getInstance(); Chat bo = controller.getCurrentActiveChat(); controller.removeChat(bo.getChatId(), controller.getCurrentActiveChatType()); finish(); // Reset current active chat. controller.setCurrentActiveChat(bo.getChatType(), null); // Show find connection after leaving a chat room. startActivity(new Intent(getApplicationContext(), FindConnectionActivity.class)); } }; } protected void clearReferences() { Activity currentActivity = appController.getCurrentActivity(); if (this.equals(currentActivity)) { appController.setCurrentActivity(null); } } protected void logout() { FirebaseAuth.getInstance().signOut(); Intent intent = new Intent(getApplicationContext(), LoginActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(intent); finish(); } }
package com.expidev.gcmapp.http; import static com.expidev.gcmapp.BuildConfig.THEKEY_CLIENTID; import android.annotation.TargetApi; import android.content.Context; import android.content.SharedPreferences; import android.net.Uri; import android.os.Build; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.text.TextUtils; import android.util.Log; import android.util.Pair; import com.expidev.gcmapp.BuildConfig; import com.expidev.gcmapp.http.GmaApiClient.Session; import com.expidev.gcmapp.json.MinistryJsonParser; import com.expidev.gcmapp.model.Ministry; import com.expidev.gcmapp.utils.JsonStringReader; import org.apache.http.HttpStatus; import org.ccci.gto.android.common.api.AbstractTheKeyApi; import org.ccci.gto.android.common.api.ApiException; import org.ccci.gto.android.common.api.ApiSocketException; import org.ccci.gto.android.common.util.IOUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.io.InputStream; import java.net.HttpCookie; import java.net.HttpURLConnection; import java.net.URISyntaxException; import java.net.URL; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.net.ssl.HttpsURLConnection; import me.thekey.android.TheKey; import me.thekey.android.TheKeySocketException; import me.thekey.android.lib.TheKeyImpl; public class GmaApiClient extends AbstractTheKeyApi<AbstractTheKeyApi.Request<Session>, Session> { private final String TAG = getClass().getSimpleName(); private static final String MINISTRIES = "ministries"; private static final String TOKEN = "token"; private static final String TRAINING = "training"; private static final String PREF_NAME = "gcm_prefs"; private static final Object LOCK_INSTANCE = new Object(); private static GmaApiClient INSTANCE; private SharedPreferences preferences; private SharedPreferences.Editor prefEditor; public GmaApiClient(final Context context) { super(context, TheKeyImpl.getInstance(context, THEKEY_CLIENTID), BuildConfig.GCM_BASE_URI, "gcm_api_sessions"); preferences = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE); prefEditor = preferences.edit(); } public static GmaApiClient getInstance(final Context context) { synchronized (LOCK_INSTANCE) { if(INSTANCE == null) { INSTANCE = new GmaApiClient(context.getApplicationContext()); } } return INSTANCE; } @Override protected Session loadSession(@NonNull final SharedPreferences prefs, @NonNull final Request request) { return new Session(prefs, request.guid); } @Nullable @Override protected Session establishSession(@NonNull final Request<Session> request) throws ApiException { HttpURLConnection conn = null; try { final Pair<HttpURLConnection, String> tokenPair = this.getTokenInternal(false); if (tokenPair != null) { conn = tokenPair.first; // extract cookies // XXX: this won't be needed once Jon removes the cookie requirement from the API final Set<String> cookies = new HashSet<>(); for (final Map.Entry<String, List<String>> header : conn.getHeaderFields().entrySet()) { final String key = header.getKey(); if ("Set-Cookie".equalsIgnoreCase(key) || "Set-Cookie2".equals(key)) { for (final String value : header.getValue()) { for (final HttpCookie cookie : HttpCookie.parse(value)) { if (cookie != null) { cookies.add(cookie.toString()); } } } } } // create session object final JSONObject json = new JSONObject(IOUtils.readString(conn.getInputStream())); return new Session(json.optString("session_ticket", null), cookies, tokenPair.second); } } catch (final IOException e) { throw new ApiSocketException(e); } catch (final JSONException e) { Log.i(TAG, "invalid json for getToken", e); } finally { IOUtils.closeQuietly(conn); } // unable to get a session return null; } @Override protected void onPrepareUri(@NonNull final Uri.Builder uri, @NonNull final Request<Session> request) throws ApiException { super.onPrepareUri(uri, request); // append the session_token when using the session if (request.useSession && request.session != null) { uri.appendQueryParameter("token", request.session.id); } } @Override protected void onPrepareRequest(@NonNull final HttpURLConnection conn, @NonNull final Request<Session> request) throws ApiException, IOException { super.onPrepareRequest(conn, request); conn.setConnectTimeout(10000); conn.setReadTimeout(10000); // attach cookies when using the session // XXX: this should go away once we remove the cookie requirement on the API if (request.useSession && request.session != null) { conn.addRequestProperty("Cookie", TextUtils.join("; ", request.session.cookies)); } } private String getService() { return mBaseUri.buildUpon().appendPath(TOKEN).toString(); } @Nullable private Pair<HttpURLConnection, String> getTokenInternal(final boolean refresh) throws ApiException { HttpURLConnection conn = null; boolean successful = false; try { final TheKey.TicketAttributesPair ticket = mTheKey.getTicketAndAttributes(getService()); // issue request only if we have a ticket if (ticket != null && ticket.attributes.getGuid() != null) { // build request final Request<Session> request = new Request<>(TOKEN); request.accept = Request.MediaType.APPLICATION_JSON; request.params.add(param("st", ticket.ticket)); request.params.add(param("refresh", refresh)); request.useSession = false; // send request (tickets are one time use only, so we can't retry) conn = this.sendRequest(request, 0); // parse valid responses if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) { successful = true; return Pair.create(conn, ticket.attributes.getGuid()); } } } catch (final TheKeySocketException | IOException e) { throw new ApiSocketException(e); } finally { if (!successful) { IOUtils.closeQuietly(conn); } } // error retrieving token return null; } private HttpURLConnection prepareRequest(HttpURLConnection connection) { String cookie = preferences.getString("Cookie", ""); if (!cookie.isEmpty()) { Log.i(TAG, "Cookie added: " + cookie); connection.addRequestProperty("Cookie", cookie); } else { Log.w(TAG, "No Cookies found"); } return connection; } private HttpURLConnection processResponse(HttpURLConnection connection) throws IOException { if (connection.getHeaderFields() != null) { String headerName; StringBuilder stringBuilder = new StringBuilder(); for (int i = 1; (headerName = connection.getHeaderFieldKey(i)) != null; i++) { if (headerName.equals("Set-Cookie")) { String cookie = connection.getHeaderField(i); cookie = cookie.split("\\;")[0] + "; "; stringBuilder.append(cookie); } } // cookie store is not retrieving cookie so it will be saved to preferences if (!stringBuilder.toString().isEmpty()) { prefEditor.putString("Cookie", stringBuilder.toString()); prefEditor.apply(); } } return connection; } @Nullable public JSONObject authorizeUser() { HttpURLConnection conn = null; try { final Pair<HttpURLConnection, String> tokenPair = this.getTokenInternal(true); if (tokenPair != null) { conn = tokenPair.first; return new JSONObject(IOUtils.readString(conn.getInputStream())); } } catch (Exception e) { Log.e(TAG, e.getMessage(), e); } finally { IOUtils.closeQuietly(conn); } return null; } public List<Ministry> getAllMinistries(String sessionToken) { String reason; String urlString = BuildConfig.GCM_BASE_URI + MINISTRIES + "?token=" + sessionToken; try { String json = httpGet(new URL(urlString)); if(json == null) { Log.e(TAG, "Failed to retrieve ministries, most likely cause is a bad session ticket"); return null; } else { if(json.startsWith("[")) { JSONArray jsonArray = new JSONArray(json); return MinistryJsonParser.parseMinistriesJson(jsonArray); } else { JSONObject jsonObject = new JSONObject(json); reason = jsonObject.optString("reason"); Log.e(TAG, reason); return null; } } } catch(Exception e) { reason = e.getMessage(); Log.e(TAG, "Problem occurred while retrieving ministries: " + reason); return null; } } public JSONArray searchTraining(String ministryId, String mcc, String sessionTicket) { try { String urlString = BuildConfig.GCM_BASE_URI + TRAINING + "?token=" + sessionTicket + "&ministry_id=" + ministryId + "&mcc=" + mcc; Log.i(TAG, "Url: " + urlString); URL url = new URL(urlString); return new JSONArray(httpGet(url)); } catch (Exception e) { Log.e(TAG, e.getMessage(), e); } return null; } public JSONArray searchMeasurements(String ministryId, String mcc, String period, String sessionTicket) { try { String urlString = BuildConfig.GCM_BASE_URI + "measurements" + "?token=" + sessionTicket + "&ministry_id=" + ministryId + "&mcc=" + mcc; if(period != null) { urlString += "&period=" + period; } Log.i(TAG, "Url: " + urlString); return new JSONArray(httpGet(new URL(urlString))); } catch(Exception e) { Log.e(TAG, e.getMessage(), e); } return null; } public JSONObject getDetailsForMeasurement( String measurementId, String sessionTicket, String ministryId, String mcc, String period) { try { String urlString = BuildConfig.GCM_BASE_URI + "measurements/" + measurementId + "?token=" + sessionTicket + "&ministry_id=" + ministryId + "&mcc=" + mcc; if(period != null) { urlString += "&period=" + period; } Log.i(TAG, "Url: " + urlString); return new JSONObject(httpGet(new URL(urlString))); } catch(Exception e) { Log.e(TAG, e.getMessage(), e); } return null; } private String httpGet(URL url) throws IOException, JSONException, URISyntaxException { HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); prepareRequest(connection); connection.setReadTimeout(10000); connection.setConnectTimeout(10000); connection.connect(); processResponse(connection); if (connection.getResponseCode() == HttpStatus.SC_OK) { InputStream inputStream = connection.getInputStream(); if (inputStream != null) { String jsonAsString = JsonStringReader.readFully(inputStream, "UTF-8"); Log.i(TAG, jsonAsString); // instead of returning a JSONObject, a string will be returned. This is // because some endpoints return an object and some return an array. return jsonAsString; } } else { Log.d(TAG, "Status: " + connection.getResponseCode()); } return null; } protected static class Session extends AbstractTheKeyApi.Session { @NonNull final Set<String> cookies; Session(@Nullable final String id, @Nullable final Collection<String> cookies, @NonNull final String guid) { super(id, guid); this.cookies = Collections.unmodifiableSet(new HashSet<>(cookies)); } @TargetApi(Build.VERSION_CODES.HONEYCOMB) Session(@NonNull final SharedPreferences prefs, @NonNull final String guid) { super(prefs, guid); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { this.cookies = Collections.unmodifiableSet(new HashSet<>( prefs.getStringSet(this.getPrefAttrName("cookies"), Collections.<String>emptySet()))); } else { // work around missing getStringSet final Set<String> cookies = new HashSet<>(); try { final JSONArray json = new JSONArray(prefs.getString(this.getPrefAttrName("cookies"), null)); for (int i = 0; i < json.length(); i++) { cookies.add(json.getString(i)); } } catch (final JSONException ignored) { } this.cookies = Collections.unmodifiableSet(cookies); } } @Override @TargetApi(Build.VERSION_CODES.HONEYCOMB) protected void save(@NonNull final SharedPreferences.Editor prefs) { super.save(prefs); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { prefs.putStringSet(this.getPrefAttrName("cookies"), this.cookies); } else { // work around missing putStringSet prefs.putString(this.getPrefAttrName("cookies"), new JSONArray(this.cookies).toString()); } } @Override protected void delete(@NonNull SharedPreferences.Editor prefs) { super.delete(prefs); prefs.remove(this.getPrefAttrName("cookies")); } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final Session that = (Session) o; return super.equals(o) && this.cookies.equals(that.cookies); } @Override protected boolean isValid() { return super.isValid() && this.cookies.size() > 0; } } }